clang 19.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
14#include "clang/AST/Decl.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/Template.h"
40#include "llvm/ADT/SmallBitVector.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/StringExtras.h"
43
44#include <iterator>
45#include <optional>
46using namespace clang;
47using namespace sema;
48
49// Exported for use by Parser.
52 unsigned N) {
53 if (!N) return SourceRange();
54 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
55}
56
57unsigned Sema::getTemplateDepth(Scope *S) const {
58 unsigned Depth = 0;
59
60 // Each template parameter scope represents one level of template parameter
61 // depth.
62 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
63 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
64 ++Depth;
65 }
66
67 // Note that there are template parameters with the given depth.
68 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
69
70 // Look for parameters of an enclosing generic lambda. We don't create a
71 // template parameter scope for these.
73 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
74 if (!LSI->TemplateParams.empty()) {
75 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
76 break;
77 }
78 if (LSI->GLTemplateParameterList) {
79 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
80 break;
81 }
82 }
83 }
84
85 // Look for parameters of an enclosing terse function template. We don't
86 // create a template parameter scope for these either.
87 for (const InventedTemplateParameterInfo &Info :
89 if (!Info.TemplateParams.empty()) {
90 ParamsAtDepth(Info.AutoTemplateParameterDepth);
91 break;
92 }
93 }
94
95 return Depth;
96}
97
98/// \brief Determine whether the declaration found is acceptable as the name
99/// of a template and, if so, return that template declaration. Otherwise,
100/// returns null.
101///
102/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
103/// is true. In all other cases it will return a TemplateDecl (or null).
105 bool AllowFunctionTemplates,
106 bool AllowDependent) {
107 D = D->getUnderlyingDecl();
108
109 if (isa<TemplateDecl>(D)) {
110 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
111 return nullptr;
112
113 return D;
114 }
115
116 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
117 // C++ [temp.local]p1:
118 // Like normal (non-template) classes, class templates have an
119 // injected-class-name (Clause 9). The injected-class-name
120 // can be used with or without a template-argument-list. When
121 // it is used without a template-argument-list, it is
122 // equivalent to the injected-class-name followed by the
123 // template-parameters of the class template enclosed in
124 // <>. When it is used with a template-argument-list, it
125 // refers to the specified class template specialization,
126 // which could be the current specialization or another
127 // specialization.
128 if (Record->isInjectedClassName()) {
129 Record = cast<CXXRecordDecl>(Record->getDeclContext());
130 if (Record->getDescribedClassTemplate())
131 return Record->getDescribedClassTemplate();
132
133 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
134 return Spec->getSpecializedTemplate();
135 }
136
137 return nullptr;
138 }
139
140 // 'using Dependent::foo;' can resolve to a template name.
141 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
142 // injected-class-name).
143 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
144 return D;
145
146 return nullptr;
147}
148
150 bool AllowFunctionTemplates,
151 bool AllowDependent) {
152 LookupResult::Filter filter = R.makeFilter();
153 while (filter.hasNext()) {
154 NamedDecl *Orig = filter.next();
155 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
156 filter.erase();
157 }
158 filter.done();
159}
160
162 bool AllowFunctionTemplates,
163 bool AllowDependent,
164 bool AllowNonTemplateFunctions) {
165 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
166 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
167 return true;
168 if (AllowNonTemplateFunctions &&
169 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
170 return true;
171 }
172
173 return false;
174}
175
177 CXXScopeSpec &SS,
178 bool hasTemplateKeyword,
179 const UnqualifiedId &Name,
180 ParsedType ObjectTypePtr,
181 bool EnteringContext,
182 TemplateTy &TemplateResult,
183 bool &MemberOfUnknownSpecialization,
184 bool Disambiguation) {
185 assert(getLangOpts().CPlusPlus && "No template names in C!");
186
187 DeclarationName TName;
188 MemberOfUnknownSpecialization = false;
189
190 switch (Name.getKind()) {
192 TName = DeclarationName(Name.Identifier);
193 break;
194
197 Name.OperatorFunctionId.Operator);
198 break;
199
201 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
202 break;
203
204 default:
205 return TNK_Non_template;
206 }
207
208 QualType ObjectType = ObjectTypePtr.get();
209
210 AssumedTemplateKind AssumedTemplate;
211 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
212 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
213 /*RequiredTemplate=*/SourceLocation(),
214 &AssumedTemplate,
215 /*AllowTypoCorrection=*/!Disambiguation))
216 return TNK_Non_template;
217 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
218
219 if (AssumedTemplate != AssumedTemplateKind::None) {
220 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
221 // Let the parser know whether we found nothing or found functions; if we
222 // found nothing, we want to more carefully check whether this is actually
223 // a function template name versus some other kind of undeclared identifier.
224 return AssumedTemplate == AssumedTemplateKind::FoundNothing
227 }
228
229 if (R.empty())
230 return TNK_Non_template;
231
232 NamedDecl *D = nullptr;
233 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
234 if (R.isAmbiguous()) {
235 // If we got an ambiguity involving a non-function template, treat this
236 // as a template name, and pick an arbitrary template for error recovery.
237 bool AnyFunctionTemplates = false;
238 for (NamedDecl *FoundD : R) {
239 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
240 if (isa<FunctionTemplateDecl>(FoundTemplate))
241 AnyFunctionTemplates = true;
242 else {
243 D = FoundTemplate;
244 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
245 break;
246 }
247 }
248 }
249
250 // If we didn't find any templates at all, this isn't a template name.
251 // Leave the ambiguity for a later lookup to diagnose.
252 if (!D && !AnyFunctionTemplates) {
253 R.suppressDiagnostics();
254 return TNK_Non_template;
255 }
256
257 // If the only templates were function templates, filter out the rest.
258 // We'll diagnose the ambiguity later.
259 if (!D)
261 }
262
263 // At this point, we have either picked a single template name declaration D
264 // or we have a non-empty set of results R containing either one template name
265 // declaration or a set of function templates.
266
267 TemplateName Template;
268 TemplateNameKind TemplateKind;
269
270 unsigned ResultCount = R.end() - R.begin();
271 if (!D && ResultCount > 1) {
272 // We assume that we'll preserve the qualifier from a function
273 // template name in other ways.
274 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
275 TemplateKind = TNK_Function_template;
276
277 // We'll do this lookup again later.
279 } else {
280 if (!D) {
282 assert(D && "unambiguous result is not a template name");
283 }
284
285 if (isa<UnresolvedUsingValueDecl>(D)) {
286 // We don't yet know whether this is a template-name or not.
287 MemberOfUnknownSpecialization = true;
288 return TNK_Non_template;
289 }
290
291 TemplateDecl *TD = cast<TemplateDecl>(D);
292 Template =
293 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
294 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
295 if (SS.isSet() && !SS.isInvalid()) {
296 NestedNameSpecifier *Qualifier = SS.getScopeRep();
297 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
298 Template);
299 }
300
301 if (isa<FunctionTemplateDecl>(TD)) {
302 TemplateKind = TNK_Function_template;
303
304 // We'll do this lookup again later.
306 } else {
307 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
308 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
309 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
310 TemplateKind =
311 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
312 isa<ConceptDecl>(TD) ? TNK_Concept_template :
314 }
315 }
316
317 TemplateResult = TemplateTy::make(Template);
318 return TemplateKind;
319}
320
322 SourceLocation NameLoc, CXXScopeSpec &SS,
323 ParsedTemplateTy *Template /*=nullptr*/) {
324 // We could use redeclaration lookup here, but we don't need to: the
325 // syntactic form of a deduction guide is enough to identify it even
326 // if we can't look up the template name at all.
327 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
328 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
329 /*EnteringContext*/ false))
330 return false;
331
332 if (R.empty()) return false;
333 if (R.isAmbiguous()) {
334 // FIXME: Diagnose an ambiguity if we find at least one template.
336 return false;
337 }
338
339 // We only treat template-names that name type templates as valid deduction
340 // guide names.
342 if (!TD || !getAsTypeTemplateDecl(TD))
343 return false;
344
345 if (Template)
346 *Template = TemplateTy::make(TemplateName(TD));
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) {
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() ||
598 OuterTemplate->getCanonicalDecl()) {
599 Diag(Found.getNameLoc(),
600 diag::ext_nested_name_member_ref_lookup_ambiguous)
601 << Found.getLookupName()
602 << ObjectType;
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
720/// ActOnDependentIdExpression - Handle a dependent id-expression that
721/// was just parsed. This is only possible with an explicit scope
722/// specifier naming a dependent type.
725 SourceLocation TemplateKWLoc,
726 const DeclarationNameInfo &NameInfo,
727 bool isAddressOfOperand,
728 const TemplateArgumentListInfo *TemplateArgs) {
730
731 // C++11 [expr.prim.general]p12:
732 // An id-expression that denotes a non-static data member or non-static
733 // member function of a class can only be used:
734 // (...)
735 // - if that id-expression denotes a non-static data member and it
736 // appears in an unevaluated operand.
737 //
738 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
739 // CXXDependentScopeMemberExpr. The former can instantiate to either
740 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
741 // always a MemberExpr.
742 bool MightBeCxx11UnevalField =
743 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
744
745 // Check if the nested name specifier is an enum type.
746 bool IsEnum = false;
747 if (NestedNameSpecifier *NNS = SS.getScopeRep())
748 IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
749
750 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
751 isa<CXXMethodDecl>(DC) &&
752 cast<CXXMethodDecl>(DC)->isImplicitObjectMemberFunction()) {
753 QualType ThisType =
754 cast<CXXMethodDecl>(DC)->getThisType().getNonReferenceType();
755
756 // Since the 'this' expression is synthesized, we don't need to
757 // perform the double-lookup check.
758 NamedDecl *FirstQualifierInScope = nullptr;
759
761 Context, /*This=*/nullptr, ThisType,
762 /*IsArrow=*/!Context.getLangOpts().HLSL,
763 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
764 FirstQualifierInScope, NameInfo, TemplateArgs);
765 }
766
767 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
768}
769
772 SourceLocation TemplateKWLoc,
773 const DeclarationNameInfo &NameInfo,
774 const TemplateArgumentListInfo *TemplateArgs) {
775 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
777 if (!QualifierLoc)
778 return ExprError();
779
781 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
782}
783
784
785/// Determine whether we would be unable to instantiate this template (because
786/// it either has no definition, or is in the process of being instantiated).
788 NamedDecl *Instantiation,
789 bool InstantiatedFromMember,
790 const NamedDecl *Pattern,
791 const NamedDecl *PatternDef,
793 bool Complain /*= true*/) {
794 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
795 isa<VarDecl>(Instantiation));
796
797 bool IsEntityBeingDefined = false;
798 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
799 IsEntityBeingDefined = TD->isBeingDefined();
800
801 if (PatternDef && !IsEntityBeingDefined) {
802 NamedDecl *SuggestedDef = nullptr;
803 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
804 &SuggestedDef,
805 /*OnlyNeedComplete*/ false)) {
806 // If we're allowed to diagnose this and recover, do so.
807 bool Recover = Complain && !isSFINAEContext();
808 if (Complain)
809 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
811 return !Recover;
812 }
813 return false;
814 }
815
816 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
817 return true;
818
819 QualType InstantiationTy;
820 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
821 InstantiationTy = Context.getTypeDeclType(TD);
822 if (PatternDef) {
823 Diag(PointOfInstantiation,
824 diag::err_template_instantiate_within_definition)
825 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
826 << InstantiationTy;
827 // Not much point in noting the template declaration here, since
828 // we're lexically inside it.
829 Instantiation->setInvalidDecl();
830 } else if (InstantiatedFromMember) {
831 if (isa<FunctionDecl>(Instantiation)) {
832 Diag(PointOfInstantiation,
833 diag::err_explicit_instantiation_undefined_member)
834 << /*member function*/ 1 << Instantiation->getDeclName()
835 << Instantiation->getDeclContext();
836 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
837 } else {
838 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
839 Diag(PointOfInstantiation,
840 diag::err_implicit_instantiate_member_undefined)
841 << InstantiationTy;
842 Diag(Pattern->getLocation(), diag::note_member_declared_at);
843 }
844 } else {
845 if (isa<FunctionDecl>(Instantiation)) {
846 Diag(PointOfInstantiation,
847 diag::err_explicit_instantiation_undefined_func_template)
848 << Pattern;
849 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
850 } else if (isa<TagDecl>(Instantiation)) {
851 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
852 << (TSK != TSK_ImplicitInstantiation)
853 << InstantiationTy;
854 NoteTemplateLocation(*Pattern);
855 } else {
856 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
857 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
858 Diag(PointOfInstantiation,
859 diag::err_explicit_instantiation_undefined_var_template)
860 << Instantiation;
861 Instantiation->setInvalidDecl();
862 } else
863 Diag(PointOfInstantiation,
864 diag::err_explicit_instantiation_undefined_member)
865 << /*static data member*/ 2 << Instantiation->getDeclName()
866 << Instantiation->getDeclContext();
867 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
868 }
869 }
870
871 // In general, Instantiation isn't marked invalid to get more than one
872 // error for multiple undefined instantiations. But the code that does
873 // explicit declaration -> explicit definition conversion can't handle
874 // invalid declarations, so mark as invalid in that case.
876 Instantiation->setInvalidDecl();
877 return true;
878}
879
881 bool SupportedForCompatibility) {
882 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
883
884 // C++23 [temp.local]p6:
885 // The name of a template-parameter shall not be bound to any following.
886 // declaration whose locus is contained by the scope to which the
887 // template-parameter belongs.
888 //
889 // When MSVC compatibility is enabled, the diagnostic is always a warning
890 // by default. Otherwise, it an error unless SupportedForCompatibility is
891 // true, in which case it is a default-to-error warning.
892 unsigned DiagId =
893 getLangOpts().MSVCCompat
894 ? diag::ext_template_param_shadow
895 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
896 : diag::err_template_param_shadow);
897 const auto *ND = cast<NamedDecl>(PrevDecl);
898 Diag(Loc, DiagId) << ND->getDeclName();
900}
901
902/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
903/// the parameter D to reference the templated declaration and return a pointer
904/// to the template declaration. Otherwise, do nothing to D and return null.
906 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
907 D = Temp->getTemplatedDecl();
908 return Temp;
909 }
910 return nullptr;
911}
912
914 SourceLocation EllipsisLoc) const {
915 assert(Kind == Template &&
916 "Only template template arguments can be pack expansions here");
917 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
918 "Template template argument pack expansion without packs");
920 Result.EllipsisLoc = EllipsisLoc;
921 return Result;
922}
923
925 const ParsedTemplateArgument &Arg) {
926
927 switch (Arg.getKind()) {
929 TypeSourceInfo *DI;
930 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
931 if (!DI)
932 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
934 }
935
937 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
939 }
940
942 TemplateName Template = Arg.getAsTemplate().get();
943 TemplateArgument TArg;
944 if (Arg.getEllipsisLoc().isValid())
945 TArg = TemplateArgument(Template, std::optional<unsigned int>());
946 else
947 TArg = Template;
948 return TemplateArgumentLoc(
949 SemaRef.Context, TArg,
951 Arg.getLocation(), Arg.getEllipsisLoc());
952 }
953 }
954
955 llvm_unreachable("Unhandled parsed template argument");
956}
957
958/// Translates template arguments as provided by the parser
959/// into template arguments used by semantic analysis.
961 TemplateArgumentListInfo &TemplateArgs) {
962 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
963 TemplateArgs.addArgument(translateTemplateArgument(*this,
964 TemplateArgsIn[I]));
965}
966
969 const IdentifierInfo *Name) {
970 NamedDecl *PrevDecl =
972 RedeclarationKind::ForVisibleRedeclaration);
973 if (PrevDecl && PrevDecl->isTemplateParameter())
974 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
975}
976
977/// Convert a parsed type into a parsed template argument. This is mostly
978/// trivial, except that we may have parsed a C++17 deduced class template
979/// specialization type, in which case we should form a template template
980/// argument instead of a type template argument.
982 TypeSourceInfo *TInfo;
984 if (T.isNull())
985 return ParsedTemplateArgument();
986 assert(TInfo && "template argument with no location");
987
988 // If we might have formed a deduced template specialization type, convert
989 // it to a template template argument.
990 if (getLangOpts().CPlusPlus17) {
991 TypeLoc TL = TInfo->getTypeLoc();
992 SourceLocation EllipsisLoc;
993 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
994 EllipsisLoc = PET.getEllipsisLoc();
995 TL = PET.getPatternLoc();
996 }
997
998 CXXScopeSpec SS;
999 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
1000 SS.Adopt(ET.getQualifierLoc());
1001 TL = ET.getNamedTypeLoc();
1002 }
1003
1004 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1005 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1006 if (SS.isSet())
1008 /*HasTemplateKeyword=*/false,
1009 Name);
1011 DTST.getTemplateNameLoc());
1012 if (EllipsisLoc.isValid())
1013 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1014 return Result;
1015 }
1016 }
1017
1018 // This is a normal type template argument. Note, if the type template
1019 // argument is an injected-class-name for a template, it has a dual nature
1020 // and can be used as either a type or a template. We handle that in
1021 // convertTypeTemplateArgumentToTemplate.
1024 TInfo->getTypeLoc().getBeginLoc());
1025}
1026
1027/// ActOnTypeParameter - Called when a C++ template type parameter
1028/// (e.g., "typename T") has been parsed. Typename specifies whether
1029/// the keyword "typename" was used to declare the type parameter
1030/// (otherwise, "class" was used), and KeyLoc is the location of the
1031/// "class" or "typename" keyword. ParamName is the name of the
1032/// parameter (NULL indicates an unnamed template parameter) and
1033/// ParamNameLoc is the location of the parameter name (if any).
1034/// If the type parameter has a default argument, it will be added
1035/// later via ActOnTypeParameterDefault.
1037 SourceLocation EllipsisLoc,
1038 SourceLocation KeyLoc,
1039 IdentifierInfo *ParamName,
1040 SourceLocation ParamNameLoc,
1041 unsigned Depth, unsigned Position,
1042 SourceLocation EqualLoc,
1043 ParsedType DefaultArg,
1044 bool HasTypeConstraint) {
1045 assert(S->isTemplateParamScope() &&
1046 "Template type parameter not in template parameter scope!");
1047
1048 bool IsParameterPack = EllipsisLoc.isValid();
1051 KeyLoc, ParamNameLoc, Depth, Position,
1052 ParamName, Typename, IsParameterPack,
1053 HasTypeConstraint);
1054 Param->setAccess(AS_public);
1055
1056 if (Param->isParameterPack())
1057 if (auto *LSI = getEnclosingLambda())
1058 LSI->LocalPacks.push_back(Param);
1059
1060 if (ParamName) {
1061 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1062
1063 // Add the template parameter into the current scope.
1064 S->AddDecl(Param);
1065 IdResolver.AddDecl(Param);
1066 }
1067
1068 // C++0x [temp.param]p9:
1069 // A default template-argument may be specified for any kind of
1070 // template-parameter that is not a template parameter pack.
1071 if (DefaultArg && IsParameterPack) {
1072 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1073 DefaultArg = nullptr;
1074 }
1075
1076 // Handle the default argument, if provided.
1077 if (DefaultArg) {
1078 TypeSourceInfo *DefaultTInfo;
1079 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1080
1081 assert(DefaultTInfo && "expected source information for type");
1082
1083 // Check for unexpanded parameter packs.
1084 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1086 return Param;
1087
1088 // Check the template argument itself.
1089 if (CheckTemplateArgument(DefaultTInfo)) {
1090 Param->setInvalidDecl();
1091 return Param;
1092 }
1093
1094 Param->setDefaultArgument(DefaultTInfo);
1095 }
1096
1097 return Param;
1098}
1099
1100/// Convert the parser's template argument list representation into our form.
1103 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1104 TemplateId.RAngleLoc);
1105 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1106 TemplateId.NumArgs);
1107 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1108 return TemplateArgs;
1109}
1110
1112
1113 TemplateName TN = TypeConstr->Template.get();
1114 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1115
1116 // C++2a [temp.param]p4:
1117 // [...] The concept designated by a type-constraint shall be a type
1118 // concept ([temp.concept]).
1119 if (!CD->isTypeConcept()) {
1120 Diag(TypeConstr->TemplateNameLoc,
1121 diag::err_type_constraint_non_type_concept);
1122 return true;
1123 }
1124
1125 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1126
1127 if (!WereArgsSpecified &&
1129 Diag(TypeConstr->TemplateNameLoc,
1130 diag::err_type_constraint_missing_arguments)
1131 << CD;
1132 return true;
1133 }
1134 return false;
1135}
1136
1138 TemplateIdAnnotation *TypeConstr,
1139 TemplateTypeParmDecl *ConstrainedParameter,
1140 SourceLocation EllipsisLoc) {
1141 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1142 false);
1143}
1144
1146 TemplateIdAnnotation *TypeConstr,
1147 TemplateTypeParmDecl *ConstrainedParameter,
1148 SourceLocation EllipsisLoc,
1149 bool AllowUnexpandedPack) {
1150
1151 if (CheckTypeConstraint(TypeConstr))
1152 return true;
1153
1154 TemplateName TN = TypeConstr->Template.get();
1155 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1157
1158 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1159 TypeConstr->TemplateNameLoc);
1160
1161 TemplateArgumentListInfo TemplateArgs;
1162 if (TypeConstr->LAngleLoc.isValid()) {
1163 TemplateArgs =
1164 makeTemplateArgumentListInfo(*this, *TypeConstr);
1165
1166 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1167 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1169 return true;
1170 }
1171 }
1172 }
1173 return AttachTypeConstraint(
1175 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1176 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1177 ConstrainedParameter, EllipsisLoc);
1178}
1179
1180template <typename ArgumentLocAppender>
1183 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1184 SourceLocation RAngleLoc, QualType ConstrainedType,
1185 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1186 SourceLocation EllipsisLoc) {
1187
1188 TemplateArgumentListInfo ConstraintArgs;
1189 ConstraintArgs.addArgument(
1191 /*NTTPType=*/QualType(), ParamNameLoc));
1192
1193 ConstraintArgs.setRAngleLoc(RAngleLoc);
1194 ConstraintArgs.setLAngleLoc(LAngleLoc);
1195 Appender(ConstraintArgs);
1196
1197 // C++2a [temp.param]p4:
1198 // [...] This constraint-expression E is called the immediately-declared
1199 // constraint of T. [...]
1200 CXXScopeSpec SS;
1201 SS.Adopt(NS);
1202 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1203 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1204 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1205 &ConstraintArgs);
1206 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1207 return ImmediatelyDeclaredConstraint;
1208
1209 // C++2a [temp.param]p4:
1210 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1211 //
1212 // We have the following case:
1213 //
1214 // template<typename T> concept C1 = true;
1215 // template<C1... T> struct s1;
1216 //
1217 // The constraint: (C1<T> && ...)
1218 //
1219 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1220 // any unqualified lookups for 'operator&&' here.
1221 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1222 /*LParenLoc=*/SourceLocation(),
1223 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1224 EllipsisLoc, /*RHS=*/nullptr,
1225 /*RParenLoc=*/SourceLocation(),
1226 /*NumExpansions=*/std::nullopt);
1227}
1228
1229/// Attach a type-constraint to a template parameter.
1230/// \returns true if an error occurred. This can happen if the
1231/// immediately-declared constraint could not be formed (e.g. incorrect number
1232/// of arguments for the named concept).
1234 DeclarationNameInfo NameInfo,
1235 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1236 const TemplateArgumentListInfo *TemplateArgs,
1237 TemplateTypeParmDecl *ConstrainedParameter,
1238 SourceLocation EllipsisLoc) {
1239 // C++2a [temp.param]p4:
1240 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1241 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1242 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1244 *TemplateArgs) : nullptr;
1245
1246 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1247
1248 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1249 *this, NS, NameInfo, NamedConcept, FoundDecl,
1250 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1251 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1252 ParamAsArgument, ConstrainedParameter->getLocation(),
1253 [&](TemplateArgumentListInfo &ConstraintArgs) {
1254 if (TemplateArgs)
1255 for (const auto &ArgLoc : TemplateArgs->arguments())
1256 ConstraintArgs.addArgument(ArgLoc);
1257 },
1258 EllipsisLoc);
1259 if (ImmediatelyDeclaredConstraint.isInvalid())
1260 return true;
1261
1262 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1263 /*TemplateKWLoc=*/SourceLocation{},
1264 /*ConceptNameInfo=*/NameInfo,
1265 /*FoundDecl=*/FoundDecl,
1266 /*NamedConcept=*/NamedConcept,
1267 /*ArgsWritten=*/ArgsAsWritten);
1268 ConstrainedParameter->setTypeConstraint(CL,
1269 ImmediatelyDeclaredConstraint.get());
1270 return false;
1271}
1272
1274 NonTypeTemplateParmDecl *NewConstrainedParm,
1275 NonTypeTemplateParmDecl *OrigConstrainedParm,
1276 SourceLocation EllipsisLoc) {
1277 if (NewConstrainedParm->getType() != TL.getType() ||
1279 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1280 diag::err_unsupported_placeholder_constraint)
1281 << NewConstrainedParm->getTypeSourceInfo()
1282 ->getTypeLoc()
1283 .getSourceRange();
1284 return true;
1285 }
1286 // FIXME: Concepts: This should be the type of the placeholder, but this is
1287 // unclear in the wording right now.
1288 DeclRefExpr *Ref =
1289 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1290 VK_PRValue, OrigConstrainedParm->getLocation());
1291 if (!Ref)
1292 return true;
1293 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1295 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1297 OrigConstrainedParm->getLocation(),
1298 [&](TemplateArgumentListInfo &ConstraintArgs) {
1299 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1300 ConstraintArgs.addArgument(TL.getArgLoc(I));
1301 },
1302 EllipsisLoc);
1303 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1304 !ImmediatelyDeclaredConstraint.isUsable())
1305 return true;
1306
1307 NewConstrainedParm->setPlaceholderTypeConstraint(
1308 ImmediatelyDeclaredConstraint.get());
1309 return false;
1310}
1311
1312/// Check that the type of a non-type template parameter is
1313/// well-formed.
1314///
1315/// \returns the (possibly-promoted) parameter type if valid;
1316/// otherwise, produces a diagnostic and returns a NULL type.
1319 if (TSI->getType()->isUndeducedType()) {
1320 // C++17 [temp.dep.expr]p3:
1321 // An id-expression is type-dependent if it contains
1322 // - an identifier associated by name lookup with a non-type
1323 // template-parameter declared with a type that contains a
1324 // placeholder type (7.1.7.4),
1326 }
1327
1329}
1330
1331/// Require the given type to be a structural type, and diagnose if it is not.
1332///
1333/// \return \c true if an error was produced.
1335 if (T->isDependentType())
1336 return false;
1337
1338 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1339 return true;
1340
1341 if (T->isStructuralType())
1342 return false;
1343
1344 // Structural types are required to be object types or lvalue references.
1345 if (T->isRValueReferenceType()) {
1346 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1347 return true;
1348 }
1349
1350 // Don't mention structural types in our diagnostic prior to C++20. Also,
1351 // there's not much more we can say about non-scalar non-class types --
1352 // because we can't see functions or arrays here, those can only be language
1353 // extensions.
1354 if (!getLangOpts().CPlusPlus20 ||
1355 (!T->isScalarType() && !T->isRecordType())) {
1356 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1357 return true;
1358 }
1359
1360 // Structural types are required to be literal types.
1361 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1362 return true;
1363
1364 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1365
1366 // Drill down into the reason why the class is non-structural.
1367 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1368 // All members are required to be public and non-mutable, and can't be of
1369 // rvalue reference type. Check these conditions first to prefer a "local"
1370 // reason over a more distant one.
1371 for (const FieldDecl *FD : RD->fields()) {
1372 if (FD->getAccess() != AS_public) {
1373 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1374 return true;
1375 }
1376 if (FD->isMutable()) {
1377 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1378 return true;
1379 }
1380 if (FD->getType()->isRValueReferenceType()) {
1381 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1382 << T;
1383 return true;
1384 }
1385 }
1386
1387 // All bases are required to be public.
1388 for (const auto &BaseSpec : RD->bases()) {
1389 if (BaseSpec.getAccessSpecifier() != AS_public) {
1390 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1391 << T << 1;
1392 return true;
1393 }
1394 }
1395
1396 // All subobjects are required to be of structural types.
1397 SourceLocation SubLoc;
1398 QualType SubType;
1399 int Kind = -1;
1400
1401 for (const FieldDecl *FD : RD->fields()) {
1402 QualType T = Context.getBaseElementType(FD->getType());
1403 if (!T->isStructuralType()) {
1404 SubLoc = FD->getLocation();
1405 SubType = T;
1406 Kind = 0;
1407 break;
1408 }
1409 }
1410
1411 if (Kind == -1) {
1412 for (const auto &BaseSpec : RD->bases()) {
1413 QualType T = BaseSpec.getType();
1414 if (!T->isStructuralType()) {
1415 SubLoc = BaseSpec.getBaseTypeLoc();
1416 SubType = T;
1417 Kind = 1;
1418 break;
1419 }
1420 }
1421 }
1422
1423 assert(Kind != -1 && "couldn't find reason why type is not structural");
1424 Diag(SubLoc, diag::note_not_structural_subobject)
1425 << T << Kind << SubType;
1426 T = SubType;
1427 RD = T->getAsCXXRecordDecl();
1428 }
1429
1430 return true;
1431}
1432
1435 // We don't allow variably-modified types as the type of non-type template
1436 // parameters.
1437 if (T->isVariablyModifiedType()) {
1438 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1439 << T;
1440 return QualType();
1441 }
1442
1443 // C++ [temp.param]p4:
1444 //
1445 // A non-type template-parameter shall have one of the following
1446 // (optionally cv-qualified) types:
1447 //
1448 // -- integral or enumeration type,
1450 // -- pointer to object or pointer to function,
1451 T->isPointerType() ||
1452 // -- lvalue reference to object or lvalue reference to function,
1454 // -- pointer to member,
1456 // -- std::nullptr_t, or
1457 T->isNullPtrType() ||
1458 // -- a type that contains a placeholder type.
1459 T->isUndeducedType()) {
1460 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1461 // are ignored when determining its type.
1462 return T.getUnqualifiedType();
1463 }
1464
1465 // C++ [temp.param]p8:
1466 //
1467 // A non-type template-parameter of type "array of T" or
1468 // "function returning T" is adjusted to be of type "pointer to
1469 // T" or "pointer to function returning T", respectively.
1470 if (T->isArrayType() || T->isFunctionType())
1471 return Context.getDecayedType(T);
1472
1473 // If T is a dependent type, we can't do the check now, so we
1474 // assume that it is well-formed. Note that stripping off the
1475 // qualifiers here is not really correct if T turns out to be
1476 // an array type, but we'll recompute the type everywhere it's
1477 // used during instantiation, so that should be OK. (Using the
1478 // qualified type is equally wrong.)
1479 if (T->isDependentType())
1480 return T.getUnqualifiedType();
1481
1482 // C++20 [temp.param]p6:
1483 // -- a structural type
1485 return QualType();
1486
1487 if (!getLangOpts().CPlusPlus20) {
1488 // FIXME: Consider allowing structural types as an extension in C++17. (In
1489 // earlier language modes, the template argument evaluation rules are too
1490 // inflexible.)
1491 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1492 return QualType();
1493 }
1494
1495 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1496 return T.getUnqualifiedType();
1497}
1498
1500 unsigned Depth,
1501 unsigned Position,
1502 SourceLocation EqualLoc,
1503 Expr *Default) {
1505
1506 // Check that we have valid decl-specifiers specified.
1507 auto CheckValidDeclSpecifiers = [this, &D] {
1508 // C++ [temp.param]
1509 // p1
1510 // template-parameter:
1511 // ...
1512 // parameter-declaration
1513 // p2
1514 // ... A storage class shall not be specified in a template-parameter
1515 // declaration.
1516 // [dcl.typedef]p1:
1517 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1518 // of a parameter-declaration
1519 const DeclSpec &DS = D.getDeclSpec();
1520 auto EmitDiag = [this](SourceLocation Loc) {
1521 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1523 };
1525 EmitDiag(DS.getStorageClassSpecLoc());
1526
1528 EmitDiag(DS.getThreadStorageClassSpecLoc());
1529
1530 // [dcl.inline]p1:
1531 // The inline specifier can be applied only to the declaration or
1532 // definition of a variable or function.
1533
1534 if (DS.isInlineSpecified())
1535 EmitDiag(DS.getInlineSpecLoc());
1536
1537 // [dcl.constexpr]p1:
1538 // The constexpr specifier shall be applied only to the definition of a
1539 // variable or variable template or the declaration of a function or
1540 // function template.
1541
1542 if (DS.hasConstexprSpecifier())
1543 EmitDiag(DS.getConstexprSpecLoc());
1544
1545 // [dcl.fct.spec]p1:
1546 // Function-specifiers can be used only in function declarations.
1547
1548 if (DS.isVirtualSpecified())
1549 EmitDiag(DS.getVirtualSpecLoc());
1550
1551 if (DS.hasExplicitSpecifier())
1552 EmitDiag(DS.getExplicitSpecLoc());
1553
1554 if (DS.isNoreturnSpecified())
1555 EmitDiag(DS.getNoreturnSpecLoc());
1556 };
1557
1558 CheckValidDeclSpecifiers();
1559
1560 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1561 if (isa<AutoType>(T))
1563 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1564 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1565
1566 assert(S->isTemplateParamScope() &&
1567 "Non-type template parameter not in template parameter scope!");
1568 bool Invalid = false;
1569
1571 if (T.isNull()) {
1572 T = Context.IntTy; // Recover with an 'int' type.
1573 Invalid = true;
1574 }
1575
1577
1578 const IdentifierInfo *ParamName = D.getIdentifier();
1579 bool IsParameterPack = D.hasEllipsis();
1582 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1583 TInfo);
1584 Param->setAccess(AS_public);
1585
1587 if (TL.isConstrained())
1588 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1589 Invalid = true;
1590
1591 if (Invalid)
1592 Param->setInvalidDecl();
1593
1594 if (Param->isParameterPack())
1595 if (auto *LSI = getEnclosingLambda())
1596 LSI->LocalPacks.push_back(Param);
1597
1598 if (ParamName) {
1600 ParamName);
1601
1602 // Add the template parameter into the current scope.
1603 S->AddDecl(Param);
1604 IdResolver.AddDecl(Param);
1605 }
1606
1607 // C++0x [temp.param]p9:
1608 // A default template-argument may be specified for any kind of
1609 // template-parameter that is not a template parameter pack.
1610 if (Default && IsParameterPack) {
1611 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1612 Default = nullptr;
1613 }
1614
1615 // Check the well-formedness of the default template argument, if provided.
1616 if (Default) {
1617 // Check for unexpanded parameter packs.
1619 return Param;
1620
1622 }
1623
1624 return Param;
1625}
1626
1627/// ActOnTemplateTemplateParameter - Called when a C++ template template
1628/// parameter (e.g. T in template <template <typename> class T> class array)
1629/// has been parsed. S is the current scope.
1631 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1632 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1633 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1635 assert(S->isTemplateParamScope() &&
1636 "Template template parameter not in template parameter scope!");
1637
1638 // Construct the parameter object.
1639 bool IsParameterPack = EllipsisLoc.isValid();
1642 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1643 Name, Typename, Params);
1644 Param->setAccess(AS_public);
1645
1646 if (Param->isParameterPack())
1647 if (auto *LSI = getEnclosingLambda())
1648 LSI->LocalPacks.push_back(Param);
1649
1650 // If the template template parameter has a name, then link the identifier
1651 // into the scope and lookup mechanisms.
1652 if (Name) {
1653 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1654
1655 S->AddDecl(Param);
1656 IdResolver.AddDecl(Param);
1657 }
1658
1659 if (Params->size() == 0) {
1660 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1661 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1662 Param->setInvalidDecl();
1663 }
1664
1665 // C++0x [temp.param]p9:
1666 // A default template-argument may be specified for any kind of
1667 // template-parameter that is not a template parameter pack.
1668 if (IsParameterPack && !Default.isInvalid()) {
1669 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1671 }
1672
1673 if (!Default.isInvalid()) {
1674 // Check only that we have a template template argument. We don't want to
1675 // try to check well-formedness now, because our template template parameter
1676 // might have dependent types in its template parameters, which we wouldn't
1677 // be able to match now.
1678 //
1679 // If none of the template template parameter's template arguments mention
1680 // other template parameters, we could actually perform more checking here.
1681 // However, it isn't worth doing.
1683 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1684 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1685 << DefaultArg.getSourceRange();
1686 return Param;
1687 }
1688
1689 // Check for unexpanded parameter packs.
1691 DefaultArg.getArgument().getAsTemplate(),
1693 return Param;
1694
1695 Param->setDefaultArgument(Context, DefaultArg);
1696 }
1697
1698 return Param;
1699}
1700
1701namespace {
1702class ConstraintRefersToContainingTemplateChecker
1703 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1704 bool Result = false;
1705 const FunctionDecl *Friend = nullptr;
1706 unsigned TemplateDepth = 0;
1707
1708 // Check a record-decl that we've seen to see if it is a lexical parent of the
1709 // Friend, likely because it was referred to without its template arguments.
1710 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1711 CheckingRD = CheckingRD->getMostRecentDecl();
1712 if (!CheckingRD->isTemplated())
1713 return;
1714
1715 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1716 DC && !DC->isFileContext(); DC = DC->getParent())
1717 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1718 if (CheckingRD == RD->getMostRecentDecl())
1719 Result = true;
1720 }
1721
1722 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1723 assert(D->getDepth() <= TemplateDepth &&
1724 "Nothing should reference a value below the actual template depth, "
1725 "depth is likely wrong");
1726 if (D->getDepth() != TemplateDepth)
1727 Result = true;
1728
1729 // Necessary because the type of the NTTP might be what refers to the parent
1730 // constriant.
1731 TransformType(D->getType());
1732 }
1733
1734public:
1736
1737 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1738 const FunctionDecl *Friend,
1739 unsigned TemplateDepth)
1740 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1741 bool getResult() const { return Result; }
1742
1743 // This should be the only template parm type that we have to deal with.
1744 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1745 // FunctionParmPackExpr are all partially substituted, which cannot happen
1746 // with concepts at this point in translation.
1747 using inherited::TransformTemplateTypeParmType;
1748 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1749 TemplateTypeParmTypeLoc TL, bool) {
1750 assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1751 "Nothing should reference a value below the actual template depth, "
1752 "depth is likely wrong");
1753 if (TL.getDecl()->getDepth() != TemplateDepth)
1754 Result = true;
1755 return inherited::TransformTemplateTypeParmType(
1756 TLB, TL,
1757 /*SuppressObjCLifetime=*/false);
1758 }
1759
1760 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1761 if (!D)
1762 return D;
1763 // FIXME : This is possibly an incomplete list, but it is unclear what other
1764 // Decl kinds could be used to refer to the template parameters. This is a
1765 // best guess so far based on examples currently available, but the
1766 // unreachable should catch future instances/cases.
1767 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1768 TransformType(TD->getUnderlyingType());
1769 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1770 CheckNonTypeTemplateParmDecl(NTTPD);
1771 else if (auto *VD = dyn_cast<ValueDecl>(D))
1772 TransformType(VD->getType());
1773 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1774 TransformTemplateParameterList(TD->getTemplateParameters());
1775 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1776 CheckIfContainingRecord(RD);
1777 else if (isa<NamedDecl>(D)) {
1778 // No direct types to visit here I believe.
1779 } else
1780 llvm_unreachable("Don't know how to handle this declaration type yet");
1781 return D;
1782 }
1783};
1784} // namespace
1785
1787 const FunctionDecl *Friend, unsigned TemplateDepth,
1788 const Expr *Constraint) {
1789 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1790 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1791 TemplateDepth);
1792 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1793 return Checker.getResult();
1794}
1795
1796/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1797/// constrained by RequiresClause, that contains the template parameters in
1798/// Params.
1801 SourceLocation ExportLoc,
1802 SourceLocation TemplateLoc,
1803 SourceLocation LAngleLoc,
1804 ArrayRef<NamedDecl *> Params,
1805 SourceLocation RAngleLoc,
1806 Expr *RequiresClause) {
1807 if (ExportLoc.isValid())
1808 Diag(ExportLoc, diag::warn_template_export_unsupported);
1809
1810 for (NamedDecl *P : Params)
1812
1814 Context, TemplateLoc, LAngleLoc,
1815 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1816}
1817
1819 const CXXScopeSpec &SS) {
1820 if (SS.isSet())
1821 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1822}
1823
1824// Returns the template parameter list with all default template argument
1825// information.
1827 // Make sure we get the template parameter list from the most
1828 // recent declaration, since that is the only one that is guaranteed to
1829 // have all the default template argument information.
1830 Decl *D = TD->getMostRecentDecl();
1831 // C++11 N3337 [temp.param]p12:
1832 // A default template argument shall not be specified in a friend class
1833 // template declaration.
1834 //
1835 // Skip past friend *declarations* because they are not supposed to contain
1836 // default template arguments. Moreover, these declarations may introduce
1837 // template parameters living in different template depths than the
1838 // corresponding template parameters in TD, causing unmatched constraint
1839 // substitution.
1840 //
1841 // FIXME: Diagnose such cases within a class template:
1842 // template <class T>
1843 // struct S {
1844 // template <class = void> friend struct C;
1845 // };
1846 // template struct S<int>;
1848 D->getPreviousDecl())
1849 D = D->getPreviousDecl();
1850 return cast<TemplateDecl>(D)->getTemplateParameters();
1851}
1852
1854 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1855 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1856 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1857 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1858 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1859 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1860 assert(TemplateParams && TemplateParams->size() > 0 &&
1861 "No template parameters");
1862 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1863 bool Invalid = false;
1864
1865 // Check that we can declare a template here.
1866 if (CheckTemplateDeclScope(S, TemplateParams))
1867 return true;
1868
1870 assert(Kind != TagTypeKind::Enum &&
1871 "can't build template of enumerated type");
1872
1873 // There is no such thing as an unnamed class template.
1874 if (!Name) {
1875 Diag(KWLoc, diag::err_template_unnamed_class);
1876 return true;
1877 }
1878
1879 // Find any previous declaration with this name. For a friend with no
1880 // scope explicitly specified, we only look for tag declarations (per
1881 // C++11 [basic.lookup.elab]p2).
1882 DeclContext *SemanticContext;
1883 LookupResult Previous(*this, Name, NameLoc,
1884 (SS.isEmpty() && TUK == TUK_Friend)
1887 if (SS.isNotEmpty() && !SS.isInvalid()) {
1888 SemanticContext = computeDeclContext(SS, true);
1889 if (!SemanticContext) {
1890 // FIXME: Horrible, horrible hack! We can't currently represent this
1891 // in the AST, and historically we have just ignored such friend
1892 // class templates, so don't complain here.
1893 Diag(NameLoc, TUK == TUK_Friend
1894 ? diag::warn_template_qualified_friend_ignored
1895 : diag::err_template_qualified_declarator_no_match)
1896 << SS.getScopeRep() << SS.getRange();
1897 return TUK != TUK_Friend;
1898 }
1899
1900 if (RequireCompleteDeclContext(SS, SemanticContext))
1901 return true;
1902
1903 // If we're adding a template to a dependent context, we may need to
1904 // rebuilding some of the types used within the template parameter list,
1905 // now that we know what the current instantiation is.
1906 if (SemanticContext->isDependentContext()) {
1907 ContextRAII SavedContext(*this, SemanticContext);
1909 Invalid = true;
1910 }
1911
1912 if (TUK != TUK_Friend && TUK != TUK_Reference)
1913 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1914 /*TemplateId-*/ nullptr,
1915 /*IsMemberSpecialization*/ false);
1916
1917 LookupQualifiedName(Previous, SemanticContext);
1918 } else {
1919 SemanticContext = CurContext;
1920
1921 // C++14 [class.mem]p14:
1922 // If T is the name of a class, then each of the following shall have a
1923 // name different from T:
1924 // -- every member template of class T
1925 if (TUK != TUK_Friend &&
1926 DiagnoseClassNameShadow(SemanticContext,
1927 DeclarationNameInfo(Name, NameLoc)))
1928 return true;
1929
1930 LookupName(Previous, S);
1931 }
1932
1933 if (Previous.isAmbiguous())
1934 return true;
1935
1936 NamedDecl *PrevDecl = nullptr;
1937 if (Previous.begin() != Previous.end())
1938 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1939
1940 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1941 // Maybe we will complain about the shadowed template parameter.
1942 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1943 // Just pretend that we didn't see the previous declaration.
1944 PrevDecl = nullptr;
1945 }
1946
1947 // If there is a previous declaration with the same name, check
1948 // whether this is a valid redeclaration.
1949 ClassTemplateDecl *PrevClassTemplate =
1950 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1951
1952 // We may have found the injected-class-name of a class template,
1953 // class template partial specialization, or class template specialization.
1954 // In these cases, grab the template that is being defined or specialized.
1955 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1956 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1957 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1958 PrevClassTemplate
1959 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1960 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1961 PrevClassTemplate
1962 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1963 ->getSpecializedTemplate();
1964 }
1965 }
1966
1967 if (TUK == TUK_Friend) {
1968 // C++ [namespace.memdef]p3:
1969 // [...] When looking for a prior declaration of a class or a function
1970 // declared as a friend, and when the name of the friend class or
1971 // function is neither a qualified name nor a template-id, scopes outside
1972 // the innermost enclosing namespace scope are not considered.
1973 if (!SS.isSet()) {
1974 DeclContext *OutermostContext = CurContext;
1975 while (!OutermostContext->isFileContext())
1976 OutermostContext = OutermostContext->getLookupParent();
1977
1978 if (PrevDecl &&
1979 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1980 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1981 SemanticContext = PrevDecl->getDeclContext();
1982 } else {
1983 // Declarations in outer scopes don't matter. However, the outermost
1984 // context we computed is the semantic context for our new
1985 // declaration.
1986 PrevDecl = PrevClassTemplate = nullptr;
1987 SemanticContext = OutermostContext;
1988
1989 // Check that the chosen semantic context doesn't already contain a
1990 // declaration of this name as a non-tag type.
1992 DeclContext *LookupContext = SemanticContext;
1993 while (LookupContext->isTransparentContext())
1994 LookupContext = LookupContext->getLookupParent();
1995 LookupQualifiedName(Previous, LookupContext);
1996
1997 if (Previous.isAmbiguous())
1998 return true;
1999
2000 if (Previous.begin() != Previous.end())
2001 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2002 }
2003 }
2004 } else if (PrevDecl &&
2005 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
2006 S, SS.isValid()))
2007 PrevDecl = PrevClassTemplate = nullptr;
2008
2009 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2010 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2011 if (SS.isEmpty() &&
2012 !(PrevClassTemplate &&
2013 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2014 SemanticContext->getRedeclContext()))) {
2015 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2016 Diag(Shadow->getTargetDecl()->getLocation(),
2017 diag::note_using_decl_target);
2018 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2019 // Recover by ignoring the old declaration.
2020 PrevDecl = PrevClassTemplate = nullptr;
2021 }
2022 }
2023
2024 if (PrevClassTemplate) {
2025 // Ensure that the template parameter lists are compatible. Skip this check
2026 // for a friend in a dependent context: the template parameter list itself
2027 // could be dependent.
2028 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2030 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2031 : CurContext,
2032 CurContext, KWLoc),
2033 TemplateParams, PrevClassTemplate,
2034 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2036 return true;
2037
2038 // C++ [temp.class]p4:
2039 // In a redeclaration, partial specialization, explicit
2040 // specialization or explicit instantiation of a class template,
2041 // the class-key shall agree in kind with the original class
2042 // template declaration (7.1.5.3).
2043 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2044 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
2045 TUK == TUK_Definition, KWLoc, Name)) {
2046 Diag(KWLoc, diag::err_use_with_wrong_tag)
2047 << Name
2048 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2049 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2050 Kind = PrevRecordDecl->getTagKind();
2051 }
2052
2053 // Check for redefinition of this class template.
2054 if (TUK == TUK_Definition) {
2055 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2056 // If we have a prior definition that is not visible, treat this as
2057 // simply making that previous definition visible.
2058 NamedDecl *Hidden = nullptr;
2059 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2060 SkipBody->ShouldSkip = true;
2061 SkipBody->Previous = Def;
2062 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2063 assert(Tmpl && "original definition of a class template is not a "
2064 "class template?");
2067 } else {
2068 Diag(NameLoc, diag::err_redefinition) << Name;
2069 Diag(Def->getLocation(), diag::note_previous_definition);
2070 // FIXME: Would it make sense to try to "forget" the previous
2071 // definition, as part of error recovery?
2072 return true;
2073 }
2074 }
2075 }
2076 } else if (PrevDecl) {
2077 // C++ [temp]p5:
2078 // A class template shall not have the same name as any other
2079 // template, class, function, object, enumeration, enumerator,
2080 // namespace, or type in the same scope (3.3), except as specified
2081 // in (14.5.4).
2082 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2083 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2084 return true;
2085 }
2086
2087 // Check the template parameter list of this declaration, possibly
2088 // merging in the template parameter list from the previous class
2089 // template declaration. Skip this check for a friend in a dependent
2090 // context, because the template parameter list might be dependent.
2091 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2093 TemplateParams,
2094 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2095 : nullptr,
2096 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2097 SemanticContext->isDependentContext())
2101 SkipBody))
2102 Invalid = true;
2103
2104 if (SS.isSet()) {
2105 // If the name of the template was qualified, we must be defining the
2106 // template out-of-line.
2107 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2108 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2109 : diag::err_member_decl_does_not_match)
2110 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2111 Invalid = true;
2112 }
2113 }
2114
2115 // If this is a templated friend in a dependent context we should not put it
2116 // on the redecl chain. In some cases, the templated friend can be the most
2117 // recent declaration tricking the template instantiator to make substitutions
2118 // there.
2119 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2120 bool ShouldAddRedecl
2121 = !(TUK == TUK_Friend && CurContext->isDependentContext());
2122
2123 CXXRecordDecl *NewClass =
2124 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2125 PrevClassTemplate && ShouldAddRedecl ?
2126 PrevClassTemplate->getTemplatedDecl() : nullptr,
2127 /*DelayTypeCreation=*/true);
2128 SetNestedNameSpecifier(*this, NewClass, SS);
2129 if (NumOuterTemplateParamLists > 0)
2131 Context,
2132 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2133
2134 // Add alignment attributes if necessary; these attributes are checked when
2135 // the ASTContext lays out the structure.
2136 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2139 }
2140
2141 ClassTemplateDecl *NewTemplate
2142 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2143 DeclarationName(Name), TemplateParams,
2144 NewClass);
2145
2146 if (ShouldAddRedecl)
2147 NewTemplate->setPreviousDecl(PrevClassTemplate);
2148
2149 NewClass->setDescribedClassTemplate(NewTemplate);
2150
2151 if (ModulePrivateLoc.isValid())
2152 NewTemplate->setModulePrivate();
2153
2154 // Build the type for the class template declaration now.
2156 T = Context.getInjectedClassNameType(NewClass, T);
2157 assert(T->isDependentType() && "Class template type is not dependent?");
2158 (void)T;
2159
2160 // If we are providing an explicit specialization of a member that is a
2161 // class template, make a note of that.
2162 if (PrevClassTemplate &&
2163 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2164 PrevClassTemplate->setMemberSpecialization();
2165
2166 // Set the access specifier.
2167 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2168 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2169
2170 // Set the lexical context of these templates
2172 NewTemplate->setLexicalDeclContext(CurContext);
2173
2174 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2175 NewClass->startDefinition();
2176
2177 ProcessDeclAttributeList(S, NewClass, Attr);
2178 ProcessAPINotes(NewClass);
2179
2180 if (PrevClassTemplate)
2181 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2182
2186
2187 if (TUK != TUK_Friend) {
2188 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2189 Scope *Outer = S;
2190 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2191 Outer = Outer->getParent();
2192 PushOnScopeChains(NewTemplate, Outer);
2193 } else {
2194 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2195 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2196 NewClass->setAccess(PrevClassTemplate->getAccess());
2197 }
2198
2199 NewTemplate->setObjectOfFriendDecl();
2200
2201 // Friend templates are visible in fairly strange ways.
2203 DeclContext *DC = SemanticContext->getRedeclContext();
2204 DC->makeDeclVisibleInContext(NewTemplate);
2205 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2206 PushOnScopeChains(NewTemplate, EnclosingScope,
2207 /* AddToContext = */ false);
2208 }
2209
2211 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2212 Friend->setAccess(AS_public);
2213 CurContext->addDecl(Friend);
2214 }
2215
2216 if (PrevClassTemplate)
2217 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2218
2219 if (Invalid) {
2220 NewTemplate->setInvalidDecl();
2221 NewClass->setInvalidDecl();
2222 }
2223
2224 ActOnDocumentableDecl(NewTemplate);
2225
2226 if (SkipBody && SkipBody->ShouldSkip)
2227 return SkipBody->Previous;
2228
2229 return NewTemplate;
2230}
2231
2232namespace {
2233/// Tree transform to "extract" a transformed type from a class template's
2234/// constructor to a deduction guide.
2235class ExtractTypeForDeductionGuide
2236 : public TreeTransform<ExtractTypeForDeductionGuide> {
2237 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2238
2239public:
2241 ExtractTypeForDeductionGuide(
2242 Sema &SemaRef,
2243 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2244 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2245
2246 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2247
2248 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2249 ASTContext &Context = SemaRef.getASTContext();
2250 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2251 TypedefNameDecl *Decl = OrigDecl;
2252 // Transform the underlying type of the typedef and clone the Decl only if
2253 // the typedef has a dependent context.
2254 if (OrigDecl->getDeclContext()->isDependentContext()) {
2255 TypeLocBuilder InnerTLB;
2256 QualType Transformed =
2257 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2258 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2259 if (isa<TypeAliasDecl>(OrigDecl))
2261 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2262 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2263 else {
2264 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2266 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2267 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2268 }
2269 MaterializedTypedefs.push_back(Decl);
2270 }
2271
2272 QualType TDTy = Context.getTypedefType(Decl);
2273 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2274 TypedefTL.setNameLoc(TL.getNameLoc());
2275
2276 return TDTy;
2277 }
2278};
2279
2280// Build a deduction guide with the specified parameter types.
2281FunctionTemplateDecl *buildDeductionGuide(
2282 Sema &SemaRef, TemplateDecl *OriginalTemplate,
2283 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2284 ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2285 SourceLocation Loc, SourceLocation LocEnd, bool IsImplicit,
2286 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2287 DeclContext *DC = OriginalTemplate->getDeclContext();
2288 auto DeductionGuideName =
2290 OriginalTemplate);
2291
2292 DeclarationNameInfo Name(DeductionGuideName, Loc);
2294 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2295
2296 // Build the implicit deduction guide template.
2297 auto *Guide =
2298 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2299 TInfo->getType(), TInfo, LocEnd, Ctor);
2300 Guide->setImplicit(IsImplicit);
2301 Guide->setParams(Params);
2302
2303 for (auto *Param : Params)
2304 Param->setDeclContext(Guide);
2305 for (auto *TD : MaterializedTypedefs)
2306 TD->setDeclContext(Guide);
2307
2308 auto *GuideTemplate = FunctionTemplateDecl::Create(
2309 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2310 GuideTemplate->setImplicit(IsImplicit);
2311 Guide->setDescribedFunctionTemplate(GuideTemplate);
2312
2313 if (isa<CXXRecordDecl>(DC)) {
2314 Guide->setAccess(AS_public);
2315 GuideTemplate->setAccess(AS_public);
2316 }
2317
2318 DC->addDecl(GuideTemplate);
2319 return GuideTemplate;
2320}
2321
2322// Transform a given template type parameter `TTP`.
2324transformTemplateTypeParam(Sema &SemaRef, DeclContext *DC,
2327 unsigned NewDepth, unsigned NewIndex) {
2328 // TemplateTypeParmDecl's index cannot be changed after creation, so
2329 // substitute it directly.
2330 auto *NewTTP = TemplateTypeParmDecl::Create(
2331 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), NewDepth,
2332 NewIndex, TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2333 TTP->isParameterPack(), TTP->hasTypeConstraint(),
2335 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
2336 : std::nullopt);
2337 if (const auto *TC = TTP->getTypeConstraint())
2338 SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
2339 /*EvaluateConstraint=*/true);
2340 if (TTP->hasDefaultArgument()) {
2341 TypeSourceInfo *InstantiatedDefaultArg =
2342 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2343 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2344 if (InstantiatedDefaultArg)
2345 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2346 }
2347 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TTP, NewTTP);
2348 return NewTTP;
2349}
2350// Similar to above, but for non-type template or template template parameters.
2351template <typename NonTypeTemplateOrTemplateTemplateParmDecl>
2352NonTypeTemplateOrTemplateTemplateParmDecl *
2353transformTemplateParam(Sema &SemaRef, DeclContext *DC,
2354 NonTypeTemplateOrTemplateTemplateParmDecl *OldParam,
2355 MultiLevelTemplateArgumentList &Args, unsigned NewIndex,
2356 unsigned NewDepth) {
2357 // Ask the template instantiator to do the heavy lifting for us, then adjust
2358 // the index of the parameter once it's done.
2359 auto *NewParam = cast<NonTypeTemplateOrTemplateTemplateParmDecl>(
2360 SemaRef.SubstDecl(OldParam, DC, Args));
2361 NewParam->setPosition(NewIndex);
2362 NewParam->setDepth(NewDepth);
2363 return NewParam;
2364}
2365
2366/// Transform to convert portions of a constructor declaration into the
2367/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2368struct ConvertConstructorToDeductionGuideTransform {
2369 ConvertConstructorToDeductionGuideTransform(Sema &S,
2370 ClassTemplateDecl *Template)
2371 : SemaRef(S), Template(Template) {
2372 // If the template is nested, then we need to use the original
2373 // pattern to iterate over the constructors.
2374 ClassTemplateDecl *Pattern = Template;
2375 while (Pattern->getInstantiatedFromMemberTemplate()) {
2376 if (Pattern->isMemberSpecialization())
2377 break;
2378 Pattern = Pattern->getInstantiatedFromMemberTemplate();
2379 NestedPattern = Pattern;
2380 }
2381
2382 if (NestedPattern)
2383 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
2384 }
2385
2386 Sema &SemaRef;
2387 ClassTemplateDecl *Template;
2388 ClassTemplateDecl *NestedPattern = nullptr;
2389
2390 DeclContext *DC = Template->getDeclContext();
2391 CXXRecordDecl *Primary = Template->getTemplatedDecl();
2392 DeclarationName DeductionGuideName =
2394
2395 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2396
2397 // Index adjustment to apply to convert depth-1 template parameters into
2398 // depth-0 template parameters.
2399 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2400
2401 // Instantiation arguments for the outermost depth-1 templates
2402 // when the template is nested
2403 MultiLevelTemplateArgumentList OuterInstantiationArgs;
2404
2405 /// Transform a constructor declaration into a deduction guide.
2406 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2407 CXXConstructorDecl *CD) {
2409
2411
2412 // C++ [over.match.class.deduct]p1:
2413 // -- For each constructor of the class template designated by the
2414 // template-name, a function template with the following properties:
2415
2416 // -- The template parameters are the template parameters of the class
2417 // template followed by the template parameters (including default
2418 // template arguments) of the constructor, if any.
2419 TemplateParameterList *TemplateParams = GetTemplateParameterList(Template);
2420 if (FTD) {
2421 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2424 AllParams.reserve(TemplateParams->size() + InnerParams->size());
2425 AllParams.insert(AllParams.begin(),
2426 TemplateParams->begin(), TemplateParams->end());
2427 SubstArgs.reserve(InnerParams->size());
2428 Depth1Args.reserve(InnerParams->size());
2429
2430 // Later template parameters could refer to earlier ones, so build up
2431 // a list of substituted template arguments as we go.
2432 for (NamedDecl *Param : *InnerParams) {
2434 Args.setKind(TemplateSubstitutionKind::Rewrite);
2435 Args.addOuterTemplateArguments(Depth1Args);
2436 Args.addOuterRetainedLevel();
2437 if (NestedPattern)
2438 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2439 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2440 if (!NewParam)
2441 return nullptr;
2442 // Constraints require that we substitute depth-1 arguments
2443 // to match depths when substituted for evaluation later
2444 Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2445 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2446
2447 if (NestedPattern) {
2448 TemplateDeclInstantiator Instantiator(SemaRef, DC,
2449 OuterInstantiationArgs);
2450 Instantiator.setEvaluateConstraints(false);
2451 SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] {
2452 NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam));
2453 });
2454 }
2455
2456 assert(NewParam->getTemplateDepth() == 0 &&
2457 "Unexpected template parameter depth");
2458
2459 AllParams.push_back(NewParam);
2460 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2461 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2462 }
2463
2464 // Substitute new template parameters into requires-clause if present.
2465 Expr *RequiresClause = nullptr;
2466 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2468 Args.setKind(TemplateSubstitutionKind::Rewrite);
2469 Args.addOuterTemplateArguments(Depth1Args);
2470 Args.addOuterRetainedLevel();
2471 if (NestedPattern)
2472 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2473 ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2474 if (E.isInvalid())
2475 return nullptr;
2476 RequiresClause = E.getAs<Expr>();
2477 }
2478
2479 TemplateParams = TemplateParameterList::Create(
2480 SemaRef.Context, InnerParams->getTemplateLoc(),
2481 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2482 RequiresClause);
2483 }
2484
2485 // If we built a new template-parameter-list, track that we need to
2486 // substitute references to the old parameters into references to the
2487 // new ones.
2489 Args.setKind(TemplateSubstitutionKind::Rewrite);
2490 if (FTD) {
2491 Args.addOuterTemplateArguments(SubstArgs);
2492 Args.addOuterRetainedLevel();
2493 }
2494
2497 assert(FPTL && "no prototype for constructor declaration");
2498
2499 // Transform the type of the function, adjusting the return type and
2500 // replacing references to the old parameters with references to the
2501 // new ones.
2502 TypeLocBuilder TLB;
2504 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2505 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2506 MaterializedTypedefs);
2507 if (NewType.isNull())
2508 return nullptr;
2509 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2510
2511 return buildDeductionGuide(
2512 SemaRef, Template, TemplateParams, CD, CD->getExplicitSpecifier(),
2513 NewTInfo, CD->getBeginLoc(), CD->getLocation(), CD->getEndLoc(),
2514 /*IsImplicit=*/true, MaterializedTypedefs);
2515 }
2516
2517 /// Build a deduction guide with the specified parameter types.
2518 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2519 SourceLocation Loc = Template->getLocation();
2520
2521 // Build the requested type.
2523 EPI.HasTrailingReturn = true;
2524 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2525 DeductionGuideName, EPI);
2526 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2527 if (NestedPattern)
2528 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2529 DeductionGuideName);
2530
2533
2534 // Build the parameters, needed during deduction / substitution.
2536 for (auto T : ParamTypes) {
2537 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
2538 if (NestedPattern)
2539 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2540 DeclarationName());
2541 ParmVarDecl *NewParam =
2542 ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
2543 TSI->getType(), TSI, SC_None, nullptr);
2544 NewParam->setScopeInfo(0, Params.size());
2545 FPTL.setParam(Params.size(), NewParam);
2546 Params.push_back(NewParam);
2547 }
2548
2549 return buildDeductionGuide(
2550 SemaRef, Template, GetTemplateParameterList(Template), nullptr,
2551 ExplicitSpecifier(), TSI, Loc, Loc, Loc, /*IsImplicit=*/true);
2552 }
2553
2554private:
2555 /// Transform a constructor template parameter into a deduction guide template
2556 /// parameter, rebuilding any internal references to earlier parameters and
2557 /// renumbering as we go.
2558 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2560 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
2561 return transformTemplateTypeParam(
2562 SemaRef, DC, TTP, Args, TTP->getDepth() - 1,
2563 Depth1IndexAdjustment + TTP->getIndex());
2564 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2565 return transformTemplateParam(SemaRef, DC, TTP, Args,
2566 Depth1IndexAdjustment + TTP->getIndex(),
2567 TTP->getDepth() - 1);
2568 auto *NTTP = cast<NonTypeTemplateParmDecl>(TemplateParam);
2569 return transformTemplateParam(SemaRef, DC, NTTP, Args,
2570 Depth1IndexAdjustment + NTTP->getIndex(),
2571 NTTP->getDepth() - 1);
2572 }
2573
2574 QualType transformFunctionProtoType(
2578 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2579 SmallVector<QualType, 4> ParamTypes;
2580 const FunctionProtoType *T = TL.getTypePtr();
2581
2582 // -- The types of the function parameters are those of the constructor.
2583 for (auto *OldParam : TL.getParams()) {
2584 ParmVarDecl *NewParam = OldParam;
2585 // Given
2586 // template <class T> struct C {
2587 // template <class U> struct D {
2588 // template <class V> D(U, V);
2589 // };
2590 // };
2591 // First, transform all the references to template parameters that are
2592 // defined outside of the surrounding class template. That is T in the
2593 // above example.
2594 if (NestedPattern) {
2595 NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs,
2596 MaterializedTypedefs);
2597 if (!NewParam)
2598 return QualType();
2599 }
2600 // Then, transform all the references to template parameters that are
2601 // defined at the class template and the constructor. In this example,
2602 // they're U and V, respectively.
2603 NewParam =
2604 transformFunctionTypeParam(NewParam, Args, MaterializedTypedefs);
2605 if (!NewParam)
2606 return QualType();
2607 ParamTypes.push_back(NewParam->getType());
2608 Params.push_back(NewParam);
2609 }
2610
2611 // -- The return type is the class template specialization designated by
2612 // the template-name and template arguments corresponding to the
2613 // template parameters obtained from the class template.
2614 //
2615 // We use the injected-class-name type of the primary template instead.
2616 // This has the convenient property that it is different from any type that
2617 // the user can write in a deduction-guide (because they cannot enter the
2618 // context of the template), so implicit deduction guides can never collide
2619 // with explicit ones.
2620 QualType ReturnType = DeducedType;
2621 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2622
2623 // Resolving a wording defect, we also inherit the variadicness of the
2624 // constructor.
2626 EPI.Variadic = T->isVariadic();
2627 EPI.HasTrailingReturn = true;
2628
2629 QualType Result = SemaRef.BuildFunctionType(
2630 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2631 if (Result.isNull())
2632 return QualType();
2633
2634 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2636 NewTL.setLParenLoc(TL.getLParenLoc());
2637 NewTL.setRParenLoc(TL.getRParenLoc());
2640 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2641 NewTL.setParam(I, Params[I]);
2642
2643 return Result;
2644 }
2645
2646 ParmVarDecl *transformFunctionTypeParam(
2648 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2649 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2650 TypeSourceInfo *NewDI;
2651 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2652 // Expand out the one and only element in each inner pack.
2653 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2654 NewDI =
2655 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2656 OldParam->getLocation(), OldParam->getDeclName());
2657 if (!NewDI) return nullptr;
2658 NewDI =
2659 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2660 PackTL.getTypePtr()->getNumExpansions());
2661 } else
2662 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2663 OldParam->getDeclName());
2664 if (!NewDI)
2665 return nullptr;
2666
2667 // Extract the type. This (for instance) replaces references to typedef
2668 // members of the current instantiations with the definitions of those
2669 // typedefs, avoiding triggering instantiation of the deduced type during
2670 // deduction.
2671 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2672 .transform(NewDI);
2673
2674 // Resolving a wording defect, we also inherit default arguments from the
2675 // constructor.
2676 ExprResult NewDefArg;
2677 if (OldParam->hasDefaultArg()) {
2678 // We don't care what the value is (we won't use it); just create a
2679 // placeholder to indicate there is a default argument.
2680 QualType ParamTy = NewDI->getType();
2681 NewDefArg = new (SemaRef.Context)
2683 ParamTy.getNonLValueExprType(SemaRef.Context),
2684 ParamTy->isLValueReferenceType() ? VK_LValue
2685 : ParamTy->isRValueReferenceType() ? VK_XValue
2686 : VK_PRValue);
2687 }
2688 // Handle arrays and functions decay.
2689 auto NewType = NewDI->getType();
2690 if (NewType->isArrayType() || NewType->isFunctionType())
2691 NewType = SemaRef.Context.getDecayedType(NewType);
2692
2693 ParmVarDecl *NewParam = ParmVarDecl::Create(
2694 SemaRef.Context, DC, OldParam->getInnerLocStart(),
2695 OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewDI,
2696 OldParam->getStorageClass(), NewDefArg.get());
2697 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2698 OldParam->getFunctionScopeIndex());
2699 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2700 return NewParam;
2701 }
2702};
2703
2704// Find all template parameters that appear in the given DeducedArgs.
2705// Return the indices of the template parameters in the TemplateParams.
2706SmallVector<unsigned> TemplateParamsReferencedInTemplateArgumentList(
2707 ArrayRef<NamedDecl *> TemplateParams,
2708 ArrayRef<TemplateArgument> DeducedArgs) {
2709 struct TemplateParamsReferencedFinder
2710 : public RecursiveASTVisitor<TemplateParamsReferencedFinder> {
2711 llvm::DenseSet<NamedDecl *> TemplateParams;
2712 llvm::DenseSet<const NamedDecl *> ReferencedTemplateParams;
2713
2714 TemplateParamsReferencedFinder(ArrayRef<NamedDecl *> TemplateParams)
2715 : TemplateParams(TemplateParams.begin(), TemplateParams.end()) {}
2716
2717 bool VisitTemplateTypeParmType(TemplateTypeParmType *TTP) {
2718 MarkAppeared(TTP->getDecl());
2719 return true;
2720 }
2721 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
2722 MarkAppeared(DRE->getFoundDecl());
2723 return true;
2724 }
2725
2726 bool TraverseTemplateName(TemplateName Template) {
2727 if (auto *TD = Template.getAsTemplateDecl())
2728 MarkAppeared(TD);
2730 }
2731
2732 void MarkAppeared(NamedDecl *ND) {
2733 if (TemplateParams.contains(ND))
2734 ReferencedTemplateParams.insert(ND);
2735 }
2736 };
2737 TemplateParamsReferencedFinder Finder(TemplateParams);
2738 Finder.TraverseTemplateArguments(DeducedArgs);
2739
2740 SmallVector<unsigned> Results;
2741 for (unsigned Index = 0; Index < TemplateParams.size(); ++Index) {
2742 if (Finder.ReferencedTemplateParams.contains(TemplateParams[Index]))
2743 Results.push_back(Index);
2744 }
2745 return Results;
2746}
2747
2748bool hasDeclaredDeductionGuides(DeclarationName Name, DeclContext *DC) {
2749 // Check whether we've already declared deduction guides for this template.
2750 // FIXME: Consider storing a flag on the template to indicate this.
2751 assert(Name.getNameKind() ==
2753 "name must be a deduction guide name");
2754 auto Existing = DC->lookup(Name);
2755 for (auto *D : Existing)
2756 if (D->isImplicit())
2757 return true;
2758 return false;
2759}
2760
2761unsigned getTemplateParameterDepth(NamedDecl *TemplateParam) {
2762 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
2763 return TTP->getDepth();
2764 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2765 return TTP->getDepth();
2766 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(TemplateParam))
2767 return NTTP->getDepth();
2768 llvm_unreachable("Unhandled template parameter types");
2769}
2770
2771NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
2774 unsigned NewIndex, unsigned NewDepth) {
2775 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
2776 return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth,
2777 NewIndex);
2778 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2779 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex, NewDepth);
2780 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(TemplateParam))
2781 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex, NewDepth);
2782 llvm_unreachable("Unhandled template parameter types");
2783}
2784
2785// Build the associated constraints for the alias deduction guides.
2786// C++ [over.match.class.deduct]p3.3:
2787// The associated constraints ([temp.constr.decl]) are the conjunction of the
2788// associated constraints of g and a constraint that is satisfied if and only
2789// if the arguments of A are deducible (see below) from the return type.
2790//
2791// The return result is expected to be the require-clause for the synthesized
2792// alias deduction guide.
2793Expr *
2794buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F,
2797 Expr *IsDeducible) {
2799 if (!RC)
2800 return IsDeducible;
2801
2802 ASTContext &Context = SemaRef.Context;
2804
2805 // In the clang AST, constraint nodes are deliberately not instantiated unless
2806 // they are actively being evaluated. Consequently, occurrences of template
2807 // parameters in the require-clause expression have a subtle "depth"
2808 // difference compared to normal occurrences in places, such as function
2809 // parameters. When transforming the require-clause, we must take this
2810 // distinction into account:
2811 //
2812 // 1) In the transformed require-clause, occurrences of template parameters
2813 // must use the "uninstantiated" depth;
2814 // 2) When substituting on the require-clause expr of the underlying
2815 // deduction guide, we must use the entire set of template argument lists;
2816 //
2817 // It's important to note that we're performing this transformation on an
2818 // *instantiated* AliasTemplate.
2819
2820 // For 1), if the alias template is nested within a class template, we
2821 // calcualte the 'uninstantiated' depth by adding the substitution level back.
2822 unsigned AdjustDepth = 0;
2823 if (auto *PrimaryTemplate =
2824 AliasTemplate->getInstantiatedFromMemberTemplate())
2825 AdjustDepth = PrimaryTemplate->getTemplateDepth();
2826
2827 // We rebuild all template parameters with the uninstantiated depth, and
2828 // build template arguments refer to them.
2829 SmallVector<TemplateArgument> AdjustedAliasTemplateArgs;
2830
2831 for (auto *TP : *AliasTemplate->getTemplateParameters()) {
2832 // Rebuild any internal references to earlier parameters and reindex
2833 // as we go.
2836 Args.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
2837 NamedDecl *NewParam = transformTemplateParameter(
2838 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
2839 /*NewIndex=*/AdjustedAliasTemplateArgs.size(),
2840 getTemplateParameterDepth(TP) + AdjustDepth);
2841
2842 auto NewTemplateArgument = Context.getCanonicalTemplateArgument(
2843 Context.getInjectedTemplateArg(NewParam));
2844 AdjustedAliasTemplateArgs.push_back(NewTemplateArgument);
2845 }
2846 // Template arguments used to transform the template arguments in
2847 // DeducedResults.
2848 SmallVector<TemplateArgument> TemplateArgsForBuildingRC(
2849 F->getTemplateParameters()->size());
2850 // Transform the transformed template args
2853 Args.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
2854
2855 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
2856 const auto &D = DeduceResults[Index];
2857 if (D.isNull())
2858 continue;
2859 TemplateArgumentLoc Input =
2861 TemplateArgumentLoc Output;
2862 if (!SemaRef.SubstTemplateArgument(Input, Args, Output)) {
2863 assert(TemplateArgsForBuildingRC[Index].isNull() &&
2864 "InstantiatedArgs must be null before setting");
2865 TemplateArgsForBuildingRC[Index] = Output.getArgument();
2866 }
2867 }
2868
2869 // A list of template arguments for transforming the require-clause of F.
2870 // It must contain the entire set of template argument lists.
2871 MultiLevelTemplateArgumentList ArgsForBuildingRC;
2873 ArgsForBuildingRC.addOuterTemplateArguments(TemplateArgsForBuildingRC);
2874 // For 2), if the underlying F is instantiated from a member template, we need
2875 // the entire template argument list, as the constraint AST in the
2876 // require-clause of F remains completely uninstantiated.
2877 //
2878 // For example:
2879 // template <typename T> // depth 0
2880 // struct Outer {
2881 // template <typename U>
2882 // struct Foo { Foo(U); };
2883 //
2884 // template <typename U> // depth 1
2885 // requires C<U>
2886 // Foo(U) -> Foo<int>;
2887 // };
2888 // template <typename U>
2889 // using AFoo = Outer<int>::Foo<U>;
2890 //
2891 // In this scenario, the deduction guide for `Foo` inside `Outer<int>`:
2892 // - The occurrence of U in the require-expression is [depth:1, index:0]
2893 // - The occurrence of U in the function parameter is [depth:0, index:0]
2894 // - The template parameter of U is [depth:0, index:0]
2895 //
2896 // We add the outer template arguments which is [int] to the multi-level arg
2897 // list to ensure that the occurrence U in `C<U>` will be replaced with int
2898 // during the substitution.
2900 auto OuterLevelArgs = SemaRef.getTemplateInstantiationArgs(
2901 F, F->getLexicalDeclContext(),
2902 /*Final=*/false, /*Innermost=*/std::nullopt,
2903 /*RelativeToPrimary=*/true,
2904 /*Pattern=*/nullptr,
2905 /*ForConstraintInstantiation=*/true);
2906 for (auto It : OuterLevelArgs)
2907 ArgsForBuildingRC.addOuterTemplateArguments(It.Args);
2908 }
2909
2910 ExprResult E = SemaRef.SubstExpr(RC, ArgsForBuildingRC);
2911 if (E.isInvalid())
2912 return nullptr;
2913
2914 auto Conjunction =
2915 SemaRef.BuildBinOp(SemaRef.getCurScope(), SourceLocation{},
2916 BinaryOperatorKind::BO_LAnd, E.get(), IsDeducible);
2917 if (Conjunction.isInvalid())
2918 return nullptr;
2919 return Conjunction.getAs<Expr>();
2920}
2921// Build the is_deducible constraint for the alias deduction guides.
2922// [over.match.class.deduct]p3.3:
2923// ... and a constraint that is satisfied if and only if the arguments
2924// of A are deducible (see below) from the return type.
2925Expr *buildIsDeducibleConstraint(Sema &SemaRef,
2927 QualType ReturnType,
2928 SmallVector<NamedDecl *> TemplateParams) {
2929 ASTContext &Context = SemaRef.Context;
2930 // Constraint AST nodes must use uninstantiated depth.
2931 if (auto *PrimaryTemplate =
2932 AliasTemplate->getInstantiatedFromMemberTemplate()) {
2934
2935 // Adjust the depth for TemplateParams.
2936 unsigned AdjustDepth = PrimaryTemplate->getTemplateDepth();
2937 SmallVector<TemplateArgument> TransformedTemplateArgs;
2938 for (auto *TP : TemplateParams) {
2939 // Rebuild any internal references to earlier parameters and reindex
2940 // as we go.
2943 Args.addOuterTemplateArguments(TransformedTemplateArgs);
2944 NamedDecl *NewParam = transformTemplateParameter(
2945 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
2946 /*NewIndex=*/TransformedTemplateArgs.size(),
2947 getTemplateParameterDepth(TP) + AdjustDepth);
2948
2949 auto NewTemplateArgument = Context.getCanonicalTemplateArgument(
2950 Context.getInjectedTemplateArg(NewParam));
2951 TransformedTemplateArgs.push_back(NewTemplateArgument);
2952 }
2953 // Transformed the ReturnType to restore the uninstantiated depth.
2956 Args.addOuterTemplateArguments(TransformedTemplateArgs);
2957 ReturnType = SemaRef.SubstType(
2958 ReturnType, Args, AliasTemplate->getLocation(),
2960 };
2961
2962 SmallVector<TypeSourceInfo *> IsDeducibleTypeTraitArgs = {
2965 TemplateName(AliasTemplate), /*DeducedType=*/QualType(),
2966 /*IsDependent=*/true)), // template specialization type whose
2967 // arguments will be deduced.
2969 ReturnType), // type from which template arguments are deduced.
2970 };
2971 return TypeTraitExpr::Create(
2972 Context, Context.getLogicalOperationType(), AliasTemplate->getLocation(),
2973 TypeTrait::BTT_IsDeducible, IsDeducibleTypeTraitArgs,
2974 AliasTemplate->getLocation(), /*Value*/ false);
2975}
2976
2977std::pair<TemplateDecl *, llvm::ArrayRef<TemplateArgument>>
2978getRHSTemplateDeclAndArgs(Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate) {
2979 // Unwrap the sugared ElaboratedType.
2980 auto RhsType = AliasTemplate->getTemplatedDecl()
2981 ->getUnderlyingType()
2982 .getSingleStepDesugaredType(SemaRef.Context);
2983 TemplateDecl *Template = nullptr;
2984 llvm::ArrayRef<TemplateArgument> AliasRhsTemplateArgs;
2985 if (const auto *TST = RhsType->getAs<TemplateSpecializationType>()) {
2986 // Cases where the RHS of the alias is dependent. e.g.
2987 // template<typename T>
2988 // using AliasFoo1 = Foo<T>; // a class/type alias template specialization
2989 Template = TST->getTemplateName().getAsTemplateDecl();
2990 AliasRhsTemplateArgs = TST->template_arguments();
2991 } else if (const auto *RT = RhsType->getAs<RecordType>()) {
2992 // Cases where template arguments in the RHS of the alias are not
2993 // dependent. e.g.
2994 // using AliasFoo = Foo<bool>;
2995 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
2996 RT->getAsCXXRecordDecl())) {
2997 Template = CTSD->getSpecializedTemplate();
2998 AliasRhsTemplateArgs = CTSD->getTemplateArgs().asArray();
2999 }
3000 } else {
3001 assert(false && "unhandled RHS type of the alias");
3002 }
3003 return {Template, AliasRhsTemplateArgs};
3004}
3005
3006// Build deduction guides for a type alias template from the given underlying
3007// deduction guide F.
3009BuildDeductionGuideForTypeAlias(Sema &SemaRef,
3013 Sema::InstantiatingTemplate BuildingDeductionGuides(
3014 SemaRef, AliasTemplate->getLocation(), F,
3016 if (BuildingDeductionGuides.isInvalid())
3017 return nullptr;
3018
3019 auto &Context = SemaRef.Context;
3020 auto [Template, AliasRhsTemplateArgs] =
3021 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
3022
3023 auto RType = F->getTemplatedDecl()->getReturnType();
3024 // The (trailing) return type of the deduction guide.
3025 const TemplateSpecializationType *FReturnType =
3027 if (const auto *InjectedCNT = RType->getAs<InjectedClassNameType>())
3028 // implicitly-generated deduction guide.
3029 FReturnType = InjectedCNT->getInjectedTST();
3030 else if (const auto *ET = RType->getAs<ElaboratedType>())
3031 // explicit deduction guide.
3032 FReturnType = ET->getNamedType()->getAs<TemplateSpecializationType>();
3033 assert(FReturnType && "expected to see a return type");
3034 // Deduce template arguments of the deduction guide f from the RHS of
3035 // the alias.
3036 //
3037 // C++ [over.match.class.deduct]p3: ...For each function or function
3038 // template f in the guides of the template named by the
3039 // simple-template-id of the defining-type-id, the template arguments
3040 // of the return type of f are deduced from the defining-type-id of A
3041 // according to the process in [temp.deduct.type] with the exception
3042 // that deduction does not fail if not all template arguments are
3043 // deduced.
3044 //
3045 //
3046 // template<typename X, typename Y>
3047 // f(X, Y) -> f<Y, X>;
3048 //
3049 // template<typename U>
3050 // using alias = f<int, U>;
3051 //
3052 // The RHS of alias is f<int, U>, we deduced the template arguments of
3053 // the return type of the deduction guide from it: Y->int, X->U
3054 sema::TemplateDeductionInfo TDeduceInfo(Loc);
3055 // Must initialize n elements, this is required by DeduceTemplateArguments.
3057 F->getTemplateParameters()->size());
3058
3059 // FIXME: DeduceTemplateArguments stops immediately at the first
3060 // non-deducible template argument. However, this doesn't seem to casue
3061 // issues for practice cases, we probably need to extend it to continue
3062 // performing deduction for rest of arguments to align with the C++
3063 // standard.
3065 F->getTemplateParameters(), FReturnType->template_arguments(),
3066 AliasRhsTemplateArgs, TDeduceInfo, DeduceResults,
3067 /*NumberOfArgumentsMustMatch=*/false);
3068
3070 SmallVector<unsigned> NonDeducedTemplateParamsInFIndex;
3071 // !!NOTE: DeduceResults respects the sequence of template parameters of
3072 // the deduction guide f.
3073 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
3074 if (const auto &D = DeduceResults[Index]; !D.isNull()) // Deduced
3075 DeducedArgs.push_back(D);
3076 else
3077 NonDeducedTemplateParamsInFIndex.push_back(Index);
3078 }
3079 auto DeducedAliasTemplateParams =
3080 TemplateParamsReferencedInTemplateArgumentList(
3081 AliasTemplate->getTemplateParameters()->asArray(), DeducedArgs);
3082 // All template arguments null by default.
3083 SmallVector<TemplateArgument> TemplateArgsForBuildingFPrime(
3084 F->getTemplateParameters()->size());
3085
3086 // Create a template parameter list for the synthesized deduction guide f'.
3087 //
3088 // C++ [over.match.class.deduct]p3.2:
3089 // If f is a function template, f' is a function template whose template
3090 // parameter list consists of all the template parameters of A
3091 // (including their default template arguments) that appear in the above
3092 // deductions or (recursively) in their default template arguments
3093 SmallVector<NamedDecl *> FPrimeTemplateParams;
3094 // Store template arguments that refer to the newly-created template
3095 // parameters, used for building `TemplateArgsForBuildingFPrime`.
3096 SmallVector<TemplateArgument, 16> TransformedDeducedAliasArgs(
3097 AliasTemplate->getTemplateParameters()->size());
3098
3099 for (unsigned AliasTemplateParamIdx : DeducedAliasTemplateParams) {
3100 auto *TP =
3101 AliasTemplate->getTemplateParameters()->getParam(AliasTemplateParamIdx);
3102 // Rebuild any internal references to earlier parameters and reindex as
3103 // we go.
3106 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
3107 NamedDecl *NewParam = transformTemplateParameter(
3108 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
3109 /*NewIndex=*/FPrimeTemplateParams.size(),
3110 getTemplateParameterDepth(TP));
3111 FPrimeTemplateParams.push_back(NewParam);
3112
3113 auto NewTemplateArgument = Context.getCanonicalTemplateArgument(
3114 Context.getInjectedTemplateArg(NewParam));
3115 TransformedDeducedAliasArgs[AliasTemplateParamIdx] = NewTemplateArgument;
3116 }
3117 // ...followed by the template parameters of f that were not deduced
3118 // (including their default template arguments)
3119 for (unsigned FTemplateParamIdx : NonDeducedTemplateParamsInFIndex) {
3120 auto *TP = F->getTemplateParameters()->getParam(FTemplateParamIdx);
3123 // We take a shortcut here, it is ok to reuse the
3124 // TemplateArgsForBuildingFPrime.
3125 Args.addOuterTemplateArguments(TemplateArgsForBuildingFPrime);
3126 NamedDecl *NewParam = transformTemplateParameter(
3127 SemaRef, F->getDeclContext(), TP, Args, FPrimeTemplateParams.size(),
3128 getTemplateParameterDepth(TP));
3129 FPrimeTemplateParams.push_back(NewParam);
3130
3131 assert(TemplateArgsForBuildingFPrime[FTemplateParamIdx].isNull() &&
3132 "The argument must be null before setting");
3133 TemplateArgsForBuildingFPrime[FTemplateParamIdx] =
3135 Context.getInjectedTemplateArg(NewParam));
3136 }
3137
3138 // To form a deduction guide f' from f, we leverage clang's instantiation
3139 // mechanism, we construct a template argument list where the template
3140 // arguments refer to the newly-created template parameters of f', and
3141 // then apply instantiation on this template argument list to instantiate
3142 // f, this ensures all template parameter occurrences are updated
3143 // correctly.
3144 //
3145 // The template argument list is formed from the `DeducedArgs`, two parts:
3146 // 1) appeared template parameters of alias: transfrom the deduced
3147 // template argument;
3148 // 2) non-deduced template parameters of f: rebuild a
3149 // template argument;
3150 //
3151 // 2) has been built already (when rebuilding the new template
3152 // parameters), we now perform 1).
3155 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
3156 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
3157 const auto &D = DeduceResults[Index];
3158 if (D.isNull()) {
3159 // 2): Non-deduced template parameter has been built already.
3160 assert(!TemplateArgsForBuildingFPrime[Index].isNull() &&
3161 "template arguments for non-deduced template parameters should "
3162 "be been set!");
3163 continue;
3164 }
3165 TemplateArgumentLoc Input =
3167 TemplateArgumentLoc Output;
3168 if (!SemaRef.SubstTemplateArgument(Input, Args, Output)) {
3169 assert(TemplateArgsForBuildingFPrime[Index].isNull() &&
3170 "InstantiatedArgs must be null before setting");
3171 TemplateArgsForBuildingFPrime[Index] = Output.getArgument();
3172 }
3173 }
3174
3175 auto *TemplateArgListForBuildingFPrime =
3176 TemplateArgumentList::CreateCopy(Context, TemplateArgsForBuildingFPrime);
3177 // Form the f' by substituting the template arguments into f.
3178 if (auto *FPrime = SemaRef.InstantiateFunctionDeclaration(
3179 F, TemplateArgListForBuildingFPrime, AliasTemplate->getLocation(),
3181 auto *GG = cast<CXXDeductionGuideDecl>(FPrime);
3182
3183 Expr *IsDeducible = buildIsDeducibleConstraint(
3184 SemaRef, AliasTemplate, FPrime->getReturnType(), FPrimeTemplateParams);
3185 Expr *RequiresClause = buildAssociatedConstraints(
3186 SemaRef, F, AliasTemplate, DeduceResults, IsDeducible);
3187
3188 // FIXME: implement the is_deducible constraint per C++
3189 // [over.match.class.deduct]p3.3:
3190 // ... and a constraint that is satisfied if and only if the arguments
3191 // of A are deducible (see below) from the return type.
3192 auto *FPrimeTemplateParamList = TemplateParameterList::Create(
3193 Context, AliasTemplate->getTemplateParameters()->getTemplateLoc(),
3194 AliasTemplate->getTemplateParameters()->getLAngleLoc(),
3195 FPrimeTemplateParams,
3196 AliasTemplate->getTemplateParameters()->getRAngleLoc(),
3197 /*RequiresClause=*/RequiresClause);
3198 FunctionTemplateDecl *Result = buildDeductionGuide(
3199 SemaRef, AliasTemplate, FPrimeTemplateParamList,
3200 GG->getCorrespondingConstructor(), GG->getExplicitSpecifier(),
3201 GG->getTypeSourceInfo(), AliasTemplate->getBeginLoc(),
3202 AliasTemplate->getLocation(), AliasTemplate->getEndLoc(),
3203 F->isImplicit());
3204 cast<CXXDeductionGuideDecl>(Result->getTemplatedDecl())
3205 ->setDeductionCandidateKind(GG->getDeductionCandidateKind());
3206 return Result;
3207 }
3208 return nullptr;
3209}
3210
3211void DeclareImplicitDeductionGuidesForTypeAlias(
3213 if (AliasTemplate->isInvalidDecl())
3214 return;
3215 auto &Context = SemaRef.Context;
3216 // FIXME: if there is an explicit deduction guide after the first use of the
3217 // type alias usage, we will not cover this explicit deduction guide. fix this
3218 // case.
3219 if (hasDeclaredDeductionGuides(
3221 AliasTemplate->getDeclContext()))
3222 return;
3223 auto [Template, AliasRhsTemplateArgs] =
3224 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
3225 if (!Template)
3226 return;
3227 DeclarationNameInfo NameInfo(
3228 Context.DeclarationNames.getCXXDeductionGuideName(Template), Loc);
3229 LookupResult Guides(SemaRef, NameInfo, clang::Sema::LookupOrdinaryName);
3230 SemaRef.LookupQualifiedName(Guides, Template->getDeclContext());
3231 Guides.suppressDiagnostics();
3232
3233 for (auto *G : Guides) {
3234 FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(G);
3235 if (!F)
3236 continue;
3237 // The **aggregate** deduction guides are handled in a different code path
3238 // (DeclareAggregateDeductionGuideFromInitList), which involves the tricky
3239 // cache.
3240 if (cast<CXXDeductionGuideDecl>(F->getTemplatedDecl())
3241 ->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
3242 continue;
3243
3244 BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate, F, Loc);
3245 }
3246}
3247
3248// Build an aggregate deduction guide for a type alias template.
3249FunctionTemplateDecl *DeclareAggregateDeductionGuideForTypeAlias(
3252 TemplateDecl *RHSTemplate =
3253 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate).first;
3254 if (!RHSTemplate)
3255 return nullptr;
3256 auto *RHSDeductionGuide = SemaRef.DeclareAggregateDeductionGuideFromInitList(
3257 RHSTemplate, ParamTypes, Loc);
3258 if (!RHSDeductionGuide)
3259 return nullptr;
3260 return BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate,
3261 RHSDeductionGuide, Loc);
3262}
3263
3264} // namespace
3265
3267 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
3269 llvm::FoldingSetNodeID ID;
3270 ID.AddPointer(Template);
3271 for (auto &T : ParamTypes)
3272 T.getCanonicalType().Profile(ID);
3273 unsigned Hash = ID.ComputeHash();
3274
3275 auto Found = AggregateDeductionCandidates.find(Hash);
3276 if (Found != AggregateDeductionCandidates.end()) {
3277 CXXDeductionGuideDecl *GD = Found->getSecond();
3278 return GD->getDescribedFunctionTemplate();
3279 }
3280
3281 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
3282 if (auto *FTD = DeclareAggregateDeductionGuideForTypeAlias(
3283 *this, AliasTemplate, ParamTypes, Loc)) {
3284 auto *GD = cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
3285 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
3287 return FTD;
3288 }
3289 }
3290
3291 if (CXXRecordDecl *DefRecord =
3292 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
3293 if (TemplateDecl *DescribedTemplate =
3294 DefRecord->getDescribedClassTemplate())
3295 Template = DescribedTemplate;
3296 }
3297
3298 DeclContext *DC = Template->getDeclContext();
3299 if (DC->isDependentContext())
3300 return nullptr;
3301
3302 ConvertConstructorToDeductionGuideTransform Transform(
3303 *this, cast<ClassTemplateDecl>(Template));
3304 if (!isCompleteType(Loc, Transform.DeducedType))
3305 return nullptr;
3306
3307 // In case we were expanding a pack when we attempted to declare deduction
3308 // guides, turn off pack expansion for everything we're about to do.
3309 ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
3310 /*NewSubstitutionIndex=*/-1);
3311 // Create a template instantiation record to track the "instantiation" of
3312 // constructors into deduction guides.
3313 InstantiatingTemplate BuildingDeductionGuides(
3314 *this, Loc, Template,
3316 if (BuildingDeductionGuides.isInvalid())
3317 return nullptr;
3318
3319 ClassTemplateDecl *Pattern =
3320 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
3321 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
3322
3323 auto *FTD = cast<FunctionTemplateDecl>(
3324 Transform.buildSimpleDeductionGuide(ParamTypes));
3325 SavedContext.pop();
3326 auto *GD = cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
3327 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
3329 return FTD;
3330}
3331
3334 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
3335 DeclareImplicitDeductionGuidesForTypeAlias(*this, AliasTemplate, Loc);
3336 return;
3337 }
3338 if (CXXRecordDecl *DefRecord =
3339 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
3340 if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate())
3341 Template = DescribedTemplate;
3342 }
3343
3344 DeclContext *DC = Template->getDeclContext();
3345 if (DC->isDependentContext())
3346 return;
3347
3348 ConvertConstructorToDeductionGuideTransform Transform(
3349 *this, cast<ClassTemplateDecl>(Template));
3350 if (!isCompleteType(Loc, Transform.DeducedType))
3351 return;
3352
3353 if (hasDeclaredDeductionGuides(Transform.DeductionGuideName, DC))
3354 return;
3355
3356 // In case we were expanding a pack when we attempted to declare deduction
3357 // guides, turn off pack expansion for everything we're about to do.
3358 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3359 // Create a template instantiation record to track the "instantiation" of
3360 // constructors into deduction guides.
3361 InstantiatingTemplate BuildingDeductionGuides(
3362 *this, Loc, Template,
3364 if (BuildingDeductionGuides.isInvalid())
3365 return;
3366
3367 // Convert declared constructors into deduction guide templates.
3368 // FIXME: Skip constructors for which deduction must necessarily fail (those
3369 // for which some class template parameter without a default argument never
3370 // appears in a deduced context).
3371 ClassTemplateDecl *Pattern =
3372 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
3373 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
3374 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
3375 bool AddedAny = false;
3376 for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) {
3377 D = D->getUnderlyingDecl();
3378 if (D->isInvalidDecl() || D->isImplicit())
3379 continue;
3380
3381 D = cast<NamedDecl>(D->getCanonicalDecl());
3382
3383 // Within C++20 modules, we may have multiple same constructors in
3384 // multiple same RecordDecls. And it doesn't make sense to create
3385 // duplicated deduction guides for the duplicated constructors.
3386 if (ProcessedCtors.count(D))
3387 continue;
3388
3389 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
3390 auto *CD =
3391 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
3392 // Class-scope explicit specializations (MS extension) do not result in
3393 // deduction guides.
3394 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
3395 continue;
3396
3397 // Cannot make a deduction guide when unparsed arguments are present.
3398 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
3399 return !P || P->hasUnparsedDefaultArg();
3400 }))
3401 continue;
3402
3403 ProcessedCtors.insert(D);
3404 Transform.transformConstructor(FTD, CD);
3405 AddedAny = true;
3406 }
3407
3408 // C++17 [over.match.class.deduct]
3409 // -- If C is not defined or does not declare any constructors, an
3410 // additional function template derived as above from a hypothetical
3411 // constructor C().
3412 if (!AddedAny)
3413 Transform.buildSimpleDeductionGuide(std::nullopt);
3414
3415 // -- An additional function template derived as above from a hypothetical
3416 // constructor C(C), called the copy deduction candidate.
3417 cast<CXXDeductionGuideDecl>(
3418 cast<FunctionTemplateDecl>(
3419 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
3420 ->getTemplatedDecl())
3421 ->setDeductionCandidateKind(DeductionCandidate::Copy);
3422
3423 SavedContext.pop();
3424}
3425
3426/// Diagnose the presence of a default template argument on a
3427/// template parameter, which is ill-formed in certain contexts.
3428///
3429/// \returns true if the default template argument should be dropped.
3432 SourceLocation ParamLoc,
3433 SourceRange DefArgRange) {
3434 switch (TPC) {
3438 return false;
3439
3442 // C++ [temp.param]p9:
3443 // A default template-argument shall not be specified in a
3444 // function template declaration or a function template
3445 // definition [...]
3446 // If a friend function template declaration specifies a default
3447 // template-argument, that declaration shall be a definition and shall be
3448 // the only declaration of the function template in the translation unit.
3449 // (C++98/03 doesn't have this wording; see DR226).
3450 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
3451 diag::warn_cxx98_compat_template_parameter_default_in_function_template
3452 : diag::ext_template_parameter_default_in_function_template)
3453 << DefArgRange;
3454 return false;
3455
3457 // C++0x [temp.param]p9:
3458 // A default template-argument shall not be specified in the
3459 // template-parameter-lists of the definition of a member of a
3460 // class template that appears outside of the member's class.
3461 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
3462 << DefArgRange;
3463 return true;
3464
3467 // C++ [temp.param]p9:
3468 // A default template-argument shall not be specified in a
3469 // friend template declaration.
3470 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
3471 << DefArgRange;
3472 return true;
3473
3474 // FIXME: C++0x [temp.param]p9 allows default template-arguments
3475 // for friend function templates if there is only a single
3476 // declaration (and it is a definition). Strange!
3477 }
3478
3479 llvm_unreachable("Invalid TemplateParamListContext!");
3480}
3481
3482/// Check for unexpanded parameter packs within the template parameters
3483/// of a template template parameter, recursively.
3486 // A template template parameter which is a parameter pack is also a pack
3487 // expansion.
3488 if (TTP->isParameterPack())
3489 return false;
3490
3492 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3493 NamedDecl *P = Params->getParam(I);
3494 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
3495 if (!TTP->isParameterPack())
3496 if (const TypeConstraint *TC = TTP->getTypeConstraint())
3497 if (TC->hasExplicitTemplateArgs())
3498 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3501 return true;
3502 continue;
3503 }
3504
3505 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
3506 if (!NTTP->isParameterPack() &&
3507 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
3508 NTTP->getTypeSourceInfo(),
3510 return true;
3511
3512 continue;
3513 }
3514
3515 if (TemplateTemplateParmDecl *InnerTTP
3516 = dyn_cast<TemplateTemplateParmDecl>(P))
3517 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
3518 return true;
3519 }
3520
3521 return false;
3522}
3523
3524/// Checks the validity of a template parameter list, possibly
3525/// considering the template parameter list from a previous
3526/// declaration.
3527///
3528/// If an "old" template parameter list is provided, it must be
3529/// equivalent (per TemplateParameterListsAreEqual) to the "new"
3530/// template parameter list.
3531///
3532/// \param NewParams Template parameter list for a new template
3533/// declaration. This template parameter list will be updated with any
3534/// default arguments that are carried through from the previous
3535/// template parameter list.
3536///
3537/// \param OldParams If provided, template parameter list from a
3538/// previous declaration of the same template. Default template
3539/// arguments will be merged from the old template parameter list to
3540/// the new template parameter list.
3541///
3542/// \param TPC Describes the context in which we are checking the given
3543/// template parameter list.
3544///
3545/// \param SkipBody If we might have already made a prior merged definition
3546/// of this template visible, the corresponding body-skipping information.
3547/// Default argument redefinition is not an error when skipping such a body,
3548/// because (under the ODR) we can assume the default arguments are the same
3549/// as the prior merged definition.
3550///
3551/// \returns true if an error occurred, false otherwise.
3553 TemplateParameterList *OldParams,
3555 SkipBodyInfo *SkipBody) {
3556 bool Invalid = false;
3557
3558 // C++ [temp.param]p10:
3559 // The set of default template-arguments available for use with a
3560 // template declaration or definition is obtained by merging the
3561 // default arguments from the definition (if in scope) and all
3562 // declarations in scope in the same way default function
3563 // arguments are (8.3.6).
3564 bool SawDefaultArgument = false;
3565 SourceLocation PreviousDefaultArgLoc;
3566
3567 // Dummy initialization to avoid warnings.
3568 TemplateParameterList::iterator OldParam = NewParams->end();
3569 if (OldParams)
3570 OldParam = OldParams->begin();
3571
3572 bool RemoveDefaultArguments = false;
3573 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3574 NewParamEnd = NewParams->end();
3575 NewParam != NewParamEnd; ++NewParam) {
3576 // Whether we've seen a duplicate default argument in the same translation
3577 // unit.
3578 bool RedundantDefaultArg = false;
3579 // Whether we've found inconsis inconsitent default arguments in different
3580 // translation unit.
3581 bool InconsistentDefaultArg = false;
3582 // The name of the module which contains the inconsistent default argument.
3583 std::string PrevModuleName;
3584
3585 SourceLocation OldDefaultLoc;
3586 SourceLocation NewDefaultLoc;
3587
3588 // Variable used to diagnose missing default arguments
3589 bool MissingDefaultArg = false;
3590
3591 // Variable used to diagnose non-final parameter packs
3592 bool SawParameterPack = false;
3593
3594 if (TemplateTypeParmDecl *NewTypeParm
3595 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
3596 // Check the presence of a default argument here.
3597 if (NewTypeParm->hasDefaultArgument() &&
3599 NewTypeParm->getLocation(),
3600 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
3601 .getSourceRange()))
3602 NewTypeParm->removeDefaultArgument();
3603
3604 // Merge default arguments for template type parameters.
3605 TemplateTypeParmDecl *OldTypeParm
3606 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
3607 if (NewTypeParm->isParameterPack()) {
3608 assert(!NewTypeParm->hasDefaultArgument() &&
3609 "Parameter packs can't have a default argument!");
3610 SawParameterPack = true;
3611 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
3612 NewTypeParm->hasDefaultArgument() &&
3613 (!SkipBody || !SkipBody->ShouldSkip)) {
3614 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
3615 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
3616 SawDefaultArgument = true;
3617
3618 if (!OldTypeParm->getOwningModule())
3619 RedundantDefaultArg = true;
3620 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
3621 NewTypeParm)) {
3622 InconsistentDefaultArg = true;
3623 PrevModuleName =
3625 }
3626 PreviousDefaultArgLoc = NewDefaultLoc;
3627 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
3628 // Merge the default argument from the old declaration to the
3629 // new declaration.
3630 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
3631 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
3632 } else if (NewTypeParm->hasDefaultArgument()) {
3633 SawDefaultArgument = true;
3634 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
3635 } else if (SawDefaultArgument)
3636 MissingDefaultArg = true;
3637 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
3638 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
3639 // Check for unexpanded parameter packs.
3640 if (!NewNonTypeParm->isParameterPack() &&
3641 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
3642 NewNonTypeParm->getTypeSourceInfo(),
3644 Invalid = true;
3645 continue;
3646 }
3647
3648 // Check the presence of a default argument here.
3649 if (NewNonTypeParm->hasDefaultArgument() &&
3651 NewNonTypeParm->getLocation(),
3652 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
3653 NewNonTypeParm->removeDefaultArgument();
3654 }
3655
3656 // Merge default arguments for non-type template parameters
3657 NonTypeTemplateParmDecl *OldNonTypeParm
3658 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
3659 if (NewNonTypeParm->isParameterPack()) {
3660 assert(!NewNonTypeParm->hasDefaultArgument() &&
3661 "Parameter packs can't have a default argument!");
3662 if (!NewNonTypeParm->isPackExpansion())
3663 SawParameterPack = true;
3664 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
3665 NewNonTypeParm->hasDefaultArgument() &&
3666 (!SkipBody || !SkipBody->ShouldSkip)) {
3667 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
3668 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
3669 SawDefaultArgument = true;
3670 if (!OldNonTypeParm->getOwningModule())
3671 RedundantDefaultArg = true;
3672 else if (!getASTContext().isSameDefaultTemplateArgument(
3673 OldNonTypeParm, NewNonTypeParm)) {
3674 InconsistentDefaultArg = true;
3675 PrevModuleName =
3676 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
3677 }
3678 PreviousDefaultArgLoc = NewDefaultLoc;
3679 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
3680 // Merge the default argument from the old declaration to the
3681 // new declaration.
3682 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
3683 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
3684 } else if (NewNonTypeParm->hasDefaultArgument()) {
3685 SawDefaultArgument = true;
3686 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
3687 } else if (SawDefaultArgument)
3688 MissingDefaultArg = true;
3689 } else {
3690 TemplateTemplateParmDecl *NewTemplateParm
3691 = cast<TemplateTemplateParmDecl>(*NewParam);
3692
3693 // Check for unexpanded parameter packs, recursively.
3694 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
3695 Invalid = true;
3696 continue;
3697 }
3698
3699 // Check the presence of a default argument here.
3700 if (NewTemplateParm->hasDefaultArgument() &&
3702 NewTemplateParm->getLocation(),
3703 NewTemplateParm->getDefaultArgument().getSourceRange()))
3704 NewTemplateParm->removeDefaultArgument();
3705
3706 // Merge default arguments for template template parameters
3707 TemplateTemplateParmDecl *OldTemplateParm
3708 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
3709 if (NewTemplateParm->isParameterPack()) {
3710 assert(!NewTemplateParm->hasDefaultArgument() &&
3711 "Parameter packs can't have a default argument!");
3712 if (!NewTemplateParm->isPackExpansion())
3713 SawParameterPack = true;
3714 } else if (OldTemplateParm &&
3715 hasVisibleDefaultArgument(OldTemplateParm) &&
3716 NewTemplateParm->hasDefaultArgument() &&
3717 (!SkipBody || !SkipBody->ShouldSkip)) {
3718 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
3719 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
3720 SawDefaultArgument = true;
3721 if (!OldTemplateParm->getOwningModule())
3722 RedundantDefaultArg = true;
3723 else if (!getASTContext().isSameDefaultTemplateArgument(
3724 OldTemplateParm, NewTemplateParm)) {
3725 InconsistentDefaultArg = true;
3726 PrevModuleName =
3727 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
3728 }
3729 PreviousDefaultArgLoc = NewDefaultLoc;
3730 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
3731 // Merge the default argument from the old declaration to the
3732 // new declaration.
3733 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
3734 PreviousDefaultArgLoc
3735 = OldTemplateParm->getDefaultArgument().getLocation();
3736 } else if (NewTemplateParm->hasDefaultArgument()) {
3737 SawDefaultArgument = true;
3738 PreviousDefaultArgLoc
3739 = NewTemplateParm->getDefaultArgument().getLocation();
3740 } else if (SawDefaultArgument)
3741 MissingDefaultArg = true;
3742 }
3743
3744 // C++11 [temp.param]p11:
3745 // If a template parameter of a primary class template or alias template
3746 // is a template parameter pack, it shall be the last template parameter.
3747 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
3748 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
3749 TPC == TPC_TypeAliasTemplate)) {
3750 Diag((*NewParam)->getLocation(),
3751 diag::err_template_param_pack_must_be_last_template_parameter);
3752 Invalid = true;
3753 }
3754
3755 // [basic.def.odr]/13:
3756 // There can be more than one definition of a
3757 // ...
3758 // default template argument
3759 // ...
3760 // in a program provided that each definition appears in a different
3761 // translation unit and the definitions satisfy the [same-meaning
3762 // criteria of the ODR].
3763 //
3764 // Simply, the design of modules allows the definition of template default
3765 // argument to be repeated across translation unit. Note that the ODR is
3766 // checked elsewhere. But it is still not allowed to repeat template default
3767 // argument in the same translation unit.
3768 if (RedundantDefaultArg) {
3769 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
3770 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
3771 Invalid = true;
3772 } else if (InconsistentDefaultArg) {
3773 // We could only diagnose about the case that the OldParam is imported.
3774 // The case NewParam is imported should be handled in ASTReader.
3775 Diag(NewDefaultLoc,
3776 diag::err_template_param_default_arg_inconsistent_redefinition);
3777 Diag(OldDefaultLoc,
3778 diag::note_template_param_prev_default_arg_in_other_module)
3779 << PrevModuleName;
3780 Invalid = true;
3781 } else if (MissingDefaultArg &&
3782 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
3783 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
3784 // C++ 23[temp.param]p14:
3785 // If a template-parameter of a class template, variable template, or
3786 // alias template has a default template argument, each subsequent
3787 // template-parameter shall either have a default template argument
3788 // supplied or be a template parameter pack.
3789 Diag((*NewParam)->getLocation(),
3790 diag::err_template_param_default_arg_missing);
3791 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3792 Invalid = true;
3793 RemoveDefaultArguments = true;
3794 }
3795
3796 // If we have an old template parameter list that we're merging
3797 // in, move on to the next parameter.
3798 if (OldParams)
3799 ++OldParam;
3800 }
3801
3802 // We were missing some default arguments at the end of the list, so remove
3803 // all of the default arguments.
3804 if (RemoveDefaultArguments) {
3805 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3806 NewParamEnd = NewParams->end();
3807 NewParam != NewParamEnd; ++NewParam) {
3808 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
3809 TTP->removeDefaultArgument();
3810 else if (NonTypeTemplateParmDecl *NTTP
3811 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
3812 NTTP->removeDefaultArgument();
3813 else
3814 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
3815 }
3816 }
3817
3818 return Invalid;
3819}
3820
3821namespace {
3822
3823/// A class which looks for a use of a certain level of template
3824/// parameter.
3825struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3827
3828 unsigned Depth;
3829
3830 // Whether we're looking for a use of a template parameter that makes the
3831 // overall construct type-dependent / a dependent type. This is strictly
3832 // best-effort for now; we may fail to match at all for a dependent type
3833 // in some cases if this is set.
3834 bool IgnoreNonTypeDependent;
3835
3836 bool Match;
3837 SourceLocation MatchLoc;
3838
3839 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3840 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3841 Match(false) {}
3842
3843 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3844 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3845 NamedDecl *ND = Params->getParam(0);
3846 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
3847 Depth = PD->getDepth();
3848 } else if (NonTypeTemplateParmDecl *PD =
3849 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
3850 Depth = PD->getDepth();
3851 } else {
3852 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
3853 }
3854 }
3855
3856 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3857 if (ParmDepth >= Depth) {
3858 Match = true;
3859 MatchLoc = Loc;
3860 return true;
3861 }
3862 return false;
3863 }
3864
3865 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3866 // Prune out non-type-dependent expressions if requested. This can
3867 // sometimes result in us failing to find a template parameter reference
3868 // (if a value-dependent expression creates a dependent type), but this
3869 // mode is best-effort only.
3870 if (auto *E = dyn_cast_or_null<Expr>(S))
3871 if (IgnoreNonTypeDependent && !E->isTypeDependent())
3872 return true;
3873 return super::TraverseStmt(S, Q);
3874 }
3875
3876 bool TraverseTypeLoc(TypeLoc TL) {
3877 if (IgnoreNonTypeDependent && !TL.isNull() &&
3878 !TL.getType()->isDependentType())
3879 return true;
3880 return super::TraverseTypeLoc(TL);
3881 }
3882
3883 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3884 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3885 }
3886
3887 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3888 // For a best-effort search, keep looking until we find a location.
3889 return IgnoreNonTypeDependent || !Matches(T->getDepth());
3890 }
3891
3892 bool TraverseTemplateName(TemplateName N) {
3893 if (TemplateTemplateParmDecl *PD =
3894 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3895 if (Matches(PD->getDepth()))
3896 return false;
3897 return super::TraverseTemplateName(N);
3898 }
3899
3900 bool VisitDeclRefExpr(DeclRefExpr *E) {
3901 if (NonTypeTemplateParmDecl *PD =
3902 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3903 if (Matches(PD->getDepth(), E->getExprLoc()))
3904 return false;
3905 return super::VisitDeclRefExpr(E);
3906 }
3907
3908 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3909 return TraverseType(T->getReplacementType());
3910 }
3911
3912 bool
3913 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3914 return TraverseTemplateArgument(T->getArgumentPack());
3915 }
3916
3917 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3918 return TraverseType(T->getInjectedSpecializationType());
3919 }
3920};
3921} // end anonymous namespace
3922
3923/// Determines whether a given type depends on the given parameter
3924/// list.
3925static bool
3927 if (!Params->size())
3928 return false;
3929
3930 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3931 Checker.TraverseType(T);
3932 return Checker.Match;
3933}
3934
3935// Find the source range corresponding to the named type in the given
3936// nested-name-specifier, if any.
3938 QualType T,
3939 const CXXScopeSpec &SS) {
3941 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3942 if (const Type *CurType = NNS->getAsType()) {
3943 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3944 return NNSLoc.getTypeLoc().getSourceRange();
3945 } else
3946 break;
3947
3948 NNSLoc = NNSLoc.getPrefix();
3949 }
3950
3951 return SourceRange();
3952}
3953
3954/// Match the given template parameter lists to the given scope
3955/// specifier, returning the template parameter list that applies to the
3956/// name.
3957///
3958/// \param DeclStartLoc the start of the declaration that has a scope
3959/// specifier or a template parameter list.
3960///
3961/// \param DeclLoc The location of the declaration itself.
3962///
3963/// \param SS the scope specifier that will be matched to the given template
3964/// parameter lists. This scope specifier precedes a qualified name that is
3965/// being declared.
3966///
3967/// \param TemplateId The template-id following the scope specifier, if there
3968/// is one. Used to check for a missing 'template<>'.
3969///
3970/// \param ParamLists the template parameter lists, from the outermost to the
3971/// innermost template parameter lists.
3972///
3973/// \param IsFriend Whether to apply the slightly different rules for
3974/// matching template parameters to scope specifiers in friend
3975/// declarations.
3976///
3977/// \param IsMemberSpecialization will be set true if the scope specifier
3978/// denotes a fully-specialized type, and therefore this is a declaration of
3979/// a member specialization.
3980///
3981/// \returns the template parameter list, if any, that corresponds to the
3982/// name that is preceded by the scope specifier @p SS. This template
3983/// parameter list may have template parameters (if we're declaring a
3984/// template) or may have no template parameters (if we're declaring a
3985/// template specialization), or may be NULL (if what we're declaring isn't
3986/// itself a template).
3988 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3989 TemplateIdAnnotation *TemplateId,
3990 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3991 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3992 IsMemberSpecialization = false;
3993 Invalid = false;
3994
3995 // The sequence of nested types to which we will match up the template
3996 // parameter lists. We first build this list by starting with the type named
3997 // by the nested-name-specifier and walking out until we run out of types.
3998 SmallVector<QualType, 4> NestedTypes;
3999 QualType T;
4000 if (SS.getScopeRep()) {
4002 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
4004 else
4005 T = QualType(SS.getScopeRep()->getAsType(), 0);
4006 }
4007
4008 // If we found an explicit specialization that prevents us from needing
4009 // 'template<>' headers, this will be set to the location of that
4010 // explicit specialization.
4011 SourceLocation ExplicitSpecLoc;
4012
4013 while (!T.isNull()) {
4014 NestedTypes.push_back(T);
4015
4016 // Retrieve the parent of a record type.
4018 // If this type is an explicit specialization, we're done.
4020 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
4021 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
4022 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
4023 ExplicitSpecLoc = Spec->getLocation();
4024 break;
4025 }
4026 } else if (Record->getTemplateSpecializationKind()
4028 ExplicitSpecLoc = Record->getLocation();
4029 break;
4030 }
4031
4032 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
4034 else
4035 T = QualType();
4036 continue;
4037 }
4038
4039 if (const TemplateSpecializationType *TST
4041 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
4042 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
4044 else
4045 T = QualType();
4046 continue;
4047 }
4048 }
4049
4050 // Look one step prior in a dependent template specialization type.
4051 if (const DependentTemplateSpecializationType *DependentTST
4053 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
4054 T = QualType(NNS->getAsType(), 0);
4055 else
4056 T = QualType();
4057 continue;
4058 }
4059
4060 // Look one step prior in a dependent name type.
4061 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
4062 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
4063 T = QualType(NNS->getAsType(), 0);
4064 else
4065 T = QualType();
4066 continue;
4067 }
4068
4069 // Retrieve the parent of an enumeration type.
4070 if (const EnumType *EnumT = T->getAs<EnumType>()) {
4071 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
4072 // check here.
4073 EnumDecl *Enum = EnumT->getDecl();
4074
4075 // Get to the parent type.
4076 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
4078 else
4079 T = QualType();
4080 continue;
4081 }
4082
4083 T = QualType();
4084 }
4085 // Reverse the nested types list, since we want to traverse from the outermost
4086 // to the innermost while checking template-parameter-lists.
4087 std::reverse(NestedTypes.begin(), NestedTypes.end());
4088
4089 // C++0x [temp.expl.spec]p17:
4090 // A member or a member template may be nested within many
4091 // enclosing class templates. In an explicit specialization for
4092 // such a member, the member declaration shall be preceded by a
4093 // template<> for each enclosing class template that is
4094 // explicitly specialized.
4095 bool SawNonEmptyTemplateParameterList = false;
4096
4097 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
4098 if (SawNonEmptyTemplateParameterList) {
4099 if (!SuppressDiagnostic)
4100 Diag(DeclLoc, diag::err_specialize_member_of_template)
4101 << !Recovery << Range;
4102 Invalid = true;
4103 IsMemberSpecialization = false;
4104 return true;
4105 }
4106
4107 return false;
4108 };
4109
4110 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
4111 // Check that we can have an explicit specialization here.
4112 if (CheckExplicitSpecialization(Range, true))
4113 return true;
4114
4115 // We don't have a template header, but we should.
4116 SourceLocation ExpectedTemplateLoc;
4117 if (!ParamLists.empty())
4118 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
4119 else
4120 ExpectedTemplateLoc = DeclStartLoc;
4121
4122 if (!SuppressDiagnostic)
4123 Diag(DeclLoc, diag::err_template_spec_needs_header)
4124 << Range
4125 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
4126 return false;
4127 };
4128
4129 unsigned ParamIdx = 0;
4130 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
4131 ++TypeIdx) {
4132 T = NestedTypes[TypeIdx];
4133
4134 // Whether we expect a 'template<>' header.
4135 bool NeedEmptyTemplateHeader = false;
4136
4137 // Whether we expect a template header with parameters.
4138 bool NeedNonemptyTemplateHeader = false;
4139
4140 // For a dependent type, the set of template parameters that we
4141 // expect to see.
4142 TemplateParameterList *ExpectedTemplateParams = nullptr;
4143
4144 // C++0x [temp.expl.spec]p15:
4145 // A member or a member template may be nested within many enclosing
4146 // class templates. In an explicit specialization for such a member, the
4147 // member declaration shall be preceded by a template<> for each
4148 // enclosing class template that is explicitly specialized.
4151 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
4152 ExpectedTemplateParams = Partial->getTemplateParameters();
4153 NeedNonemptyTemplateHeader = true;
4154 } else if (Record->isDependentType()) {
4155 if (Record->getDescribedClassTemplate()) {
4156 ExpectedTemplateParams = Record->getDescribedClassTemplate()
4157 ->getTemplateParameters();
4158 NeedNonemptyTemplateHeader = true;
4159 }
4160 } else if (ClassTemplateSpecializationDecl *Spec
4161 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
4162 // C++0x [temp.expl.spec]p4:
4163 // Members of an explicitly specialized class template are defined
4164 // in the same manner as members of normal classes, and not using
4165 // the template<> syntax.
4166 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
4167 NeedEmptyTemplateHeader = true;
4168 else
4169 continue;
4170 } else if (Record->getTemplateSpecializationKind()) {
4171 if (Record->getTemplateSpecializationKind()
4173 TypeIdx == NumTypes - 1)
4174 IsMemberSpecialization = true;
4175
4176 continue;
4177 }
4178 } else if (const TemplateSpecializationType *TST
4180 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
4181 ExpectedTemplateParams = Template->getTemplateParameters();
4182 NeedNonemptyTemplateHeader = true;
4183 }
4185 // FIXME: We actually could/should check the template arguments here
4186 // against the corresponding template parameter list.
4187 NeedNonemptyTemplateHeader = false;
4188 }
4189
4190 // C++ [temp.expl.spec]p16:
4191 // In an explicit specialization declaration for a member of a class
4192 // template or a member template that ap- pears in namespace scope, the
4193 // member template and some of its enclosing class templates may remain
4194 // unspecialized, except that the declaration shall not explicitly
4195 // specialize a class member template if its en- closing class templates
4196 // are not explicitly specialized as well.
4197 if (ParamIdx < ParamLists.size()) {
4198 if (ParamLists[ParamIdx]->size() == 0) {
4199 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
4200 false))
4201 return nullptr;
4202 } else
4203 SawNonEmptyTemplateParameterList = true;
4204 }
4205
4206 if (NeedEmptyTemplateHeader) {
4207 // If we're on the last of the types, and we need a 'template<>' header
4208 // here, then it's a member specialization.
4209 if (TypeIdx == NumTypes - 1)
4210 IsMemberSpecialization = true;
4211
4212 if (ParamIdx < ParamLists.size()) {
4213 if (ParamLists[ParamIdx]->size() > 0) {
4214 // The header has template parameters when it shouldn't. Complain.
4215 if (!SuppressDiagnostic)
4216 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
4217 diag::err_template_param_list_matches_nontemplate)
4218 << T
4219 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
4220 ParamLists[ParamIdx]->getRAngleLoc())
4222 Invalid = true;
4223 return nullptr;
4224 }
4225
4226 // Consume this template header.
4227 ++ParamIdx;
4228 continue;
4229 }
4230
4231 if (!IsFriend)
4232 if (DiagnoseMissingExplicitSpecialization(
4234 return nullptr;
4235
4236 continue;
4237 }
4238
4239 if (NeedNonemptyTemplateHeader) {
4240 // In friend declarations we can have template-ids which don't
4241 // depend on the corresponding template parameter lists. But
4242 // assume that empty parameter lists are supposed to match this
4243 // template-id.
4244 if (IsFriend && T->isDependentType()) {
4245 if (ParamIdx < ParamLists.size() &&
4247 ExpectedTemplateParams = nullptr;
4248 else
4249 continue;
4250 }
4251
4252 if (ParamIdx < ParamLists.size()) {
4253 // Check the template parameter list, if we can.
4254 if (ExpectedTemplateParams &&
4256 ExpectedTemplateParams,
4257 !SuppressDiagnostic, TPL_TemplateMatch))
4258 Invalid = true;
4259
4260 if (!Invalid &&
4261 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
4263 Invalid = true;
4264
4265 ++ParamIdx;
4266 continue;
4267 }
4268
4269 if (!SuppressDiagnostic)
4270 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
4271 << T
4273 Invalid = true;
4274 continue;
4275 }
4276 }
4277
4278 // If there were at least as many template-ids as there were template
4279 // parameter lists, then there are no template parameter lists remaining for
4280 // the declaration itself.
4281 if (ParamIdx >= ParamLists.size()) {
4282 if (TemplateId && !IsFriend) {
4283 // We don't have a template header for the declaration itself, but we
4284 // should.
4285 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
4286 TemplateId->RAngleLoc));
4287
4288 // Fabricate an empty template parameter list for the invented header.
4290 SourceLocation(), std::nullopt,
4291 SourceLocation(), nullptr);
4292 }
4293
4294 return nullptr;
4295 }
4296
4297 // If there were too many template parameter lists, complain about that now.
4298 if (ParamIdx < ParamLists.size() - 1) {
4299 bool HasAnyExplicitSpecHeader = false;
4300 bool AllExplicitSpecHeaders = true;
4301 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
4302 if (ParamLists[I]->size() == 0)
4303 HasAnyExplicitSpecHeader = true;
4304 else
4305 AllExplicitSpecHeaders = false;
4306 }
4307
4308 if (!SuppressDiagnostic)
4309 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
4310 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
4311 : diag::err_template_spec_extra_headers)
4312 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
4313 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
4314
4315 // If there was a specialization somewhere, such that 'template<>' is
4316 // not required, and there were any 'template<>' headers, note where the
4317 // specialization occurred.
4318 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
4319 !SuppressDiagnostic)
4320 Diag(ExplicitSpecLoc,
4321 diag::note_explicit_template_spec_does_not_need_header)
4322 << NestedTypes.back();
4323
4324 // We have a template parameter list with no corresponding scope, which
4325 // means that the resulting template declaration can't be instantiated
4326 // properly (we'll end up with dependent nodes when we shouldn't).
4327 if (!AllExplicitSpecHeaders)
4328 Invalid = true;
4329 }
4330
4331 // C++ [temp.expl.spec]p16:
4332 // In an explicit specialization declaration for a member of a class
4333 // template or a member template that ap- pears in namespace scope, the
4334 // member template and some of its enclosing class templates may remain
4335 // unspecialized, except that the declaration shall not explicitly
4336 // specialize a class member template if its en- closing class templates
4337 // are not explicitly specialized as well.
4338 if (ParamLists.back()->size() == 0 &&
4339 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
4340 false))
4341 return nullptr;
4342
4343 // Return the last template parameter list, which corresponds to the
4344 // entity being declared.
4345 return ParamLists.back();
4346}
4347
4349 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4350 Diag(Template->getLocation(), diag::note_template_declared_here)
4351 << (isa<FunctionTemplateDecl>(Template)
4352 ? 0
4353 : isa<ClassTemplateDecl>(Template)
4354 ? 1
4355 : isa<VarTemplateDecl>(Template)
4356 ? 2
4357 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
4358 << Template->getDeclName();
4359 return;
4360 }
4361
4362 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
4363 for (OverloadedTemplateStorage::iterator I = OST->begin(),
4364 IEnd = OST->end();
4365 I != IEnd; ++I)
4366 Diag((*I)->getLocation(), diag::note_template_declared_here)
4367 << 0 << (*I)->getDeclName();
4368
4369 return;
4370 }
4371}
4372
4373static QualType
4376 SourceLocation TemplateLoc,
4377 TemplateArgumentListInfo &TemplateArgs) {
4378 ASTContext &Context = SemaRef.getASTContext();
4379
4380 switch (BTD->getBuiltinTemplateKind()) {
4381 case BTK__make_integer_seq: {
4382 // Specializations of __make_integer_seq<S, T, N> are treated like
4383 // S<T, 0, ..., N-1>.
4384
4385 QualType OrigType = Converted[1].getAsType();
4386 // C++14 [inteseq.intseq]p1:
4387 // T shall be an integer type.
4388 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
4389 SemaRef.Diag(TemplateArgs[1].getLocation(),
4390 diag::err_integer_sequence_integral_element_type);
4391 return QualType();
4392 }
4393
4394 TemplateArgument NumArgsArg = Converted[2];
4395 if (NumArgsArg.isDependent())
4397 Converted);
4398
4399 TemplateArgumentListInfo SyntheticTemplateArgs;
4400 // The type argument, wrapped in substitution sugar, gets reused as the
4401 // first template argument in the synthetic template argument list.
4402 SyntheticTemplateArgs.addArgument(
4405 OrigType, TemplateArgs[1].getLocation())));
4406
4407 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
4408 // Expand N into 0 ... N-1.
4409 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
4410 I < NumArgs; ++I) {
4411 TemplateArgument TA(Context, I, OrigType);
4412 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
4413 TA, OrigType, TemplateArgs[2].getLocation()));
4414 }
4415 } else {
4416 // C++14 [inteseq.make]p1:
4417 // If N is negative the program is ill-formed.
4418 SemaRef.Diag(TemplateArgs[2].getLocation(),
4419 diag::err_integer_sequence_negative_length);
4420 return QualType();
4421 }
4422
4423 // The first template argument will be reused as the template decl that
4424 // our synthetic template arguments will be applied to.
4425 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
4426 TemplateLoc, SyntheticTemplateArgs);
4427 }
4428
4430 // Specializations of
4431 // __type_pack_element<Index, T_1, ..., T_N>
4432 // are treated like T_Index.
4433 assert(Converted.size() == 2 &&
4434 "__type_pack_element should be given an index and a parameter pack");
4435
4436 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
4437 if (IndexArg.isDependent() || Ts.isDependent())
4439 Converted);
4440
4441 llvm::APSInt Index = IndexArg.getAsIntegral();
4442 assert(Index >= 0 && "the index used with __type_pack_element should be of "
4443 "type std::size_t, and hence be non-negative");
4444 // If the Index is out of bounds, the program is ill-formed.
4445 if (Index >= Ts.pack_size()) {
4446 SemaRef.Diag(TemplateArgs[0].getLocation(),
4447 diag::err_type_pack_element_out_of_bounds);
4448 return QualType();
4449 }
4450
4451 // We simply return the type at index `Index`.
4452 int64_t N = Index.getExtValue();
4453 return Ts.getPackAsArray()[N].getAsType();
4454 }
4455 llvm_unreachable("unexpected BuiltinTemplateDecl!");
4456}
4457
4458/// Determine whether this alias template is "enable_if_t".
4459/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
4461 return AliasTemplate->getName() == "enable_if_t" ||
4462 AliasTemplate->getName() == "__enable_if_t";
4463}
4464
4465/// Collect all of the separable terms in the given condition, which
4466/// might be a conjunction.
4467///
4468/// FIXME: The right answer is to convert the logical expression into
4469/// disjunctive normal form, so we can find the first failed term
4470/// within each possible clause.
4471static void collectConjunctionTerms(Expr *Clause,
4472 SmallVectorImpl<Expr *> &Terms) {
4473 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
4474 if (BinOp->getOpcode() == BO_LAnd) {
4475 collectConjunctionTerms(BinOp->getLHS(), Terms);
4476 collectConjunctionTerms(BinOp->getRHS(), Terms);
4477 return;
4478 }
4479 }
4480
4481 Terms.push_back(Clause);
4482}
4483
4484// The ranges-v3 library uses an odd pattern of a top-level "||" with
4485// a left-hand side that is value-dependent but never true. Identify
4486// the idiom and ignore that term.
4488 // Top-level '||'.
4489 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
4490 if (!BinOp) return Cond;
4491
4492 if (BinOp->getOpcode() != BO_LOr) return Cond;
4493
4494 // With an inner '==' that has a literal on the right-hand side.
4495 Expr *LHS = BinOp->getLHS();
4496 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
4497 if (!InnerBinOp) return Cond;
4498
4499 if (InnerBinOp->getOpcode() != BO_EQ ||
4500 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
4501 return Cond;
4502
4503 // If the inner binary operation came from a macro expansion named
4504 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
4505 // of the '||', which is the real, user-provided condition.
4506 SourceLocation Loc = InnerBinOp->getExprLoc();
4507 if (!Loc.isMacroID()) return Cond;
4508
4509 StringRef MacroName = PP.getImmediateMacroName(Loc);
4510 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
4511 return BinOp->getRHS();
4512
4513 return Cond;
4514}
4515
4516namespace {
4517
4518// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
4519// within failing boolean expression, such as substituting template parameters
4520// for actual types.
4521class FailedBooleanConditionPrinterHelper : public PrinterHelper {
4522public:
4523 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
4524 : Policy(P) {}
4525
4526 bool handledStmt(Stmt *E, raw_ostream &OS) override {
4527 const auto *DR = dyn_cast<DeclRefExpr>(E);
4528 if (DR && DR->getQualifier()) {
4529 // If this is a qualified name, expand the template arguments in nested
4530 // qualifiers.
4531 DR->getQualifier()->print(OS, Policy, true);
4532 // Then print the decl itself.
4533 const ValueDecl *VD = DR->getDecl();
4534 OS << VD->getName();
4535 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
4536 // This is a template variable, print the expanded template arguments.
4538 OS, IV->getTemplateArgs().asArray(), Policy,
4539 IV->getSpecializedTemplate()->getTemplateParameters());
4540 }
4541 return true;
4542 }
4543 return false;
4544 }
4545
4546private:
4547 const PrintingPolicy Policy;
4548};
4549
4550} // end anonymous namespace
4551
4552std::pair<Expr *, std::string>
4554 Cond = lookThroughRangesV3Condition(PP, Cond);
4555
4556 // Separate out all of the terms in a conjunction.
4558 collectConjunctionTerms(Cond, Terms);
4559
4560 // Determine which term failed.
4561 Expr *FailedCond = nullptr;
4562 for (Expr *Term : Terms) {
4563 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
4564
4565 // Literals are uninteresting.
4566 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
4567 isa<IntegerLiteral>(TermAsWritten))
4568 continue;
4569
4570 // The initialization of the parameter from the argument is
4571 // a constant-evaluated context.
4574
4575 bool Succeeded;
4576 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
4577 !Succeeded) {
4578 FailedCond = TermAsWritten;
4579 break;
4580 }
4581 }
4582 if (!FailedCond)
4583 FailedCond = Cond->IgnoreParenImpCasts();
4584
4585 std::string Description;
4586 {
4587 llvm::raw_string_ostream Out(Description);
4589 Policy.PrintCanonicalTypes = true;
4590 FailedBooleanConditionPrinterHelper Helper(Policy);
4591 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
4592 }
4593 return { FailedCond, Description };
4594}
4595
4597 SourceLocation TemplateLoc,
4598 TemplateArgumentListInfo &TemplateArgs) {
4600 = Name.getUnderlying().getAsDependentTemplateName();
4601 if (DTN && DTN->isIdentifier())
4602 // When building a template-id where the template-name is dependent,
4603 // assume the template is a type template. Either our assumption is
4604 // correct, or the code is ill-formed and will be diagnosed when the
4605 // dependent name is substituted.
4608 TemplateArgs.arguments());
4609
4610 if (Name.getAsAssumedTemplateName() &&
4611 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
4612 return QualType();
4613
4614 TemplateDecl *Template = Name.getAsTemplateDecl();
4615 if (!Template || isa<FunctionTemplateDecl>(Template) ||
4616 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
4617 // We might have a substituted template template parameter pack. If so,
4618 // build a template specialization type for it.
4619 if (Name.getAsSubstTemplateTemplateParmPack())
4621 TemplateArgs.arguments());
4622
4623 Diag(TemplateLoc, diag::err_template_id_not_a_type)
4624 << Name;
4626 return QualType();
4627 }
4628
4629 // Check that the template argument list is well-formed for this
4630 // template.
4631 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4632 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
4633 SugaredConverted, CanonicalConverted,
4634 /*UpdateArgsWithConversions=*/true))
4635 return QualType();
4636
4637 QualType CanonType;
4638
4640 dyn_cast<TypeAliasTemplateDecl>(Template)) {
4641
4642 // Find the canonical type for this type alias template specialization.
4643 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
4644 if (Pattern->isInvalidDecl())
4645 return QualType();
4646
4647 // Only substitute for the innermost template argument list.
4648 MultiLevelTemplateArgumentList TemplateArgLists;
4649 TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
4650 /*Final=*/false);
4651 TemplateArgLists.addOuterRetainedLevels(
4652 AliasTemplate->getTemplateParameters()->getDepth());
4653
4656 *this, /*PointOfInstantiation=*/TemplateLoc,
4657 /*Entity=*/AliasTemplate,
4658 /*TemplateArgs=*/TemplateArgLists.getInnermost());
4659 if (Inst.isInvalid())
4660 return QualType();
4661
4662 std::optional<ContextRAII> SavedContext;
4663 if (!AliasTemplate->getDeclContext()->isFileContext())
4664 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
4665
4666 CanonType =
4667 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
4668 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
4669 if (CanonType.isNull()) {
4670 // If this was enable_if and we failed to find the nested type
4671 // within enable_if in a SFINAE context, dig out the specific
4672 // enable_if condition that failed and present that instead.
4674 if (auto DeductionInfo = isSFINAEContext()) {
4675 if (*DeductionInfo &&
4676 (*DeductionInfo)->hasSFINAEDiagnostic() &&
4677 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
4678 diag::err_typename_nested_not_found_enable_if &&
4679 TemplateArgs[0].getArgument().getKind()
4681 Expr *FailedCond;
4682 std::string FailedDescription;
4683 std::tie(FailedCond, FailedDescription) =
4684 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
4685
4686 // Remove the old SFINAE diagnostic.
4687 PartialDiagnosticAt OldDiag =
4689 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
4690
4691 // Add a new SFINAE diagnostic specifying which condition
4692 // failed.
4693 (*DeductionInfo)->addSFINAEDiagnostic(
4694 OldDiag.first,
4695 PDiag(diag::err_typename_nested_not_found_requirement)
4696 << FailedDescription
4697 << FailedCond->getSourceRange());
4698 }
4699 }
4700 }
4701
4702 return QualType();
4703 }
4704 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
4705 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
4706 TemplateLoc, TemplateArgs);
4707 } else if (Name.isDependent() ||
4709 TemplateArgs, CanonicalConverted)) {
4710 // This class template specialization is a dependent
4711 // type. Therefore, its canonical type is another class template
4712 // specialization type that contains all of the converted
4713 // arguments in canonical form. This ensures that, e.g., A<T> and
4714 // A<T, T> have identical types when A is declared as:
4715 //
4716 // template<typename T, typename U = T> struct A;
4718 Name, CanonicalConverted);
4719
4720 // This might work out to be a current instantiation, in which
4721 // case the canonical type needs to be the InjectedClassNameType.
4722 //
4723 // TODO: in theory this could be a simple hashtable lookup; most
4724 // changes to CurContext don't change the set of current
4725 // instantiations.
4726 if (isa<ClassTemplateDecl>(Template)) {
4727 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
4728 // If we get out to a namespace, we're done.
4729 if (Ctx->isFileContext()) break;
4730
4731 // If this isn't a record, keep looking.
4732 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
4733 if (!Record) continue;
4734
4735 // Look for one of the two cases with InjectedClassNameTypes
4736 // and check whether it's the same template.
4737 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
4738 !Record->getDescribedClassTemplate())
4739 continue;
4740
4741 // Fetch the injected class name type and check whether its
4742 // injected type is equal to the type we just built.
4744 QualType Injected = cast<InjectedClassNameType>(ICNT)
4745 ->getInjectedSpecializationType();
4746
4747 if (CanonType != Injected->getCanonicalTypeInternal())
4748 continue;
4749
4750 // If so, the canonical type of this TST is the injected
4751 // class name type of the record we just found.
4752 assert(ICNT.isCanonical());
4753 CanonType = ICNT;
4754 break;
4755 }
4756 }
4757 } else if (ClassTemplateDecl *ClassTemplate =
4758 dyn_cast<ClassTemplateDecl>(Template)) {
4759 // Find the class template specialization declaration that
4760 // corresponds to these arguments.
4761 void *InsertPos = nullptr;
4763 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
4764 if (!Decl) {
4765 // This is the first time we have referenced this class template
4766 // specialization. Create the canonical declaration and add it to
4767 // the set of specializations.
4769 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4770 ClassTemplate->getDeclContext(),
4771 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4772 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
4773 nullptr);
4774 ClassTemplate->AddSpecialization(Decl, InsertPos);
4775 if (ClassTemplate->isOutOfLine())
4776 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4777 }
4778
4779 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4780 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4781 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4782 if (!Inst.isInvalid()) {
4783 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4784 CanonicalConverted,
4785 /*Final=*/false);
4786 InstantiateAttrsForDecl(TemplateArgLists,
4787 ClassTemplate->getTemplatedDecl(), Decl);
4788 }
4789 }
4790
4791 // Diagnose uses of this specialization.
4792 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4793
4794 CanonType = Context.getTypeDeclType(Decl);
4795 assert(isa<RecordType>(CanonType) &&
4796 "type of non-dependent specialization is not a RecordType");
4797 } else {
4798 llvm_unreachable("Unhandled template kind");
4799 }
4800
4801 // Build the fully-sugared type for this class template
4802 // specialization, which refers back to the class template
4803 // specialization we created or found.
4804 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
4805 CanonType);
4806}
4807
4809 TemplateNameKind &TNK,
4810 SourceLocation NameLoc,
4811 IdentifierInfo *&II) {
4812 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4813
4814 TemplateName Name = ParsedName.get();
4815 auto *ATN = Name.getAsAssumedTemplateName();
4816 assert(ATN && "not an assumed template name");
4817 II = ATN->getDeclName().getAsIdentifierInfo();
4818
4819 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4820 // Resolved to a type template name.
4821 ParsedName = TemplateTy::make(Name);
4822 TNK = TNK_Type_template;
4823 }
4824}
4825
4827 SourceLocation NameLoc,
4828 bool Diagnose) {
4829 // We assumed this undeclared identifier to be an (ADL-only) function
4830 // template name, but it was used in a context where a type was required.
4831 // Try to typo-correct it now.
4832 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4833 assert(ATN && "not an assumed template name");
4834
4835 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4836 struct CandidateCallback : CorrectionCandidateCallback {
4837 bool ValidateCandidate(const TypoCorrection &TC) override {
4838 return TC.getCorrectionDecl() &&
4840 }
4841 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4842 return std::make_unique<CandidateCallback>(*this);
4843 }
4844 } FilterCCC;
4845
4846 TypoCorrection Corrected =
4847 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
4848 FilterCCC, CTK_ErrorRecovery);
4849 if (Corrected && Corrected.getFoundDecl()) {
4850 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4851 << ATN->getDeclName());
4852 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4853 return false;
4854 }
4855
4856 if (Diagnose)
4857 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4858 return true;
4859}
4860
4862 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4863 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
4864 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4865 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4866 bool IsCtorOrDtorName, bool IsClassName,
4867 ImplicitTypenameContext AllowImplicitTypename) {
4868 if (SS.isInvalid())
4869 return true;
4870
4871 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4872 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4873
4874 // C++ [temp.res]p3:
4875 // A qualified-id that refers to a type and in which the
4876 // nested-name-specifier depends on a template-parameter (14.6.2)
4877 // shall be prefixed by the keyword typename to indicate that the
4878 // qualified-id denotes a type, forming an
4879 // elaborated-type-specifier (7.1.5.3).
4880 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4881 // C++2a relaxes some of those restrictions in [temp.res]p5.
4882 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4884 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4885 else
4886 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4887 << SS.getScopeRep() << TemplateII->getName()
4888 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4889 } else
4890 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4891 << SS.getScopeRep() << TemplateII->getName();
4892
4893 // FIXME: This is not quite correct recovery as we don't transform SS
4894 // into the corresponding dependent form (and we don't diagnose missing
4895 // 'template' keywords within SS as a result).
4896 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4897 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4898 TemplateArgsIn, RAngleLoc);
4899 }
4900
4901 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4902 // it's not actually allowed to be used as a type in most cases. Because
4903 // we annotate it before we know whether it's valid, we have to check for
4904 // this case here.
4905 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4906 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4907 Diag(TemplateIILoc,
4908 TemplateKWLoc.isInvalid()
4909 ? diag::err_out_of_line_qualified_id_type_names_constructor
4910 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4911 << TemplateII << 0 /*injected-class-name used as template name*/
4912 << 1 /*if any keyword was present, it was 'template'*/;
4913 }
4914 }
4915
4916 TemplateName Template = TemplateD.get();
4917 if (Template.getAsAssumedTemplateName() &&
4918 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4919 return true;
4920
4921 // Translate the parser's template argument list in our AST format.
4922 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4923 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4924
4925 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4926 assert(SS.getScopeRep() == DTN->getQualifier());
4928 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
4929 TemplateArgs.arguments());
4930 // Build type-source information.
4931 TypeLocBuilder TLB;
4936 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4937 SpecTL.setTemplateNameLoc(TemplateIILoc);
4938 SpecTL.setLAngleLoc(LAngleLoc);
4939 SpecTL.setRAngleLoc(RAngleLoc);
4940 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4941 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4943 }
4944
4945 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4946 if (SpecTy.isNull())
4947 return true;
4948
4949 // Build type-source information.
4950 TypeLocBuilder TLB;
4953 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4954 SpecTL.setTemplateNameLoc(TemplateIILoc);
4955 SpecTL.setLAngleLoc(LAngleLoc);
4956 SpecTL.setRAngleLoc(RAngleLoc);
4957 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4958 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4959
4960 // Create an elaborated-type-specifier containing the nested-name-specifier.
4961 QualType ElTy =
4963 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4964 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4966 if (!ElabTL.isEmpty())
4968 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4969}
4970
4972 TypeSpecifierType TagSpec,
4973 SourceLocation TagLoc,
4974 CXXScopeSpec &SS,
4975 SourceLocation TemplateKWLoc,
4976 TemplateTy TemplateD,
4977 SourceLocation TemplateLoc,
4978 SourceLocation LAngleLoc,
4979 ASTTemplateArgsPtr TemplateArgsIn,
4980 SourceLocation RAngleLoc) {
4981 if (SS.isInvalid())
4982 return TypeResult(true);
4983
4984 TemplateName Template = TemplateD.get();
4985
4986 // Translate the parser's template argument list in our AST format.
4987 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4988 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4989
4990 // Determine the tag kind
4992 ElaboratedTypeKeyword Keyword
4994
4995 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4996 assert(SS.getScopeRep() == DTN->getQualifier());
4998 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
4999 TemplateArgs.arguments());
5000
5001 // Build type-source information.
5002 TypeLocBuilder TLB;
5005 SpecTL.setElaboratedKeywordLoc(TagLoc);
5007 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
5008 SpecTL.setTemplateNameLoc(TemplateLoc);
5009 SpecTL.setLAngleLoc(LAngleLoc);
5010 SpecTL.setRAngleLoc(RAngleLoc);
5011 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
5012 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
5014 }
5015
5016 if (TypeAliasTemplateDecl *TAT =
5017 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
5018 // C++0x [dcl.type.elab]p2:
5019 // If the identifier resolves to a typedef-name or the simple-template-id
5020 // resolves to an alias template specialization, the
5021 // elaborated-type-specifier is ill-formed.
5022 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
5023 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
5024 Diag(TAT->getLocation(), diag::note_declared_at);
5025 }
5026
5027 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
5028 if (Result.isNull())
5029 return TypeResult(true);
5030
5031 // Check the tag kind
5032 if (const RecordType *RT = Result->getAs<RecordType>()) {
5033 RecordDecl *D = RT->getDecl();
5034
5036 assert(Id && "templated class must have an identifier");
5037
5038 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
5039 TagLoc, Id)) {
5040 Diag(TagLoc, diag::err_use_with_wrong_tag)
5041 << Result
5043 Diag(D->getLocation(), diag::note_previous_use);
5044 }
5045 }
5046
5047 // Provide source-location information for the template specialization.
5048 TypeLocBuilder TLB;
5051 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
5052 SpecTL.setTemplateNameLoc(TemplateLoc);
5053 SpecTL.setLAngleLoc(LAngleLoc);
5054 SpecTL.setRAngleLoc(RAngleLoc);
5055 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
5056 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
5057
5058 // Construct an elaborated type containing the nested-name-specifier (if any)
5059 // and tag keyword.
5062 ElabTL.setElaboratedKeywordLoc(TagLoc);
5065}
5066
5067static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
5068 NamedDecl *PrevDecl,
5071
5073
5075 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
5076 switch (Arg.getKind()) {
5084 return false;
5085
5087 QualType Type = Arg.getAsType();
5088 const TemplateTypeParmType *TPT =
5090 return TPT && !Type.hasQualifiers() &&
5091 TPT->getDepth() == Depth && TPT->getIndex() == Index;
5092 }
5093
5095 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
5096 if (!DRE || !DRE->getDecl())
5097 return false;
5098 const NonTypeTemplateParmDecl *NTTP =
5099 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5100 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
5101 }
5102
5104 const TemplateTemplateParmDecl *TTP =
5105 dyn_cast_or_null<TemplateTemplateParmDecl>(
5107 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
5108 }
5109 llvm_unreachable("unexpected kind of template argument");
5110}
5111
5114 if (Params->size() != Args.size())
5115 return false;
5116
5117 unsigned Depth = Params->getDepth();
5118
5119 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5120 TemplateArgument Arg = Args[I];
5121
5122 // If the parameter is a pack expansion, the argument must be a pack
5123 // whose only element is a pack expansion.
5124 if (Params->getParam(I)->isParameterPack()) {
5125 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
5126 !Arg.pack_begin()->isPackExpansion())
5127 return false;
5128 Arg = Arg.pack_begin()->getPackExpansionPattern();
5129 }
5130
5131 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
5132 return false;
5133 }
5134
5135 return true;
5136}
5137
5138template<typename PartialSpecDecl>
5139static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
5140 if (Partial->getDeclContext()->isDependentContext())
5141 return;
5142
5143 // FIXME: Get the TDK from deduction in order to provide better diagnostics
5144 // for non-substitution-failure issues?
5145 TemplateDeductionInfo Info(Partial->getLocation());
5146 if (S.isMoreSpecializedThanPrimary(Partial, Info))
5147 return;
5148
5149 auto *Template = Partial->getSpecializedTemplate();
5150 S.Diag(Partial->getLocation(),
5151 diag::ext_partial_spec_not_more_specialized_than_primary)
5152 << isa<VarTemplateDecl>(Template);
5153
5154 if (Info.hasSFINAEDiagnostic()) {
5158 SmallString<128> SFINAEArgString;
5159 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
5160 S.Diag(Diag.first,
5161 diag::note_partial_spec_not_more_specialized_than_primary)
5162 << SFINAEArgString;
5163 }
5164
5165 S.NoteTemplateLocation(*Template);
5166 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
5167 Template->getAssociatedConstraints(TemplateAC);
5168 Partial->getAssociatedConstraints(PartialAC);
5169 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
5170 TemplateAC);
5171}
5172
5173static void
5175 const llvm::SmallBitVector &DeducibleParams) {
5176 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5177 if (!DeducibleParams[I]) {
5178 NamedDecl *Param = TemplateParams->getParam(I);
5179 if (Param->getDeclName())
5180 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
5181 << Param->getDeclName();
5182 else
5183 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
5184 << "(anonymous)";
5185 }
5186 }
5187}
5188
5189
5190template<typename PartialSpecDecl>
5192 PartialSpecDecl *Partial) {
5193 // C++1z [temp.class.spec]p8: (DR1495)
5194 // - The specialization shall be more specialized than the primary
5195 // template (14.5.5.2).
5197
5198 // C++ [temp.class.spec]p8: (DR1315)
5199 // - Each template-parameter shall appear at least once in the
5200 // template-id outside a non-deduced context.
5201 // C++1z [temp.class.spec.match]p3 (P0127R2)
5202 // If the template arguments of a partial specialization cannot be
5203 // deduced because of the structure of its template-parameter-list
5204 // and the template-id, the program is ill-formed.
5205 auto *TemplateParams = Partial->getTemplateParameters();
5206 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
5207 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
5208 TemplateParams->getDepth(), DeducibleParams);
5209
5210 if (!DeducibleParams.all()) {
5211 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
5212 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
5213 << isa<VarTemplatePartialSpecializationDecl>(Partial)
5214 << (NumNonDeducible > 1)
5215 << SourceRange(Partial->getLocation(),
5216 Partial->getTemplateArgsAsWritten()->RAngleLoc);
5217 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
5218 }
5219}
5220
5223 checkTemplatePartialSpecialization(*this, Partial);
5224}
5225
5228 checkTemplatePartialSpecialization(*this, Partial);
5229}
5230
5232 // C++1z [temp.param]p11:
5233 // A template parameter of a deduction guide template that does not have a
5234 // default-argument shall be deducible from the parameter-type-list of the
5235 // deduction guide template.
5236 auto *TemplateParams = TD->getTemplateParameters();
5237 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
5238 MarkDeducedTemplateParameters(TD, DeducibleParams);
5239 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
5240 // A parameter pack is deducible (to an empty pack).
5241 auto *Param = TemplateParams->getParam(I);
5242 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
5243 DeducibleParams[I] = true;
5244 }
5245
5246 if (!DeducibleParams.all()) {
5247 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
5248 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
5249 << (NumNonDeducible > 1);
5250 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
5251 }
5252}
5253
5256 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5258 // D must be variable template id.
5260 "Variable template specialization is declared with a template id.");
5261
5262 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5263 TemplateArgumentListInfo TemplateArgs =
5264 makeTemplateArgumentListInfo(*this, *TemplateId);
5265 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
5266 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
5267 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
5268
5269 TemplateName Name = TemplateId->Template.get();
5270
5271 // The template-id must name a variable template.
5273 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
5274 if (!VarTemplate) {
5275 NamedDecl *FnTemplate;
5276 if (auto *OTS = Name.getAsOverloadedTemplate())
5277 FnTemplate = *OTS->begin();
5278 else
5279 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
5280 if (FnTemplate)
5281 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
5282 << FnTemplate->getDeclName();
5283 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5285 }
5286
5287 // Check for unexpanded parameter packs in any of the template arguments.
5288 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5289 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
5293 return true;
5294
5295 // Check that the template argument list is well-formed for this
5296 // template.
5297 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5298 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
5299 false, SugaredConverted, CanonicalConverted,
5300 /*UpdateArgsWithConversions=*/true))
5301 return true;
5302
5303 // Find the variable template (partial) specialization declaration that
5304 // corresponds to these arguments.
5307 TemplateArgs.size(),
5308 CanonicalConverted))
5309 return true;
5310
5311 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
5312 // also do them during instantiation.
5313 if (!Name.isDependent() &&
5315 TemplateArgs, CanonicalConverted)) {
5316 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5317 << VarTemplate->getDeclName();
5319 }
5320
5321 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
5322 CanonicalConverted) &&
5323 (!Context.getLangOpts().CPlusPlus20 ||
5324 !TemplateParams->hasAssociatedConstraints())) {
5325 // C++ [temp.class.spec]p9b3:
5326 //
5327 // -- The argument list of the specialization shall not be identical
5328 // to the implicit argument list of the primary template.
5329 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
5330 << /*variable template*/ 1
5331 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
5332 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
5333 // FIXME: Recover from this by treating the declaration as a redeclaration
5334 // of the primary template.
5335 return true;
5336 }
5337 }
5338
5339 void *InsertPos = nullptr;
5340 VarTemplateSpecializationDecl *PrevDecl = nullptr;
5341
5343 PrevDecl = VarTemplate->findPartialSpecialization(
5344 CanonicalConverted, TemplateParams, InsertPos);
5345 else
5346 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
5347
5349
5350 // Check whether we can declare a variable template specialization in
5351 // the current scope.
5352 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
5353 TemplateNameLoc,
5355 return true;
5356
5357 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
5358 // Since the only prior variable template specialization with these
5359 // arguments was referenced but not declared, reuse that
5360 // declaration node as our own, updating its source location and
5361 // the list of outer template parameters to reflect our new declaration.
5362 Specialization = PrevDecl;
5363 Specialization->setLocation(TemplateNameLoc);
5364 PrevDecl = nullptr;
5365 } else if (IsPartialSpecialization) {
5366 // Create a new class template partial specialization declaration node.
5368 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
5371 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
5372 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
5373 CanonicalConverted);
5374 Partial->setTemplateArgsAsWritten(TemplateArgs);
5375
5376 if (!PrevPartial)
5377 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
5378 Specialization = Partial;
5379
5380 // If we are providing an explicit specialization of a member variable
5381 // template specialization, make a note of that.
5382 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5383 PrevPartial->setMemberSpecialization();
5384
5386 } else {
5387 // Create a new class template specialization declaration node for
5388 // this explicit specialization or friend declaration.
5390 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
5391 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
5392 Specialization->setTemplateArgsAsWritten(TemplateArgs);
5393
5394 if (!PrevDecl)
5395 VarTemplate->AddSpecialization(Specialization, InsertPos);
5396 }
5397
5398 // C++ [temp.expl.spec]p6:
5399 // If a template, a member template or the member of a class template is
5400 // explicitly specialized then that specialization shall be declared
5401 // before the first use of that specialization that would cause an implicit
5402 // instantiation to take place, in every translation unit in which such a
5403 // use occurs; no diagnostic is required.
5404 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
5405 bool Okay = false;
5406 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5407 // Is there any previous explicit specialization declaration?
5409 Okay = true;
5410 break;
5411 }
5412 }
5413
5414 if (!Okay) {
5415 SourceRange Range(TemplateNameLoc, RAngleLoc);
5416 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5417 << Name << Range;
5418
5419 Diag(PrevDecl->getPointOfInstantiation(),
5420 diag::note_instantiation_required_here)
5421 << (PrevDecl->getTemplateSpecializationKind() !=
5423 return true;
5424 }
5425 }
5426
5427 Specialization->setLexicalDeclContext(CurContext);
5428
5429 // Add the specialization into its lexical context, so that it can
5430 // be seen when iterating through the list of declarations in that
5431 // context. However, specializations are not found by name lookup.
5433
5434 // Note that this is an explicit specialization.
5435 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
5436
5437 Previous.clear();
5438 if (PrevDecl)
5439 Previous.addDecl(PrevDecl);
5440 else if (Specialization->isStaticDataMember() &&
5441 Specialization->isOutOfLine())
5442 Specialization->setAccess(VarTemplate->getAccess());
5443
5444 return Specialization;
5445}
5446
5447namespace {
5448/// A partial specialization whose template arguments have matched
5449/// a given template-id.
5450struct PartialSpecMatchResult {
5453};
5454} // end anonymous namespace
5455
5458 SourceLocation TemplateNameLoc,
5459 const TemplateArgumentListInfo &TemplateArgs) {
5460 assert(Template && "A variable template id without template?");
5461
5462 // Check that the template argument list is well-formed for this template.
5463 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5465 Template, TemplateNameLoc,
5466 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
5467 SugaredConverted, CanonicalConverted,
5468 /*UpdateArgsWithConversions=*/true))
5469 return true;
5470
5471 // Produce a placeholder value if the specialization is dependent.
5472 if (Template->getDeclContext()->isDependentContext() ||
5474 TemplateArgs, CanonicalConverted))
5475 return DeclResult();
5476
5477 // Find the variable template specialization declaration that
5478 // corresponds to these arguments.
5479 void *InsertPos = nullptr;
5481 Template->findSpecialization(CanonicalConverted, InsertPos)) {
5482 checkSpecializationReachability(TemplateNameLoc, Spec);
5483 // If we already have a variable template specialization, return it.
5484 return Spec;
5485 }
5486
5487 // This is the first time we have referenced this variable template
5488 // specialization. Create the canonical declaration and add it to
5489 // the set of specializations, based on the closest partial specialization
5490 // that it represents. That is,
5491 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
5492 const TemplateArgumentList *PartialSpecArgs = nullptr;
5493 bool AmbiguousPartialSpec = false;
5494 typedef PartialSpecMatchResult MatchResult;
5496 SourceLocation PointOfInstantiation = TemplateNameLoc;
5497 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
5498 /*ForTakingAddress=*/false);
5499
5500 // 1. Attempt to find the closest partial specialization that this
5501 // specializes, if any.
5502 // TODO: Unify with InstantiateClassTemplateSpecialization()?
5503 // Perhaps better after unification of DeduceTemplateArguments() and
5504 // getMoreSpecializedPartialSpecialization().
5506 Template->getPartialSpecializations(PartialSpecs);
5507
5508 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
5509 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
5510 TemplateDeductionInfo Info(FailedCandidates.getLocation());
5511
5513 DeduceTemplateArguments(Partial, CanonicalConverted, Info);
5515 // Store the failed-deduction information for use in diagnostics, later.
5516 // TODO: Actually use the failed-deduction info?
5517 FailedCandidates.addCandidate().set(
5518 DeclAccessPair::make(Template, AS_public), Partial,
5520 (void)Result;
5521 } else {
5522 Matched.push_back(PartialSpecMatchResult());
5523 Matched.back().Partial = Partial;
5524 Matched.back().Args = Info.takeCanonical();
5525 }
5526 }
5527
5528 if (Matched.size() >= 1) {
5529 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
5530 if (Matched.size() == 1) {
5531 // -- If exactly one matching specialization is found, the
5532 // instantiation is generated from that specialization.
5533 // We don't need to do anything for this.
5534 } else {
5535 // -- If more than one matching specialization is found, the
5536 // partial order rules (14.5.4.2) are used to determine
5537 // whether one of the specializations is more specialized
5538 // than the others. If none of the specializations is more
5539 // specialized than all of the other matching
5540 // specializations, then the use of the variable template is
5541 // ambiguous and the program is ill-formed.
5543 PEnd = Matched.end();
5544 P != PEnd; ++P) {
5545 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
5546 PointOfInstantiation) ==
5547 P->Partial)
5548 Best = P;
5549 }
5550
5551 // Determine if the best partial specialization is more specialized than
5552 // the others.
5553 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
5554 PEnd = Matched.end();
5555 P != PEnd; ++P) {
5557 P->Partial, Best->Partial,
5558 PointOfInstantiation) != Best->Partial) {
5559 AmbiguousPartialSpec = true;
5560 break;
5561 }
5562 }
5563 }
5564
5565 // Instantiate using the best variable template partial specialization.
5566 InstantiationPattern = Best->Partial;
5567 PartialSpecArgs = Best->Args;
5568 } else {
5569 // -- If no match is found, the instantiation is generated
5570 // from the primary template.
5571 // InstantiationPattern = Template->getTemplatedDecl();
5572 }
5573
5574 // 2. Create the canonical declaration.
5575 // Note that we do not instantiate a definition until we see an odr-use
5576 // in DoMarkVarDeclReferenced().
5577 // FIXME: LateAttrs et al.?
5579 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
5580 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
5581 if (!Decl)
5582 return true;
5583
5584 if (AmbiguousPartialSpec) {
5585 // Partial ordering did not produce a clear winner. Complain.
5587 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
5588 << Decl;
5589
5590 // Print the matching partial specializations.
5591 for (MatchResult P : Matched)
5592 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
5593 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
5594 *P.Args);
5595 return true;
5596 }
5597
5599 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
5600 Decl->setInstantiationOf(D, PartialSpecArgs);
5601
5602 checkSpecializationReachability(TemplateNameLoc, Decl);
5603
5604 assert(Decl && "No variable template specialization?");
5605 return Decl;
5606}
5607
5609 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
5610 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
5611 const TemplateArgumentListInfo *TemplateArgs) {
5612
5613 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
5614 *TemplateArgs);
5615 if (Decl.isInvalid())
5616 return ExprError();
5617
5618 if (!Decl.get())
5619 return ExprResult();
5620
5621 VarDecl *Var = cast<VarDecl>(Decl.get());
5624 NameInfo.getLoc());
5625
5626 // Build an ordinary singleton decl ref.
5627 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
5628}
5629
5632 Diag(Loc, diag::err_template_missing_args)
5633 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
5634 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
5635 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
5636 }
5637}
5638
5641 SourceLocation TemplateKWLoc,
5642 const DeclarationNameInfo &ConceptNameInfo,
5643 NamedDecl *FoundDecl,
5644 ConceptDecl *NamedConcept,
5645 const TemplateArgumentListInfo *TemplateArgs) {
5646 assert(NamedConcept && "A concept template id without a template?");
5647
5648 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5650 NamedConcept, ConceptNameInfo.getLoc(),
5651 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
5652 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
5653 /*UpdateArgsWithConversions=*/false))
5654 return ExprError();
5655
5656 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
5657
5659 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
5660 CanonicalConverted);
5661 ConstraintSatisfaction Satisfaction;
5662 bool AreArgsDependent =
5664 *TemplateArgs, CanonicalConverted);
5665 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
5666 /*Final=*/false);
5668
5671
5672 if (!AreArgsDependent &&
5674 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
5675 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
5676 TemplateArgs->getRAngleLoc()),
5677 Satisfaction))
5678 return ExprError();
5679 auto *CL = ConceptReference::Create(
5680 Context,
5682 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
5685 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
5686}
5687
5689 SourceLocation TemplateKWLoc,
5690 LookupResult &R,
5691 bool RequiresADL,
5692 const TemplateArgumentListInfo *TemplateArgs) {
5693 // FIXME: Can we do any checking at this point? I guess we could check the
5694 // template arguments that we have against the template name, if the template
5695 // name refers to a single template. That's not a terribly common case,
5696 // though.
5697 // foo<int> could identify a single function unambiguously
5698 // This approach does NOT work, since f<int>(1);
5699 // gets resolved prior to resorting to overload resolution
5700 // i.e., template<class T> void f(double);
5701 // vs template<class T, class U> void f(U);
5702
5703 // These should be filtered out by our callers.
5704 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5705
5706 // Non-function templates require a template argument list.
5707 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5708 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
5710 return ExprError();
5711 }
5712 }
5713 bool KnownDependent = false;
5714 // In C++1y, check variable template ids.
5715 if (R.getAsSingle<VarTemplateDecl>()) {
5718 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
5719 if (Res.isInvalid() || Res.isUsable())
5720 return Res;
5721 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
5722 KnownDependent = true;
5723 }
5724
5725 if (R.getAsSingle<ConceptDecl>()) {
5726 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5728 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5729 }
5730
5731 // We don't want lookup warnings at this point.
5733
5736 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5737 R.begin(), R.end(), KnownDependent);
5738
5739 // Model the templates with UnresolvedTemplateTy. The expression should then
5740 // either be transformed in an instantiation or be diagnosed in
5741 // CheckPlaceholderExpr.
5742 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5745
5746 return ULE;
5747}
5748
5749// We actually only call this from template instantiation.
5752 SourceLocation TemplateKWLoc,
5753 const DeclarationNameInfo &NameInfo,
5754 const TemplateArgumentListInfo *TemplateArgs) {
5755
5756 assert(TemplateArgs || TemplateKWLoc.isValid());
5757 DeclContext *DC;
5758 if (!(DC = computeDeclContext(SS, false)) ||
5759 DC->isDependentContext() ||
5761 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5762
5763 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5764 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
5765 /*Entering*/ false, TemplateKWLoc))
5766 return ExprError();
5767
5768 if (R.isAmbiguous())
5769 return ExprError();
5770
5771 if (R.empty()) {
5772 Diag(NameInfo.getLoc(), diag::err_no_member)
5773 << NameInfo.getName() << DC << SS.getRange();
5774 return ExprError();
5775 }
5776
5777 auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp,
5778 bool isTypeAliasTemplateDecl) {
5779 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
5780 << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange()
5781 << isTypeAliasTemplateDecl;
5782 Diag(Temp->getLocation(), diag::note_referenced_type_template)
5783 << isTypeAliasTemplateDecl;
5784 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
5785 };
5786
5788 return DiagnoseTypeTemplateDecl(Temp, false);
5789
5791 return DiagnoseTypeTemplateDecl(Temp, true);
5792
5793 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
5794}
5795
5796/// Form a template name from a name that is syntactically required to name a
5797/// template, either due to use of the 'template' keyword or because a name in
5798/// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5799///
5800/// This action forms a template name given the name of the template and its
5801/// optional scope specifier. This is used when the 'template' keyword is used
5802/// or when the parsing context unambiguously treats a following '<' as
5803/// introducing a template argument list. Note that this may produce a
5804/// non-dependent template name if we can perform the lookup now and identify
5805/// the named template.
5806///
5807/// For example, given "x.MetaFun::template apply", the scope specifier
5808/// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5809/// of the "template" keyword, and "apply" is the \p Name.
5811 CXXScopeSpec &SS,
5812 SourceLocation TemplateKWLoc,
5813 const UnqualifiedId &Name,
5814 ParsedType ObjectType,
5815 bool EnteringContext,
5817 bool AllowInjectedClassName) {
5818 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5819 Diag(TemplateKWLoc,
5821 diag::warn_cxx98_compat_template_outside_of_template :
5822 diag::ext_template_outside_of_template)
5823 << FixItHint::CreateRemoval(TemplateKWLoc);
5824
5825 if (SS.isInvalid())
5826 return TNK_Non_template;
5827
5828 // Figure out where isTemplateName is going to look.
5829 DeclContext *LookupCtx = nullptr;
5830 if (SS.isNotEmpty())
5831 LookupCtx = computeDeclContext(SS, EnteringContext);
5832 else if (ObjectType)
5833 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5834
5835 // C++0x [temp.names]p5:
5836 // If a name prefixed by the keyword template is not the name of
5837 // a template, the program is ill-formed. [Note: the keyword
5838 // template may not be applied to non-template members of class
5839 // templates. -end note ] [ Note: as is the case with the
5840 // typename prefix, the template prefix is allowed in cases
5841 // where it is not strictly necessary; i.e., when the
5842 // nested-name-specifier or the expression on the left of the ->
5843 // or . is not dependent on a template-parameter, or the use
5844 // does not appear in the scope of a template. -end note]
5845 //
5846 // Note: C++03 was more strict here, because it banned the use of
5847 // the "template" keyword prior to a template-name that was not a
5848 // dependent name. C++ DR468 relaxed this requirement (the
5849 // "template" keyword is now permitted). We follow the C++0x
5850 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5851 bool MemberOfUnknownSpecialization;
5852 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5853 ObjectType, EnteringContext, Result,
5854 MemberOfUnknownSpecialization);
5855 if (TNK != TNK_Non_template) {
5856 // We resolved this to a (non-dependent) template name. Return it.
5857 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5858 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5859 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5860 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5861 // C++14 [class.qual]p2:
5862 // In a lookup in which function names are not ignored and the
5863 // nested-name-specifier nominates a class C, if the name specified
5864 // [...] is the injected-class-name of C, [...] the name is instead
5865 // considered to name the constructor
5866 //
5867 // We don't get here if naming the constructor would be valid, so we
5868 // just reject immediately and recover by treating the
5869 // injected-class-name as naming the template.
5870 Diag(Name.getBeginLoc(),
5871 diag::ext_out_of_line_qualified_id_type_names_constructor)
5872 << Name.Identifier
5873 << 0 /*injected-class-name used as template name*/
5874 << TemplateKWLoc.isValid();
5875 }
5876 return TNK;
5877 }
5878
5879 if (!MemberOfUnknownSpecialization) {
5880 // Didn't find a template name, and the lookup wasn't dependent.
5881 // Do the lookup again to determine if this is a "nothing found" case or
5882 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5883 // need to do this.
5885 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5887 // Tell LookupTemplateName that we require a template so that it diagnoses
5888 // cases where it finds a non-template.
5889 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5890 ? RequiredTemplateKind(TemplateKWLoc)
5892 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5893 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5894 !R.isAmbiguous()) {
5895 if (LookupCtx)
5896 Diag(Name.getBeginLoc(), diag::err_no_member)
5897 << DNI.getName() << LookupCtx << SS.getRange();
5898 else
5899 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5900 << DNI.getName() << SS.getRange();
5901 }
5902 return TNK_Non_template;
5903 }
5904
5905 NestedNameSpecifier *Qualifier = SS.getScopeRep();
5906
5907 switch (Name.getKind()) {
5910 Context.getDependentTemplateName(Qualifier, Name.Identifier));
5912
5915 Qualifier, Name.OperatorFunctionId.Operator));
5916 return TNK_Function_template;
5917
5919 // This is a kind of template name, but can never occur in a dependent
5920 // scope (literal operators can only be declared at namespace scope).
5921 break;
5922
5923 default:
5924 break;
5925 }
5926
5927 // This name cannot possibly name a dependent template. Diagnose this now
5928 // rather than building a dependent template name that can never be valid.
5929 Diag(Name.getBeginLoc(),
5930 diag::err_template_kw_refers_to_dependent_non_template)
5931 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5932 << TemplateKWLoc.isValid() << TemplateKWLoc;
5933 return TNK_Non_template;
5934}
5935
5938 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5939 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5940 const TemplateArgument &Arg = AL.getArgument();
5941 QualType ArgType;
5942 TypeSourceInfo *TSI = nullptr;
5943
5944 // Check template type parameter.
5945 switch(Arg.getKind()) {
5947 // C++ [temp.arg.type]p1:
5948 // A template-argument for a template-parameter which is a
5949 // type shall be a type-id.
5950 ArgType = Arg.getAsType();
5951 TSI = AL.getTypeSourceInfo();
5952 break;
5955 // We have a template type parameter but the template argument
5956 // is a template without any arguments.
5957 SourceRange SR = AL.getSourceRange();
5960 return true;
5961 }
5963 // We have a template type parameter but the template argument is an
5964 // expression; see if maybe it is missing the "typename" keyword.
5965 CXXScopeSpec SS;
5966 DeclarationNameInfo NameInfo;
5967
5968 if (DependentScopeDeclRefExpr *ArgExpr =
5969 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5970 SS.Adopt(ArgExpr->getQualifierLoc());
5971 NameInfo = ArgExpr->getNameInfo();
5972 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5973 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5974 if (ArgExpr->isImplicitAccess()) {
5975 SS.Adopt(ArgExpr->getQualifierLoc());
5976 NameInfo = ArgExpr->getMemberNameInfo();
5977 }
5978 }
5979
5980 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5981 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5982 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5983
5984 if (Result.getAsSingle<TypeDecl>() ||
5985 Result.getResultKind() ==
5987 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5988 // Suggest that the user add 'typename' before the NNS.
5990 Diag(Loc, getLangOpts().MSVCCompat
5991 ? diag::ext_ms_template_type_arg_missing_typename
5992 : diag::err_template_arg_must_be_type_suggest)
5993 << FixItHint::CreateInsertion(Loc, "typename ");
5995
5996 // Recover by synthesizing a type using the location information that we
5997 // already have.
5999 SS.getScopeRep(), II);
6000 TypeLocBuilder TLB;
6002 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
6004 TL.setNameLoc(NameInfo.getLoc());
6005 TSI = TLB.getTypeSourceInfo(Context, ArgType);
6006
6007 // Overwrite our input TemplateArgumentLoc so that we can recover
6008 // properly.
6011
6012 break;
6013 }
6014 }
6015 // fallthrough
6016 [[fallthrough]];
6017 }
6018 default: {
6019 // We allow instantiateing a template with template argument packs when
6020 // building deduction guides.
6021 if (Arg.getKind() == TemplateArgument::Pack &&
6022 CodeSynthesisContexts.back().Kind ==
6024 SugaredConverted.push_back(Arg);
6025 CanonicalConverted.push_back(Arg);
6026 return false;
6027 }
6028 // We have a template type parameter but the template argument
6029 // is not a type.
6030 SourceRange SR = AL.getSourceRange();
6031 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
6033
6034 return true;
6035 }
6036 }
6037
6038 if (CheckTemplateArgument(TSI))
6039 return true;
6040
6041 // Objective-C ARC:
6042 // If an explicitly-specified template argument type is a lifetime type
6043 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
6044 if (getLangOpts().ObjCAutoRefCount &&
6045 ArgType->isObjCLifetimeType() &&
6046 !ArgType.getObjCLifetime()) {
6047 Qualifiers Qs;
6049 ArgType = Context.getQualifiedType(ArgType, Qs);
6050 }
6051
6052 SugaredConverted.push_back(TemplateArgument(ArgType));
6053 CanonicalConverted.push_back(
6055 return false;
6056}
6057
6058/// Substitute template arguments into the default template argument for
6059/// the given template type parameter.
6060///
6061/// \param SemaRef the semantic analysis object for which we are performing
6062/// the substitution.
6063///
6064/// \param Template the template that we are synthesizing template arguments
6065/// for.
6066///
6067/// \param TemplateLoc the location of the template name that started the
6068/// template-id we are checking.
6069///
6070/// \param RAngleLoc the location of the right angle bracket ('>') that
6071/// terminates the template-id.
6072///
6073/// \param Param the template template parameter whose default we are
6074/// substituting into.
6075///
6076/// \param Converted the list of template arguments provided for template
6077/// parameters that precede \p Param in the template parameter list.
6078/// \returns the substituted template argument, or NULL if an error occurred.
6080 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
6081 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
6082 ArrayRef<TemplateArgument> SugaredConverted,
6083 ArrayRef<TemplateArgument> CanonicalConverted) {
6084 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
6085
6086 // If the argument type is dependent, instantiate it now based
6087 // on the previously-computed template arguments.
6088 if (ArgType->getType()->isInstantiationDependentType()) {
6089 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
6090 SugaredConverted,
6091 SourceRange(TemplateLoc, RAngleLoc));
6092 if (Inst.isInvalid())
6093 return nullptr;
6094
6095 // Only substitute for the innermost template argument list.
6096 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
6097 /*Final=*/true);
6098 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
6099 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
6100
6101 bool ForLambdaCallOperator = false;
6102 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
6103 ForLambdaCallOperator = Rec->isLambda();
6104 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
6105 !ForLambdaCallOperator);
6106 ArgType =
6107 SemaRef.SubstType(ArgType, TemplateArgLists,
6108 Param->getDefaultArgumentLoc(), Param->getDeclName());
6109 }
6110
6111 return ArgType;
6112}
6113
6114/// Substitute template arguments into the default template argument for
6115/// the given non-type template parameter.
6116///
6117/// \param SemaRef the semantic analysis object for which we are performing
6118/// the substitution.
6119///
6120/// \param Template the template that we are synthesizing template arguments
6121/// for.
6122///
6123/// \param TemplateLoc the location of the template name that started the
6124/// template-id we are checking.
6125///
6126/// \param RAngleLoc the location of the right angle bracket ('>') that
6127/// terminates the template-id.
6128///
6129/// \param Param the non-type template parameter whose default we are
6130/// substituting into.
6131///
6132/// \param Converted the list of template arguments provided for template
6133/// parameters that precede \p Param in the template parameter list.
6134///
6135/// \returns the substituted template argument, or NULL if an error occurred.
6137 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
6138 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
6139 ArrayRef<TemplateArgument> SugaredConverted,
6140 ArrayRef<TemplateArgument> CanonicalConverted) {
6141 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
6142 SugaredConverted,
6143 SourceRange(TemplateLoc, RAngleLoc));
6144 if (Inst.isInvalid())
6145 return ExprError();
6146
6147 // Only substitute for the innermost template argument list.
6148 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
6149 /*Final=*/true);
6150 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
6151 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
6152
6153 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
6154 EnterExpressionEvaluationContext ConstantEvaluated(
6156 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
6157}
6158
6159/// Substitute template arguments into the default template argument for
6160/// the given template template parameter.
6161///
6162/// \param SemaRef the semantic analysis object for which we are performing
6163/// the substitution.
6164///
6165/// \param Template the template that we are synthesizing template arguments
6166/// for.
6167///
6168/// \param TemplateLoc the location of the template name that started the
6169/// template-id we are checking.
6170///
6171/// \param RAngleLoc the location of the right angle bracket ('>') that
6172/// terminates the template-id.
6173///
6174/// \param Param the template template parameter whose default we are
6175/// substituting into.
6176///
6177/// \param Converted the list of template arguments provided for template
6178/// parameters that precede \p Param in the template parameter list.
6179///
6180/// \param QualifierLoc Will be set to the nested-name-specifier (with
6181/// source-location information) that precedes the template name.
6182///
6183/// \returns the substituted template argument, or NULL if an error occurred.
6185 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
6186 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
6187 ArrayRef<TemplateArgument> SugaredConverted,
6188 ArrayRef<TemplateArgument> CanonicalConverted,
6189 NestedNameSpecifierLoc &QualifierLoc) {
6191 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
6192 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
6193 if (Inst.isInvalid())
6194 return TemplateName();
6195
6196 // Only substitute for the innermost template argument list.
6197 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
6198 /*Final=*/true);
6199 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
6200 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
6201
6202 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
6203 // Substitute into the nested-name-specifier first,
6204 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
6205 if (QualifierLoc) {
6206 QualifierLoc =
6207 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
6208 if (!QualifierLoc)
6209 return TemplateName();
6210 }
6211
6212 return SemaRef.SubstTemplateName(
6213 QualifierLoc,
6216 TemplateArgLists);
6217}
6218
6219/// If the given template parameter has a default template
6220/// argument, substitute into that default template argument and
6221/// return the corresponding template argument.
6223 TemplateDecl *Template, SourceLocation TemplateLoc,
6224 SourceLocation RAngleLoc, Decl *Param,
6225 ArrayRef<TemplateArgument> SugaredConverted,
6226 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
6227 HasDefaultArg = false;
6228
6229 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
6230 if (!hasReachableDefaultArgument(TypeParm))
6231 return TemplateArgumentLoc();
6232
6233 HasDefaultArg = true;
6235 *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted,
6236 CanonicalConverted);
6237 if (DI)
6238 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
6239
6240 return TemplateArgumentLoc();
6241 }
6242
6243 if (NonTypeTemplateParmDecl *NonTypeParm
6244 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6245 if (!hasReachableDefaultArgument(NonTypeParm))
6246 return TemplateArgumentLoc();
6247
6248 HasDefaultArg = true;
6250 *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted,
6251 CanonicalConverted);
6252 if (Arg.isInvalid())
6253 return TemplateArgumentLoc();
6254
6255 Expr *ArgE = Arg.getAs<Expr>();
6256 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
6257 }
6258
6259 TemplateTemplateParmDecl *TempTempParm
6260 = cast<TemplateTemplateParmDecl>(Param);
6261 if (!hasReachableDefaultArgument(TempTempParm))
6262 return TemplateArgumentLoc();
6263
6264 HasDefaultArg = true;
6265 NestedNameSpecifierLoc QualifierLoc;
6267 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
6268 CanonicalConverted, QualifierLoc);
6269 if (TName.isNull())
6270 return TemplateArgumentLoc();
6271
6272 return TemplateArgumentLoc(
6273 Context, TemplateArgument(TName),
6275 TempTempParm->getDefaultArgument().getTemplateNameLoc());
6276}
6277
6278/// Convert a template-argument that we parsed as a type into a template, if
6279/// possible. C++ permits injected-class-names to perform dual service as
6280/// template template arguments and as template type arguments.
6283 // Extract and step over any surrounding nested-name-specifier.
6284 NestedNameSpecifierLoc QualLoc;
6285 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
6286 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
6287 return TemplateArgumentLoc();
6288
6289 QualLoc = ETLoc.getQualifierLoc();
6290 TLoc = ETLoc.getNamedTypeLoc();
6291 }
6292 // If this type was written as an injected-class-name, it can be used as a
6293 // template template argument.
6294 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
6295 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
6296 QualLoc, InjLoc.getNameLoc());
6297
6298 // If this type was written as an injected-class-name, it may have been
6299 // converted to a RecordType during instantiation. If the RecordType is
6300 // *not* wrapped in a TemplateSpecializationType and denotes a class
6301 // template specialization, it must have come from an injected-class-name.
6302 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
6303 if (auto *CTSD =
6304 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
6305 return TemplateArgumentLoc(Context,
6306 TemplateName(CTSD->getSpecializedTemplate()),
6307 QualLoc, RecLoc.getNameLoc());
6308
6309 return TemplateArgumentLoc();
6310}
6311
6312/// Check that the given template argument corresponds to the given
6313/// template parameter.
6314///
6315/// \param Param The template parameter against which the argument will be
6316/// checked.
6317///
6318/// \param Arg The template argument, which may be updated due to conversions.
6319///
6320/// \param Template The template in which the template argument resides.
6321///
6322/// \param TemplateLoc The location of the template name for the template
6323/// whose argument list we're matching.
6324///
6325/// \param RAngleLoc The location of the right angle bracket ('>') that closes
6326/// the template argument list.
6327///
6328/// \param ArgumentPackIndex The index into the argument pack where this
6329/// argument will be placed. Only valid if the parameter is a parameter pack.
6330///
6331/// \param Converted The checked, converted argument will be added to the
6332/// end of this small vector.
6333///
6334/// \param CTAK Describes how we arrived at this particular template argument:
6335/// explicitly written, deduced, etc.
6336///
6337/// \returns true on error, false otherwise.
6339 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
6340 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
6341 unsigned ArgumentPackIndex,
6342 SmallVectorImpl<TemplateArgument> &SugaredConverted,
6343 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
6345 // Check template type parameters.
6346 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
6347 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
6348 CanonicalConverted);
6349
6350 // Check non-type template parameters.
6351 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6352 // Do substitution on the type of the non-type template parameter
6353 // with the template arguments we've seen thus far. But if the
6354 // template has a dependent context then we cannot substitute yet.
6355 QualType NTTPType = NTTP->getType();
6356 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
6357 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
6358
6359 if (NTTPType->isInstantiationDependentType() &&
6360 !isa<TemplateTemplateParmDecl>(Template) &&
6361 !Template->getDeclContext()->isDependentContext()) {
6362 // Do substitution on the type of the non-type template parameter.
6363 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
6364 SugaredConverted,
6365 SourceRange(TemplateLoc, RAngleLoc));
6366 if (Inst.isInvalid())
6367 return true;
6368
6369 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
6370 /*Final=*/true);
6371 // If the parameter is a pack expansion, expand this slice of the pack.
6372 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
6374 ArgumentPackIndex);
6375 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
6376 NTTP->getDeclName());
6377 } else {
6378 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
6379 NTTP->getDeclName());
6380 }
6381
6382 // If that worked, check the non-type template parameter type
6383 // for validity.
6384 if (!NTTPType.isNull())
6385 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
6386 NTTP->getLocation());
6387 if (NTTPType.isNull())
6388 return true;
6389 }
6390
6391 switch (Arg.getArgument().getKind()) {
6393 llvm_unreachable("Should never see a NULL template argument here");
6394
6396 Expr *E = Arg.getArgument().getAsExpr();
6397 TemplateArgument SugaredResult, CanonicalResult;
6398 unsigned CurSFINAEErrors = NumSFINAEErrors;
6399 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
6400 CanonicalResult, CTAK);
6401 if (Res.isInvalid())
6402 return true;
6403 // If the current template argument causes an error, give up now.
6404 if (CurSFINAEErrors < NumSFINAEErrors)
6405 return true;
6406
6407 // If the resulting expression is new, then use it in place of the
6408 // old expression in the template argument.
6409 if (Res.get() != E) {
6410 TemplateArgument TA(Res.get());
6411 Arg = TemplateArgumentLoc(TA, Res.get());
6412 }
6413
6414 SugaredConverted.push_back(SugaredResult);
6415 CanonicalConverted.push_back(CanonicalResult);
6416 break;
6417 }
6418
6423 // We've already checked this template argument, so just copy
6424 // it to the list of converted arguments.
6425 SugaredConverted.push_back(Arg.getArgument());
6426 CanonicalConverted.push_back(
6428 break;
6429
6432 // We were given a template template argument. It may not be ill-formed;
6433 // see below.
6434 if (DependentTemplateName *DTN
6437 // We have a template argument such as \c T::template X, which we
6438 // parsed as a template template argument. However, since we now
6439 // know that we need a non-type template argument, convert this
6440 // template name into an expression.
6441
6442 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
6443 Arg.getTemplateNameLoc());
6444
6445 CXXScopeSpec SS;
6447 // FIXME: the template-template arg was a DependentTemplateName,
6448 // so it was provided with a template keyword. However, its source
6449 // location is not stored in the template argument structure.
6450 SourceLocation TemplateKWLoc;
6452 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
6453 nullptr);
6454
6455 // If we parsed the template argument as a pack expansion, create a
6456 // pack expansion expression.
6459 if (E.isInvalid())
6460 return true;
6461 }
6462
6463 TemplateArgument SugaredResult, CanonicalResult;
6464 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
6465 CanonicalResult, CTAK_Specified);
6466 if (E.isInvalid())
6467 return true;
6468
6469 SugaredConverted.push_back(SugaredResult);
6470 CanonicalConverted.push_back(CanonicalResult);
6471 break;
6472 }
6473
6474 // We have a template argument that actually does refer to a class
6475 // template, alias template, or template template parameter, and
6476 // therefore cannot be a non-type template argument.
6477 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
6478 << Arg.getSourceRange();
6480
6481 return true;
6482
6484 // We have a non-type template parameter but the template
6485 // argument is a type.
6486
6487 // C++ [temp.arg]p2:
6488 // In a template-argument, an ambiguity between a type-id and
6489 // an expression is resolved to a type-id, regardless of the
6490 // form of the corresponding template-parameter.
6491 //
6492 // We warn specifically about this case, since it can be rather
6493 // confusing for users.
6494 QualType T = Arg.getArgument().getAsType();
6495 SourceRange SR = Arg.getSourceRange();
6496 if (T->isFunctionType())
6497 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
6498 else
6499 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
6501 return true;
6502 }
6503
6505 llvm_unreachable("Caller must expand template argument packs");
6506 }
6507
6508 return false;
6509 }
6510
6511
6512 // Check template template parameters.
6513 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
6514
6515 TemplateParameterList *Params = TempParm->getTemplateParameters();
6516 if (TempParm->isExpandedParameterPack())
6517 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
6518
6519 // Substitute into the template parameter list of the template
6520 // template parameter, since previously-supplied template arguments
6521 // may appear within the template template parameter.
6522 //
6523 // FIXME: Skip this if the parameters aren't instantiation-dependent.
6524 {
6525 // Set up a template instantiation context.
6527 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
6528 SugaredConverted,
6529 SourceRange(TemplateLoc, RAngleLoc));
6530 if (Inst.isInvalid())
6531 return true;
6532
6533 Params =
6536 Template, SugaredConverted, /*Final=*/true),
6537 /*EvaluateConstraints=*/false);
6538 if (!Params)
6539 return true;
6540 }
6541
6542 // C++1z [temp.local]p1: (DR1004)
6543 // When [the injected-class-name] is used [...] as a template-argument for
6544 // a template template-parameter [...] it refers to the class template
6545 // itself.
6549 if (!ConvertedArg.getArgument().isNull())
6550 Arg = ConvertedArg;
6551 }
6552
6553 switch (Arg.getArgument().getKind()) {
6555 llvm_unreachable("Should never see a NULL template argument here");
6556
6559 if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
6560 /*IsDeduced=*/CTAK != CTAK_Specified))
6561 return true;
6562
6563 SugaredConverted.push_back(Arg.getArgument());
6564 CanonicalConverted.push_back(
6566 break;
6567
6570 // We have a template template parameter but the template
6571 // argument does not refer to a template.
6572 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
6573 << getLangOpts().CPlusPlus11;
6574 return true;
6575
6580 llvm_unreachable("non-type argument with template template parameter");
6581
6583 llvm_unreachable("Caller must expand template argument packs");
6584 }
6585
6586 return false;
6587}
6588
6589/// Diagnose a missing template argument.
6590template<typename TemplateParmDecl>
6592 TemplateDecl *TD,
6593 const TemplateParmDecl *D,
6595 // Dig out the most recent declaration of the template parameter; there may be
6596 // declarations of the template that are more recent than TD.
6597 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
6598 ->getTemplateParameters()
6599 ->getParam(D->getIndex()));
6600
6601 // If there's a default argument that's not reachable, diagnose that we're
6602 // missing a module import.
6604 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
6605 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
6606 D->getDefaultArgumentLoc(), Modules,
6608 /*Recover*/true);
6609 return true;
6610 }
6611
6612 // FIXME: If there's a more recent default argument that *is* visible,
6613 // diagnose that it was declared too late.
6614
6616
6617 S.Diag(Loc, diag::err_template_arg_list_different_arity)
6618 << /*not enough args*/0
6620 << TD;
6621 S.NoteTemplateLocation(*TD, Params->getSourceRange());
6622 return true;
6623}
6624
6625/// Check that the given template argument list is well-formed
6626/// for specializing the given template.
6628 TemplateDecl *Template, SourceLocation TemplateLoc,
6629 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
6630 SmallVectorImpl<TemplateArgument> &SugaredConverted,
6631 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
6632 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
6633 bool PartialOrderingTTP) {
6634
6636 *ConstraintsNotSatisfied = false;
6637
6638 // Make a copy of the template arguments for processing. Only make the
6639 // changes at the end when successful in matching the arguments to the
6640 // template.
6641 TemplateArgumentListInfo NewArgs = TemplateArgs;
6642
6644
6645 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
6646
6647 // C++ [temp.arg]p1:
6648 // [...] The type and form of each template-argument specified in
6649 // a template-id shall match the type and form specified for the
6650 // corresponding parameter declared by the template in its
6651 // template-parameter-list.
6652 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
6653 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
6654 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
6655 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
6656 LocalInstantiationScope InstScope(*this, true);
6657 for (TemplateParameterList::iterator Param = Params->begin(),
6658 ParamEnd = Params->end();
6659 Param != ParamEnd; /* increment in loop */) {
6660 // If we have an expanded parameter pack, make sure we don't have too
6661 // many arguments.
6662 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
6663 if (*Expansions == SugaredArgumentPack.size()) {
6664 // We're done with this parameter pack. Pack up its arguments and add
6665 // them to the list.
6666 SugaredConverted.push_back(
6667 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6668 SugaredArgumentPack.clear();
6669
6670 CanonicalConverted.push_back(
6671 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6672 CanonicalArgumentPack.clear();
6673
6674 // This argument is assigned to the next parameter.
6675 ++Param;
6676 continue;
6677 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
6678 // Not enough arguments for this parameter pack.
6679 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6680 << /*not enough args*/0
6682 << Template;
6683 NoteTemplateLocation(*Template, Params->getSourceRange());
6684 return true;
6685 }
6686 }
6687
6688 if (ArgIdx < NumArgs) {
6689 // Check the template argument we were given.
6690 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
6691 RAngleLoc, SugaredArgumentPack.size(),
6692 SugaredConverted, CanonicalConverted,
6694 return true;
6695
6696 CanonicalConverted.back().setIsDefaulted(
6698 Context, NewArgs[ArgIdx].getArgument(), *Param,
6699 CanonicalConverted, Params->getDepth()));
6700
6701 bool PackExpansionIntoNonPack =
6702 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
6703 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
6704 // CWG1430: Don't diagnose this pack expansion when partial
6705 // ordering template template parameters. Some uses of the template could
6706 // be valid, and invalid uses will be diagnosed later during
6707 // instantiation.
6708 if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
6709 (isa<TypeAliasTemplateDecl>(Template) ||
6710 isa<ConceptDecl>(Template))) {
6711 // CWG1430: we have a pack expansion as an argument to an
6712 // alias template, and it's not part of a parameter pack. This
6713 // can't be canonicalized, so reject it now.
6714 // As for concepts - we cannot normalize constraints where this
6715 // situation exists.
6716 Diag(NewArgs[ArgIdx].getLocation(),
6717 diag::err_template_expansion_into_fixed_list)
6718 << (isa<ConceptDecl>(Template) ? 1 : 0)
6719 << NewArgs[ArgIdx].getSourceRange();
6721 return true;
6722 }
6723
6724 // We're now done with this argument.
6725 ++ArgIdx;
6726
6727 if ((*Param)->isTemplateParameterPack()) {
6728 // The template parameter was a template parameter pack, so take the
6729 // deduced argument and place it on the argument pack. Note that we
6730 // stay on the same template parameter so that we can deduce more
6731 // arguments.
6732 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
6733 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
6734 } else {
6735 // Move to the next template parameter.
6736 ++Param;
6737 }
6738
6739 // If we just saw a pack expansion into a non-pack, then directly convert
6740 // the remaining arguments, because we don't know what parameters they'll
6741 // match up with.
6742 if (PackExpansionIntoNonPack) {
6743 if (!SugaredArgumentPack.empty()) {
6744 // If we were part way through filling in an expanded parameter pack,
6745 // fall back to just producing individual arguments.
6746 SugaredConverted.insert(SugaredConverted.end(),
6747 SugaredArgumentPack.begin(),
6748 SugaredArgumentPack.end());
6749 SugaredArgumentPack.clear();
6750
6751 CanonicalConverted.insert(CanonicalConverted.end(),
6752 CanonicalArgumentPack.begin(),
6753 CanonicalArgumentPack.end());
6754 CanonicalArgumentPack.clear();
6755 }
6756
6757 while (ArgIdx < NumArgs) {
6758 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6759 SugaredConverted.push_back(Arg);
6760 CanonicalConverted.push_back(
6762 ++ArgIdx;
6763 }
6764
6765 return false;
6766 }
6767
6768 continue;
6769 }
6770
6771 // If we're checking a partial template argument list, we're done.
6772 if (PartialTemplateArgs) {
6773 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6774 SugaredConverted.push_back(
6775 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6776 CanonicalConverted.push_back(
6777 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6778 }
6779 return false;
6780 }
6781
6782 // If we have a template parameter pack with no more corresponding
6783 // arguments, just break out now and we'll fill in the argument pack below.
6784 if ((*Param)->isTemplateParameterPack()) {
6785 assert(!getExpandedPackSize(*Param) &&
6786 "Should have dealt with this already");
6787
6788 // A non-expanded parameter pack before the end of the parameter list
6789 // only occurs for an ill-formed template parameter list, unless we've
6790 // got a partial argument list for a function template, so just bail out.
6791 if (Param + 1 != ParamEnd) {
6792 assert(
6793 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6794 "Concept templates must have parameter packs at the end.");
6795 return true;
6796 }
6797
6798 SugaredConverted.push_back(
6799 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6800 SugaredArgumentPack.clear();
6801
6802 CanonicalConverted.push_back(
6803 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6804 CanonicalArgumentPack.clear();
6805
6806 ++Param;
6807 continue;
6808 }
6809
6810 // Check whether we have a default argument.
6812
6813 // Retrieve the default template argument from the template
6814 // parameter. For each kind of template parameter, we substitute the
6815 // template arguments provided thus far and any "outer" template arguments
6816 // (when the template parameter was part of a nested template) into
6817 // the default argument.
6818 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
6820 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6821 NewArgs);
6822
6824 *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted,
6825 CanonicalConverted);
6826 if (!ArgType)
6827 return true;
6828
6830 ArgType);
6831 } else if (NonTypeTemplateParmDecl *NTTP
6832 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
6833 if (!hasReachableDefaultArgument(NTTP))
6834 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6835 NewArgs);
6836
6838 *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted,
6839 CanonicalConverted);
6840 if (E.isInvalid())
6841 return true;
6842
6843 Expr *Ex = E.getAs<Expr>();
6845 } else {
6846 TemplateTemplateParmDecl *TempParm
6847 = cast<TemplateTemplateParmDecl>(*Param);
6848
6849 if (!hasReachableDefaultArgument(TempParm))
6850 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
6851 NewArgs);
6852
6853 NestedNameSpecifierLoc QualifierLoc;
6855 *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
6856 CanonicalConverted, QualifierLoc);
6857 if (Name.isNull())
6858 return true;
6859
6860 Arg = TemplateArgumentLoc(
6861 Context, TemplateArgument(Name), QualifierLoc,
6863 }
6864
6865 // Introduce an instantiation record that describes where we are using
6866 // the default template argument. We're not actually instantiating a
6867 // template here, we just create this object to put a note into the
6868 // context stack.
6869 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6870 SugaredConverted,
6871 SourceRange(TemplateLoc, RAngleLoc));
6872 if (Inst.isInvalid())
6873 return true;
6874
6875 // Check the default template argument.
6876 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6877 SugaredConverted, CanonicalConverted,
6879 return true;
6880
6881 CanonicalConverted.back().setIsDefaulted(true);
6882
6883 // Core issue 150 (assumed resolution): if this is a template template
6884 // parameter, keep track of the default template arguments from the
6885 // template definition.
6886 if (isTemplateTemplateParameter)
6887 NewArgs.addArgument(Arg);
6888
6889 // Move to the next template parameter and argument.
6890 ++Param;
6891 ++ArgIdx;
6892 }
6893
6894 // If we're performing a partial argument substitution, allow any trailing
6895 // pack expansions; they might be empty. This can happen even if
6896 // PartialTemplateArgs is false (the list of arguments is complete but
6897 // still dependent).
6898 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
6900 while (ArgIdx < NumArgs &&
6901 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6902 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6903 SugaredConverted.push_back(Arg);
6904 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
6905 }
6906 }
6907
6908 // If we have any leftover arguments, then there were too many arguments.
6909 // Complain and fail.
6910 if (ArgIdx < NumArgs) {
6911 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6912 << /*too many args*/1
6914 << Template
6915 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6916 NoteTemplateLocation(*Template, Params->getSourceRange());
6917 return true;
6918 }
6919
6920 // No problems found with the new argument list, propagate changes back
6921 // to caller.
6922 if (UpdateArgsWithConversions)
6923 TemplateArgs = std::move(NewArgs);
6924
6925 if (!PartialTemplateArgs) {
6926 // Setup the context/ThisScope for the case where we are needing to
6927 // re-instantiate constraints outside of normal instantiation.
6928 DeclContext *NewContext = Template->getDeclContext();
6929
6930 // If this template is in a template, make sure we extract the templated
6931 // decl.
6932 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6933 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6934 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6935
6936 Qualifiers ThisQuals;
6937 if (const auto *Method =
6938 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6939 ThisQuals = Method->getMethodQualifiers();
6940
6941 ContextRAII Context(*this, NewContext);
6942 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
6943
6945 Template, NewContext, /*Final=*/false, CanonicalConverted,
6946 /*RelativeToPrimary=*/true,
6947 /*Pattern=*/nullptr,
6948 /*ForConceptInstantiation=*/true);
6950 Template, MLTAL,
6951 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6954 return true;
6955 }
6956 }
6957
6958 return false;
6959}
6960
6961namespace {
6962 class UnnamedLocalNoLinkageFinder
6963 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6964 {
6965 Sema &S;
6966 SourceRange SR;
6967
6969
6970 public:
6971 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6972
6973 bool Visit(QualType T) {
6974 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6975 }
6976
6977#define TYPE(Class, Parent) \
6978 bool Visit##Class##Type(const Class##Type *);
6979#define ABSTRACT_TYPE(Class, Parent) \
6980 bool Visit##Class##Type(const Class##Type *) { return false; }
6981#define NON_CANONICAL_TYPE(Class, Parent) \
6982 bool Visit##Class##Type(const Class##Type *) { return false; }
6983#include "clang/AST/TypeNodes.inc"
6984
6985 bool VisitTagDecl(const TagDecl *Tag);
6986 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6987 };
6988} // end anonymous namespace
6989
6990bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6991 return false;
6992}
6993
6994bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6995 return Visit(T->getElementType());
6996}
6997
6998bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6999 return Visit(T->getPointeeType());
7000}
7001
7002bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
7003 const BlockPointerType* T) {
7004 return Visit(T->getPointeeType());
7005}
7006
7007bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
7008 const LValueReferenceType* T) {
7009 return Visit(T->getPointeeType());
7010}
7011
7012bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
7013 const RValueReferenceType* T) {
7014 return Visit(T->getPointeeType());
7015}
7016
7017bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
7018 const MemberPointerType* T) {
7019 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
7020}
7021
7022bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
7023 const ConstantArrayType* T) {
7024 return Visit(T->getElementType());
7025}
7026
7027bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
7028 const IncompleteArrayType* T) {
7029 return Visit(T->getElementType());
7030}
7031
7032bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
7033 const VariableArrayType* T) {
7034 return Visit(T->getElementType());
7035}
7036
7037bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
7038 const DependentSizedArrayType* T) {
7039 return Visit(T->getElementType());
7040}
7041
7042bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
7044 return Visit(T->getElementType());
7045}
7046
7047bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
7048 const DependentSizedMatrixType *T) {
7049 return Visit(T->getElementType());
7050}
7051
7052bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
7054 return Visit(T->getPointeeType());
7055}
7056
7057bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
7058 return Visit(T->getElementType());
7059}
7060
7061bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
7062 const DependentVectorType *T) {
7063 return Visit(T->getElementType());
7064}
7065
7066bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
7067 return Visit(T->getElementType());
7068}
7069
7070bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
7071 const ConstantMatrixType *T) {
7072 return Visit(T->getElementType());
7073}
7074
7075bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
7076 const FunctionProtoType* T) {
7077 for (const auto &A : T->param_types()) {
7078 if (Visit(A))
7079 return true;
7080 }
7081
7082 return Visit(T->getReturnType());
7083}
7084
7085bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
7086 const FunctionNoProtoType* T) {
7087 return Visit(T->getReturnType());
7088}
7089
7090bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
7091 const UnresolvedUsingType*) {
7092 return false;
7093}
7094
7095bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
7096 return false;
7097}
7098
7099bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
7100 return Visit(T->getUnmodifiedType());
7101}
7102
7103bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
7104 return false;
7105}
7106
7107bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
7108 const PackIndexingType *) {
7109 return false;
7110}
7111
7112bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
7113 const UnaryTransformType*) {
7114 return false;
7115}
7116
7117bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
7118 return Visit(T->getDeducedType());
7119}
7120
7121bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
7123 return Visit(T->getDeducedType());
7124}
7125
7126bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
7127 return VisitTagDecl(T->getDecl());
7128}
7129
7130bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
7131 return VisitTagDecl(T->getDecl());
7132}
7133
7134bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
7135 const TemplateTypeParmType*) {
7136 return false;
7137}
7138
7139bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
7141 return false;
7142}
7143
7144bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
7146 return false;
7147}
7148
7149bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
7150 const InjectedClassNameType* T) {
7151 return VisitTagDecl(T->getDecl());
7152}
7153
7154bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
7155 const DependentNameType* T) {
7156 return VisitNestedNameSpecifier(T->getQualifier());
7157}
7158
7159bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
7161 if (auto *Q = T->getQualifier())
7162 return VisitNestedNameSpecifier(Q);
7163 return false;
7164}
7165
7166bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
7167 const PackExpansionType* T) {
7168 return Visit(T->getPattern());
7169}
7170
7171bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
7172 return false;
7173}
7174
7175bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
7176 const ObjCInterfaceType *) {
7177 return false;
7178}
7179
7180bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
7181 const ObjCObjectPointerType *) {
7182 return false;
7183}
7184
7185bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
7186 return Visit(T->getValueType());
7187}
7188
7189bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
7190 return false;
7191}
7192
7193bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
7194 return false;
7195}
7196
7197bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
7198 const ArrayParameterType *T) {
7199 return VisitConstantArrayType(T);
7200}
7201
7202bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
7203 const DependentBitIntType *T) {
7204 return false;
7205}
7206
7207bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
7208 if (Tag->getDeclContext()->isFunctionOrMethod()) {
7209 S.Diag(SR.getBegin(),
7210 S.getLangOpts().CPlusPlus11 ?
7211 diag::warn_cxx98_compat_template_arg_local_type :
7212 diag::ext_template_arg_local_type)
7213 << S.Context.getTypeDeclType(Tag) << SR;
7214 return true;
7215 }
7216
7217 if (!Tag->hasNameForLinkage()) {
7218 S.Diag(SR.getBegin(),
7219 S.getLangOpts().CPlusPlus11 ?
7220 diag::warn_cxx98_compat_template_arg_unnamed_type :
7221 diag::ext_template_arg_unnamed_type) << SR;
7222 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
7223 return true;
7224 }
7225
7226 return false;
7227}
7228
7229bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
7230 NestedNameSpecifier *NNS) {
7231 assert(NNS);
7232 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
7233 return true;
7234
7235 switch (NNS->getKind()) {
7241 return false;
7242
7245 return Visit(QualType(NNS->getAsType(), 0));
7246 }
7247 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7248}
7249
7250/// Check a template argument against its corresponding
7251/// template type parameter.
7252///
7253/// This routine implements the semantics of C++ [temp.arg.type]. It
7254/// returns true if an error occurred, and false otherwise.
7256 assert(ArgInfo && "invalid TypeSourceInfo");
7257 QualType Arg = ArgInfo->getType();
7258 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
7259 QualType CanonArg = Context.getCanonicalType(Arg);
7260
7261 if (CanonArg->isVariablyModifiedType()) {
7262 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
7264 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
7265 }
7266
7267 // C++03 [temp.arg.type]p2:
7268 // A local type, a type with no linkage, an unnamed type or a type
7269 // compounded from any of these types shall not be used as a
7270 // template-argument for a template type-parameter.
7271 //
7272 // C++11 allows these, and even in C++03 we allow them as an extension with
7273 // a warning.
7274 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
7275 UnnamedLocalNoLinkageFinder Finder(*this, SR);
7276 (void)Finder.Visit(CanonArg);
7277 }
7278
7279 return false;
7280}
7281
7285 NPV_Error
7287
7288/// Determine whether the given template argument is a null pointer
7289/// value of the appropriate type.
7292 QualType ParamType, Expr *Arg,
7293 Decl *Entity = nullptr) {
7294 if (Arg->isValueDependent() || Arg->isTypeDependent())
7295 return NPV_NotNullPointer;
7296
7297 // dllimport'd entities aren't constant but are available inside of template
7298 // arguments.
7299 if (Entity && Entity->hasAttr<DLLImportAttr>())
7300 return NPV_NotNullPointer;
7301
7302 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
7303 llvm_unreachable(
7304 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
7305
7306 if (!S.getLangOpts().CPlusPlus11)
7307 return NPV_NotNullPointer;
7308
7309 // Determine whether we have a constant expression.
7311 if (ArgRV.isInvalid())
7312 return NPV_Error;
7313 Arg = ArgRV.get();
7314
7315 Expr::EvalResult EvalResult;
7317 EvalResult.Diag = &Notes;
7318 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
7319 EvalResult.HasSideEffects) {
7320 SourceLocation DiagLoc = Arg->getExprLoc();
7321
7322 // If our only note is the usual "invalid subexpression" note, just point
7323 // the caret at its location rather than producing an essentially
7324 // redundant note.
7325 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7326 diag::note_invalid_subexpr_in_const_expr) {
7327 DiagLoc = Notes[0].first;
7328 Notes.clear();
7329 }
7330
7331 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
7332 << Arg->getType() << Arg->getSourceRange();
7333 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7334 S.Diag(Notes[I].first, Notes[I].second);
7335
7337 return NPV_Error;
7338 }
7339
7340 // C++11 [temp.arg.nontype]p1:
7341 // - an address constant expression of type std::nullptr_t
7342 if (Arg->getType()->isNullPtrType())
7343 return NPV_NullPointer;
7344
7345 // - a constant expression that evaluates to a null pointer value (4.10); or
7346 // - a constant expression that evaluates to a null member pointer value
7347 // (4.11); or
7348 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
7349 (EvalResult.Val.isMemberPointer() &&
7350 !EvalResult.Val.getMemberPointerDecl())) {
7351 // If our expression has an appropriate type, we've succeeded.
7352 bool ObjCLifetimeConversion;
7353 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
7354 S.IsQualificationConversion(Arg->getType(), ParamType, false,
7355 ObjCLifetimeConversion))
7356 return NPV_NullPointer;
7357
7358 // The types didn't match, but we know we got a null pointer; complain,
7359 // then recover as if the types were correct.
7360 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
7361 << Arg->getType() << ParamType << Arg->getSourceRange();
7363 return NPV_NullPointer;
7364 }
7365
7366 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
7367 // We found a pointer that isn't null, but doesn't refer to an object.
7368 // We could just return NPV_NotNullPointer, but we can print a better
7369 // message with the information we have here.
7370 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
7371 << EvalResult.Val.getAsString(S.Context, ParamType);
7373 return NPV_Error;
7374 }
7375
7376 // If we don't have a null pointer value, but we do have a NULL pointer
7377 // constant, suggest a cast to the appropriate type.
7379 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
7380 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
7381 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
7383 ")");
7385 return NPV_NullPointer;
7386 }
7387
7388 // FIXME: If we ever want to support general, address-constant expressions
7389 // as non-type template arguments, we should return the ExprResult here to
7390 // be interpreted by the caller.
7391 return NPV_NotNullPointer;
7392}
7393
7394/// Checks whether the given template argument is compatible with its
7395/// template parameter.
7397 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
7398 Expr *Arg, QualType ArgType) {
7399 bool ObjCLifetimeConversion;
7400 if (ParamType->isPointerType() &&
7401 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
7402 S.IsQualificationConversion(ArgType, ParamType, false,
7403 ObjCLifetimeConversion)) {
7404 // For pointer-to-object types, qualification conversions are
7405 // permitted.
7406 } else {
7407 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
7408 if (!ParamRef->getPointeeType()->isFunctionType()) {
7409 // C++ [temp.arg.nontype]p5b3:
7410 // For a non-type template-parameter of type reference to
7411 // object, no conversions apply. The type referred to by the
7412 // reference may be more cv-qualified than the (otherwise
7413 // identical) type of the template- argument. The
7414 // template-parameter is bound directly to the
7415 // template-argument, which shall be an lvalue.
7416
7417 // FIXME: Other qualifiers?
7418 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
7419 unsigned ArgQuals = ArgType.getCVRQualifiers();
7420
7421 if ((ParamQuals | ArgQuals) != ParamQuals) {
7422 S.Diag(Arg->getBeginLoc(),
7423 diag::err_template_arg_ref_bind_ignores_quals)
7424 << ParamType << Arg->getType() << Arg->getSourceRange();
7426 return true;
7427 }
7428 }
7429 }
7430
7431 // At this point, the template argument refers to an object or
7432 // function with external linkage. We now need to check whether the
7433 // argument and parameter types are compatible.
7434 if (!S.Context.hasSameUnqualifiedType(ArgType,
7435 ParamType.getNonReferenceType())) {
7436 // We can't perform this conversion or binding.
7437 if (ParamType->isReferenceType())
7438 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
7439 << ParamType << ArgIn->getType() << Arg->getSourceRange();
7440 else
7441 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7442 << ArgIn->getType() << ParamType << Arg->getSourceRange();
7444 return true;
7445 }
7446 }
7447
7448 return false;
7449}
7450
7451/// Checks whether the given template argument is the address
7452/// of an object or function according to C++ [temp.arg.nontype]p1.
7454 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
7455 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7456 bool Invalid = false;
7457 Expr *Arg = ArgIn;
7458 QualType ArgType = Arg->getType();
7459
7460 bool AddressTaken = false;
7461 SourceLocation AddrOpLoc;
7462 if (S.getLangOpts().MicrosoftExt) {
7463 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
7464 // dereference and address-of operators.
7465 Arg = Arg->IgnoreParenCasts();
7466
7467 bool ExtWarnMSTemplateArg = false;
7468 UnaryOperatorKind FirstOpKind;
7469 SourceLocation FirstOpLoc;
7470 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7471 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
7472 if (UnOpKind == UO_Deref)
7473 ExtWarnMSTemplateArg = true;
7474 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
7475 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
7476 if (!AddrOpLoc.isValid()) {
7477 FirstOpKind = UnOpKind;
7478 FirstOpLoc = UnOp->getOperatorLoc();
7479 }
7480 } else
7481 break;
7482 }
7483 if (FirstOpLoc.isValid()) {
7484 if (ExtWarnMSTemplateArg)
7485 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
7486 << ArgIn->getSourceRange();
7487
7488 if (FirstOpKind == UO_AddrOf)
7489 AddressTaken = true;
7490 else if (Arg->getType()->isPointerType()) {
7491 // We cannot let pointers get dereferenced here, that is obviously not a
7492 // constant expression.
7493 assert(FirstOpKind == UO_Deref);
7494 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7495 << Arg->getSourceRange();
7496 }
7497 }
7498 } else {
7499 // See through any implicit casts we added to fix the type.
7500 Arg = Arg->IgnoreImpCasts();
7501
7502 // C++ [temp.arg.nontype]p1:
7503 //
7504 // A template-argument for a non-type, non-template
7505 // template-parameter shall be one of: [...]
7506 //
7507 // -- the address of an object or function with external
7508 // linkage, including function templates and function
7509 // template-ids but excluding non-static class members,
7510 // expressed as & id-expression where the & is optional if
7511 // the name refers to a function or array, or if the
7512 // corresponding template-parameter is a reference; or
7513
7514 // In C++98/03 mode, give an extension warning on any extra parentheses.
7515 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7516 bool ExtraParens = false;
7517 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7518 if (!Invalid && !ExtraParens) {
7519 S.Diag(Arg->getBeginLoc(),
7520 S.getLangOpts().CPlusPlus11
7521 ? diag::warn_cxx98_compat_template_arg_extra_parens
7522 : diag::ext_template_arg_extra_parens)
7523 << Arg->getSourceRange();
7524 ExtraParens = true;
7525 }
7526
7527 Arg = Parens->getSubExpr();
7528 }
7529
7530 while (SubstNonTypeTemplateParmExpr *subst =
7531 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7532 Arg = subst->getReplacement()->IgnoreImpCasts();
7533
7534 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7535 if (UnOp->getOpcode() == UO_AddrOf) {
7536 Arg = UnOp->getSubExpr();
7537 AddressTaken = true;
7538 AddrOpLoc = UnOp->getOperatorLoc();
7539 }
7540 }
7541
7542 while (SubstNonTypeTemplateParmExpr *subst =
7543 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7544 Arg = subst->getReplacement()->IgnoreImpCasts();
7545 }
7546
7547 ValueDecl *Entity = nullptr;
7548 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
7549 Entity = DRE->getDecl();
7550 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
7551 Entity = CUE->getGuidDecl();
7552
7553 // If our parameter has pointer type, check for a null template value.
7554 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
7555 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
7556 Entity)) {
7557 case NPV_NullPointer:
7558 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7559 SugaredConverted = TemplateArgument(ParamType,
7560 /*isNullPtr=*/true);
7561 CanonicalConverted =
7563 /*isNullPtr=*/true);
7564 return false;
7565
7566 case NPV_Error:
7567 return true;
7568
7569 case NPV_NotNullPointer:
7570 break;
7571 }
7572 }
7573
7574 // Stop checking the precise nature of the argument if it is value dependent,
7575 // it should be checked when instantiated.
7576 if (Arg->isValueDependent()) {
7577 SugaredConverted = TemplateArgument(ArgIn);
7578 CanonicalConverted =
7579 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7580 return false;
7581 }
7582
7583 if (!Entity) {
7584 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7585 << Arg->getSourceRange();
7587 return true;
7588 }
7589
7590 // Cannot refer to non-static data members
7591 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
7592 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
7593 << Entity << Arg->getSourceRange();
7595 return true;
7596 }
7597
7598 // Cannot refer to non-static member functions
7599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
7600 if (!Method->isStatic()) {
7601 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
7602 << Method << Arg->getSourceRange();
7604 return true;
7605 }
7606 }
7607
7608 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
7609 VarDecl *Var = dyn_cast<VarDecl>(Entity);
7610 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
7611
7612 // A non-type template argument must refer to an object or function.
7613 if (!Func && !Var && !Guid) {
7614 // We found something, but we don't know specifically what it is.
7615 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
7616 << Arg->getSourceRange();
7617 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
7618 return true;
7619 }
7620
7621 // Address / reference template args must have external linkage in C++98.
7622 if (Entity->getFormalLinkage() == Linkage::Internal) {
7623 S.Diag(Arg->getBeginLoc(),
7624 S.getLangOpts().CPlusPlus11
7625 ? diag::warn_cxx98_compat_template_arg_object_internal
7626 : diag::ext_template_arg_object_internal)
7627 << !Func << Entity << Arg->getSourceRange();
7628 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
7629 << !Func;
7630 } else if (!Entity->hasLinkage()) {
7631 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
7632 << !Func << Entity << Arg->getSourceRange();
7633 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
7634 << !Func;
7635 return true;
7636 }
7637
7638 if (Var) {
7639 // A value of reference type is not an object.
7640 if (Var->getType()->isReferenceType()) {
7641 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
7642 << Var->getType() << Arg->getSourceRange();
7644 return true;
7645 }
7646
7647 // A template argument must have static storage duration.
7648 if (Var->getTLSKind()) {
7649 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
7650 << Arg->getSourceRange();
7651 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
7652 return true;
7653 }
7654 }
7655
7656 if (AddressTaken && ParamType->isReferenceType()) {
7657 // If we originally had an address-of operator, but the
7658 // parameter has reference type, complain and (if things look
7659 // like they will work) drop the address-of operator.
7660 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
7661 ParamType.getNonReferenceType())) {
7662 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7663 << ParamType;
7665 return true;
7666 }
7667
7668 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7669 << ParamType
7670 << FixItHint::CreateRemoval(AddrOpLoc);
7672
7673 ArgType = Entity->getType();
7674 }
7675
7676 // If the template parameter has pointer type, either we must have taken the
7677 // address or the argument must decay to a pointer.
7678 if (!AddressTaken && ParamType->isPointerType()) {
7679 if (Func) {
7680 // Function-to-pointer decay.
7681 ArgType = S.Context.getPointerType(Func->getType());
7682 } else if (Entity->getType()->isArrayType()) {
7683 // Array-to-pointer decay.
7684 ArgType = S.Context.getArrayDecayedType(Entity->getType());
7685 } else {
7686 // If the template parameter has pointer type but the address of
7687 // this object was not taken, complain and (possibly) recover by
7688 // taking the address of the entity.
7689 ArgType = S.Context.getPointerType(Entity->getType());
7690 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
7691 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7692 << ParamType;
7694 return true;
7695 }
7696
7697 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7698 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7699
7701 }
7702 }
7703
7704 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7705 Arg, ArgType))
7706 return true;
7707
7708 // Create the template argument.
7709 SugaredConverted = TemplateArgument(Entity, ParamType);
7710 CanonicalConverted =
7711 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
7712 S.Context.getCanonicalType(ParamType));
7713 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7714 return false;
7715}
7716
7717/// Checks whether the given template argument is a pointer to
7718/// member constant according to C++ [temp.arg.nontype]p1.
7719static bool
7721 QualType ParamType, Expr *&ResultArg,
7722 TemplateArgument &SugaredConverted,
7723 TemplateArgument &CanonicalConverted) {
7724 bool Invalid = false;
7725
7726 Expr *Arg = ResultArg;
7727 bool ObjCLifetimeConversion;
7728
7729 // C++ [temp.arg.nontype]p1:
7730 //
7731 // A template-argument for a non-type, non-template
7732 // template-parameter shall be one of: [...]
7733 //
7734 // -- a pointer to member expressed as described in 5.3.1.
7735 DeclRefExpr *DRE = nullptr;
7736
7737 // In C++98/03 mode, give an extension warning on any extra parentheses.
7738 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7739 bool ExtraParens = false;
7740 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7741 if (!Invalid && !ExtraParens) {
7742 S.Diag(Arg->getBeginLoc(),
7743 S.getLangOpts().CPlusPlus11
7744 ? diag::warn_cxx98_compat_template_arg_extra_parens
7745 : diag::ext_template_arg_extra_parens)
7746 << Arg->getSourceRange();
7747 ExtraParens = true;
7748 }
7749
7750 Arg = Parens->getSubExpr();
7751 }
7752
7753 while (SubstNonTypeTemplateParmExpr *subst =
7754 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7755 Arg = subst->getReplacement()->IgnoreImpCasts();
7756
7757 // A pointer-to-member constant written &Class::member.
7758 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7759 if (UnOp->getOpcode() == UO_AddrOf) {
7760 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7761 if (DRE && !DRE->getQualifier())
7762 DRE = nullptr;
7763 }
7764 }
7765 // A constant of pointer-to-member type.
7766 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7767 ValueDecl *VD = DRE->getDecl();
7768 if (VD->getType()->isMemberPointerType()) {
7769 if (isa<NonTypeTemplateParmDecl>(VD)) {
7770 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7771 SugaredConverted = TemplateArgument(Arg);
7772 CanonicalConverted =
7773 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7774 } else {
7775 SugaredConverted = TemplateArgument(VD, ParamType);
7776 CanonicalConverted =
7777 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7778 S.Context.getCanonicalType(ParamType));
7779 }
7780 return Invalid;
7781 }
7782 }
7783
7784 DRE = nullptr;
7785 }
7786
7787 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7788
7789 // Check for a null pointer value.
7790 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7791 Entity)) {
7792 case NPV_Error:
7793 return true;
7794 case NPV_NullPointer:
7795 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7796 SugaredConverted = TemplateArgument(ParamType,
7797 /*isNullPtr*/ true);
7798 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7799 /*isNullPtr*/ true);
7800 return false;
7801 case NPV_NotNullPointer:
7802 break;
7803 }
7804
7805 if (S.IsQualificationConversion(ResultArg->getType(),
7806 ParamType.getNonReferenceType(), false,
7807 ObjCLifetimeConversion)) {
7808 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7809 ResultArg->getValueKind())
7810 .get();
7811 } else if (!S.Context.hasSameUnqualifiedType(
7812 ResultArg->getType(), ParamType.getNonReferenceType())) {
7813 // We can't perform this conversion.
7814 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7815 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7817 return true;
7818 }
7819
7820 if (!DRE)
7821 return S.Diag(Arg->getBeginLoc(),
7822 diag::err_template_arg_not_pointer_to_member_form)
7823 << Arg->getSourceRange();
7824
7825 if (isa<FieldDecl>(DRE->getDecl()) ||
7826 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7827 isa<CXXMethodDecl>(DRE->getDecl())) {
7828 assert((isa<FieldDecl>(DRE->getDecl()) ||
7829 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7830 cast<CXXMethodDecl>(DRE->getDecl())
7831 ->isImplicitObjectMemberFunction()) &&
7832 "Only non-static member pointers can make it here");
7833
7834 // Okay: this is the address of a non-static member, and therefore
7835 // a member pointer constant.
7836 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7837 SugaredConverted = TemplateArgument(Arg);
7838 CanonicalConverted =
7839 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7840 } else {
7841 ValueDecl *D = DRE->getDecl();
7842 SugaredConverted = TemplateArgument(D, ParamType);
7843 CanonicalConverted =
7844 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
7845 S.Context.getCanonicalType(ParamType));
7846 }
7847 return Invalid;
7848 }
7849
7850 // We found something else, but we don't know specifically what it is.
7851 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7852 << Arg->getSourceRange();
7853 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7854 return true;
7855}
7856
7857/// Check a template argument against its corresponding
7858/// non-type template parameter.
7859///
7860/// This routine implements the semantics of C++ [temp.arg.nontype].
7861/// If an error occurred, it returns ExprError(); otherwise, it
7862/// returns the converted template argument. \p ParamType is the
7863/// type of the non-type template parameter after it has been instantiated.
7865 QualType ParamType, Expr *Arg,
7866 TemplateArgument &SugaredConverted,
7867 TemplateArgument &CanonicalConverted,
7869 SourceLocation StartLoc = Arg->getBeginLoc();
7870
7871 // If the parameter type somehow involves auto, deduce the type now.
7872 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7873 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7874 // During template argument deduction, we allow 'decltype(auto)' to
7875 // match an arbitrary dependent argument.
7876 // FIXME: The language rules don't say what happens in this case.
7877 // FIXME: We get an opaque dependent type out of decltype(auto) if the
7878 // expression is merely instantiation-dependent; is this enough?
7879 if (Arg->isTypeDependent()) {
7880 auto *AT = dyn_cast<AutoType>(DeducedT);
7881 if (AT && AT->isDecltypeAuto()) {
7882 SugaredConverted = TemplateArgument(Arg);
7883 CanonicalConverted = TemplateArgument(
7884 Context.getCanonicalTemplateArgument(SugaredConverted));
7885 return Arg;
7886 }
7887 }
7888
7889 // When checking a deduced template argument, deduce from its type even if
7890 // the type is dependent, in order to check the types of non-type template
7891 // arguments line up properly in partial ordering.
7892 Expr *DeductionArg = Arg;
7893 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
7894 DeductionArg = PE->getPattern();
7895 TypeSourceInfo *TSI =
7896 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7897 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
7898 InitializedEntity Entity =
7901 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7902 Expr *Inits[1] = {DeductionArg};
7903 ParamType =
7904 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7905 if (ParamType.isNull())
7906 return ExprError();
7907 } else {
7908 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7909 Param->getDepth() + 1);
7910 ParamType = QualType();
7912 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7913 /*DependentDeduction=*/true,
7914 // We do not check constraints right now because the
7915 // immediately-declared constraint of the auto type is
7916 // also an associated constraint, and will be checked
7917 // along with the other associated constraints after
7918 // checking the template argument list.
7919 /*IgnoreConstraints=*/true);
7921 if (ParamType.isNull())
7922 return ExprError();
7924 Diag(Arg->getExprLoc(),
7925 diag::err_non_type_template_parm_type_deduction_failure)
7926 << Param->getDeclName() << Param->getType() << Arg->getType()
7927 << Arg->getSourceRange();
7929 return ExprError();
7930 }
7931 }
7932 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7933 // an error. The error message normally references the parameter
7934 // declaration, but here we'll pass the argument location because that's
7935 // where the parameter type is deduced.
7936 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7937 if (ParamType.isNull()) {
7939 return ExprError();
7940 }
7941 }
7942
7943 // We should have already dropped all cv-qualifiers by now.
7944 assert(!ParamType.hasQualifiers() &&
7945 "non-type template parameter type cannot be qualified");
7946
7947 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7948 if (CTAK == CTAK_Deduced &&
7949 (ParamType->isReferenceType()
7951 Arg->getType())
7952 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
7953 // FIXME: If either type is dependent, we skip the check. This isn't
7954 // correct, since during deduction we're supposed to have replaced each
7955 // template parameter with some unique (non-dependent) placeholder.
7956 // FIXME: If the argument type contains 'auto', we carry on and fail the
7957 // type check in order to force specific types to be more specialized than
7958 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
7959 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
7960 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
7961 !Arg->getType()->getContainedDeducedType()) {
7962 SugaredConverted = TemplateArgument(Arg);
7963 CanonicalConverted = TemplateArgument(
7964 Context.getCanonicalTemplateArgument(SugaredConverted));
7965 return Arg;
7966 }
7967 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7968 // we should actually be checking the type of the template argument in P,
7969 // not the type of the template argument deduced from A, against the
7970 // template parameter type.
7971 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7972 << Arg->getType()
7973 << ParamType.getUnqualifiedType();
7975 return ExprError();
7976 }
7977
7978 // If either the parameter has a dependent type or the argument is
7979 // type-dependent, there's nothing we can check now.
7980 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
7981 // Force the argument to the type of the parameter to maintain invariants.
7982 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
7983 if (PE)
7984 Arg = PE->getPattern();
7986 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7987 ParamType->isLValueReferenceType() ? VK_LValue
7988 : ParamType->isRValueReferenceType() ? VK_XValue
7989 : VK_PRValue);
7990 if (E.isInvalid())
7991 return ExprError();
7992 if (PE) {
7993 // Recreate a pack expansion if we unwrapped one.
7994 E = new (Context)
7995 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
7996 PE->getNumExpansions());
7997 }
7998 SugaredConverted = TemplateArgument(E.get());
7999 CanonicalConverted = TemplateArgument(
8000 Context.getCanonicalTemplateArgument(SugaredConverted));
8001 return E;
8002 }
8003
8004 QualType CanonParamType = Context.getCanonicalType(ParamType);
8005 // Avoid making a copy when initializing a template parameter of class type
8006 // from a template parameter object of the same type. This is going beyond
8007 // the standard, but is required for soundness: in
8008 // template<A a> struct X { X *p; X<a> *q; };
8009 // ... we need p and q to have the same type.
8010 //
8011 // Similarly, don't inject a call to a copy constructor when initializing
8012 // from a template parameter of the same type.
8013 Expr *InnerArg = Arg->IgnoreParenImpCasts();
8014 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
8015 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
8016 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
8017 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
8018
8019 SugaredConverted = TemplateArgument(TPO, ParamType);
8020 CanonicalConverted =
8021 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
8022 return Arg;
8023 }
8024 if (isa<NonTypeTemplateParmDecl>(ND)) {
8025 SugaredConverted = TemplateArgument(Arg);
8026 CanonicalConverted =
8027 Context.getCanonicalTemplateArgument(SugaredConverted);
8028 return Arg;
8029 }
8030 }
8031
8032 // The initialization of the parameter from the argument is
8033 // a constant-evaluated context.
8036
8037 bool IsConvertedConstantExpression = true;
8038 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
8040 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
8041 Expr *Inits[1] = {Arg};
8042 InitializedEntity Entity =
8044 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
8045 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
8046 if (Result.isInvalid() || !Result.get())
8047 return ExprError();
8049 if (Result.isInvalid() || !Result.get())
8050 return ExprError();
8051 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
8052 /*DiscardedValue=*/false,
8053 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
8054 .get();
8055 IsConvertedConstantExpression = false;
8056 }
8057
8058 if (getLangOpts().CPlusPlus17) {
8059 // C++17 [temp.arg.nontype]p1:
8060 // A template-argument for a non-type template parameter shall be
8061 // a converted constant expression of the type of the template-parameter.
8062 APValue Value;
8063 ExprResult ArgResult;
8064 if (IsConvertedConstantExpression) {
8065 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
8066 CCEK_TemplateArg, Param);
8067 if (ArgResult.isInvalid())
8068 return ExprError();
8069 } else {
8070 ArgResult = Arg;
8071 }
8072
8073 // For a value-dependent argument, CheckConvertedConstantExpression is
8074 // permitted (and expected) to be unable to determine a value.
8075 if (ArgResult.get()->isValueDependent()) {
8076 SugaredConverted = TemplateArgument(ArgResult.get());
8077 CanonicalConverted =
8078 Context.getCanonicalTemplateArgument(SugaredConverted);
8079 return ArgResult;
8080 }
8081
8082 APValue PreNarrowingValue;
8084 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
8085 false, PreNarrowingValue);
8086 if (ArgResult.isInvalid())
8087 return ExprError();
8088
8089 if (Value.isLValue()) {
8090 APValue::LValueBase Base = Value.getLValueBase();
8091 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
8092 // For a non-type template-parameter of pointer or reference type,
8093 // the value of the constant expression shall not refer to
8094 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
8095 ParamType->isNullPtrType());
8096 // -- a temporary object
8097 // -- a string literal
8098 // -- the result of a typeid expression, or
8099 // -- a predefined __func__ variable
8100 if (Base &&
8101 (!VD ||
8102 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
8103 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
8104 << Arg->getSourceRange();
8105 return ExprError();
8106 }
8107
8108 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
8109 VD->getType()->isArrayType() &&
8110 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
8111 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
8112 SugaredConverted = TemplateArgument(VD, ParamType);
8113 CanonicalConverted = TemplateArgument(
8114 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
8115 return ArgResult.get();
8116 }
8117
8118 // -- a subobject [until C++20]
8119 if (!getLangOpts().CPlusPlus20) {
8120 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
8121 Value.isLValueOnePastTheEnd()) {
8122 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
8123 << Value.getAsString(Context, ParamType);
8124 return ExprError();
8125 }
8126 assert((VD || !ParamType->isReferenceType()) &&
8127 "null reference should not be a constant expression");
8128 assert((!VD || !ParamType->isNullPtrType()) &&
8129 "non-null value of type nullptr_t?");
8130 }
8131 }
8132
8133 if (Value.isAddrLabelDiff())
8134 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
8135
8136 SugaredConverted = TemplateArgument(Context, ParamType, Value);
8137 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
8138 return ArgResult.get();
8139 }
8140
8141 // C++ [temp.arg.nontype]p5:
8142 // The following conversions are performed on each expression used
8143 // as a non-type template-argument. If a non-type
8144 // template-argument cannot be converted to the type of the
8145 // corresponding template-parameter then the program is
8146 // ill-formed.
8147 if (ParamType->isIntegralOrEnumerationType()) {
8148 // C++11:
8149 // -- for a non-type template-parameter of integral or
8150 // enumeration type, conversions permitted in a converted
8151 // constant expression are applied.
8152 //
8153 // C++98:
8154 // -- for a non-type template-parameter of integral or
8155 // enumeration type, integral promotions (4.5) and integral
8156 // conversions (4.7) are applied.
8157
8158 if (getLangOpts().CPlusPlus11) {
8159 // C++ [temp.arg.nontype]p1:
8160 // A template-argument for a non-type, non-template template-parameter
8161 // shall be one of:
8162 //
8163 // -- for a non-type template-parameter of integral or enumeration
8164 // type, a converted constant expression of the type of the
8165 // template-parameter; or
8166 llvm::APSInt Value;
8167 ExprResult ArgResult =
8170 if (ArgResult.isInvalid())
8171 return ExprError();
8172
8173 // We can't check arbitrary value-dependent arguments.
8174 if (ArgResult.get()->isValueDependent()) {
8175 SugaredConverted = TemplateArgument(ArgResult.get());
8176 CanonicalConverted =
8177 Context.getCanonicalTemplateArgument(SugaredConverted);
8178 return ArgResult;
8179 }
8180
8181 // Widen the argument value to sizeof(parameter type). This is almost
8182 // always a no-op, except when the parameter type is bool. In
8183 // that case, this may extend the argument from 1 bit to 8 bits.
8184 QualType IntegerType = ParamType;
8185 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
8186 IntegerType = Enum->getDecl()->getIntegerType();
8187 Value = Value.extOrTrunc(IntegerType->isBitIntType()
8188 ? Context.getIntWidth(IntegerType)
8189 : Context.getTypeSize(IntegerType));
8190
8191 SugaredConverted = TemplateArgument(Context, Value, ParamType);
8192 CanonicalConverted =
8194 return ArgResult;
8195 }
8196
8197 ExprResult ArgResult = DefaultLvalueConversion(Arg);
8198 if (ArgResult.isInvalid())
8199 return ExprError();
8200 Arg = ArgResult.get();
8201
8202 QualType ArgType = Arg->getType();
8203
8204 // C++ [temp.arg.nontype]p1:
8205 // A template-argument for a non-type, non-template
8206 // template-parameter shall be one of:
8207 //
8208 // -- an integral constant-expression of integral or enumeration
8209 // type; or
8210 // -- the name of a non-type template-parameter; or
8211 llvm::APSInt Value;
8212 if (!ArgType->isIntegralOrEnumerationType()) {
8213 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
8214 << ArgType << Arg->getSourceRange();
8216 return ExprError();
8217 } else if (!Arg->isValueDependent()) {
8218 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
8219 QualType T;
8220
8221 public:
8222 TmplArgICEDiagnoser(QualType T) : T(T) { }
8223
8224 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
8225 SourceLocation Loc) override {
8226 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
8227 }
8228 } Diagnoser(ArgType);
8229
8230 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
8231 if (!Arg)
8232 return ExprError();
8233 }
8234
8235 // From here on out, all we care about is the unqualified form
8236 // of the argument type.
8237 ArgType = ArgType.getUnqualifiedType();
8238
8239 // Try to convert the argument to the parameter's type.
8240 if (Context.hasSameType(ParamType, ArgType)) {
8241 // Okay: no conversion necessary
8242 } else if (ParamType->isBooleanType()) {
8243 // This is an integral-to-boolean conversion.
8244 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
8245 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
8246 !ParamType->isEnumeralType()) {
8247 // This is an integral promotion or conversion.
8248 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
8249 } else {
8250 // We can't perform this conversion.
8251 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
8252 << Arg->getType() << ParamType << Arg->getSourceRange();
8254 return ExprError();
8255 }
8256
8257 // Add the value of this argument to the list of converted
8258 // arguments. We use the bitwidth and signedness of the template
8259 // parameter.
8260 if (Arg->isValueDependent()) {
8261 // The argument is value-dependent. Create a new
8262 // TemplateArgument with the converted expression.
8263 SugaredConverted = TemplateArgument(Arg);
8264 CanonicalConverted =
8265 Context.getCanonicalTemplateArgument(SugaredConverted);
8266 return Arg;
8267 }
8268
8269 QualType IntegerType = ParamType;
8270 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
8271 IntegerType = Enum->getDecl()->getIntegerType();
8272 }
8273
8274 if (ParamType->isBooleanType()) {
8275 // Value must be zero or one.
8276 Value = Value != 0;
8277 unsigned AllowedBits = Context.getTypeSize(IntegerType);
8278 if (Value.getBitWidth() != AllowedBits)
8279 Value = Value.extOrTrunc(AllowedBits);
8280 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
8281 } else {
8282 llvm::APSInt OldValue = Value;
8283
8284 // Coerce the template argument's value to the value it will have
8285 // based on the template parameter's type.
8286 unsigned AllowedBits = IntegerType->isBitIntType()
8287 ? Context.getIntWidth(IntegerType)
8288 : Context.getTypeSize(IntegerType);
8289 if (Value.getBitWidth() != AllowedBits)
8290 Value = Value.extOrTrunc(AllowedBits);
8291 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
8292
8293 // Complain if an unsigned parameter received a negative value.
8294 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
8295 (OldValue.isSigned() && OldValue.isNegative())) {
8296 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
8297 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
8298 << Arg->getSourceRange();
8300 }
8301
8302 // Complain if we overflowed the template parameter's type.
8303 unsigned RequiredBits;
8304 if (IntegerType->isUnsignedIntegerOrEnumerationType())
8305 RequiredBits = OldValue.getActiveBits();
8306 else if (OldValue.isUnsigned())
8307 RequiredBits = OldValue.getActiveBits() + 1;
8308 else
8309 RequiredBits = OldValue.getSignificantBits();
8310 if (RequiredBits > AllowedBits) {
8311 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
8312 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
8313 << Arg->getSourceRange();
8315 }
8316 }
8317
8318 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
8319 SugaredConverted = TemplateArgument(Context, Value, T);
8320 CanonicalConverted =
8322 return Arg;
8323 }
8324
8325 QualType ArgType = Arg->getType();
8326 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
8327
8328 // Handle pointer-to-function, reference-to-function, and
8329 // pointer-to-member-function all in (roughly) the same way.
8330 if (// -- For a non-type template-parameter of type pointer to
8331 // function, only the function-to-pointer conversion (4.3) is
8332 // applied. If the template-argument represents a set of
8333 // overloaded functions (or a pointer to such), the matching
8334 // function is selected from the set (13.4).
8335 (ParamType->isPointerType() &&
8336 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
8337 // -- For a non-type template-parameter of type reference to
8338 // function, no conversions apply. If the template-argument
8339 // represents a set of overloaded functions, the matching
8340 // function is selected from the set (13.4).
8341 (ParamType->isReferenceType() &&
8342 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
8343 // -- For a non-type template-parameter of type pointer to
8344 // member function, no conversions apply. If the
8345 // template-argument represents a set of overloaded member
8346 // functions, the matching member function is selected from
8347 // the set (13.4).
8348 (ParamType->isMemberPointerType() &&
8349 ParamType->castAs<MemberPointerType>()->getPointeeType()
8350 ->isFunctionType())) {
8351
8352 if (Arg->getType() == Context.OverloadTy) {
8353 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
8354 true,
8355 FoundResult)) {
8356 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
8357 return ExprError();
8358
8359 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
8360 if (Res.isInvalid())
8361 return ExprError();
8362 Arg = Res.get();
8363 ArgType = Arg->getType();
8364 } else
8365 return ExprError();
8366 }
8367
8368 if (!ParamType->isMemberPointerType()) {
8370 *this, Param, ParamType, Arg, SugaredConverted,
8371 CanonicalConverted))
8372 return ExprError();
8373 return Arg;
8374 }
8375
8377 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8378 return ExprError();
8379 return Arg;
8380 }
8381
8382 if (ParamType->isPointerType()) {
8383 // -- for a non-type template-parameter of type pointer to
8384 // object, qualification conversions (4.4) and the
8385 // array-to-pointer conversion (4.2) are applied.
8386 // C++0x also allows a value of std::nullptr_t.
8387 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
8388 "Only object pointers allowed here");
8389
8391 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8392 return ExprError();
8393 return Arg;
8394 }
8395
8396 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
8397 // -- For a non-type template-parameter of type reference to
8398 // object, no conversions apply. The type referred to by the
8399 // reference may be more cv-qualified than the (otherwise
8400 // identical) type of the template-argument. The
8401 // template-parameter is bound directly to the
8402 // template-argument, which must be an lvalue.
8403 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
8404 "Only object references allowed here");
8405
8406 if (Arg->getType() == Context.OverloadTy) {
8408 ParamRefType->getPointeeType(),
8409 true,
8410 FoundResult)) {
8411 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
8412 return ExprError();
8413 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
8414 if (Res.isInvalid())
8415 return ExprError();
8416 Arg = Res.get();
8417 ArgType = Arg->getType();
8418 } else
8419 return ExprError();
8420 }
8421
8423 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8424 return ExprError();
8425 return Arg;
8426 }
8427
8428 // Deal with parameters of type std::nullptr_t.
8429 if (ParamType->isNullPtrType()) {
8430 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
8431 SugaredConverted = TemplateArgument(Arg);
8432 CanonicalConverted =
8433 Context.getCanonicalTemplateArgument(SugaredConverted);
8434 return Arg;
8435 }
8436
8437 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
8438 case NPV_NotNullPointer:
8439 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
8440 << Arg->getType() << ParamType;
8442 return ExprError();
8443
8444 case NPV_Error:
8445 return ExprError();
8446
8447 case NPV_NullPointer:
8448 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
8449 SugaredConverted = TemplateArgument(ParamType,
8450 /*isNullPtr=*/true);
8451 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
8452 /*isNullPtr=*/true);
8453 return Arg;
8454 }
8455 }
8456
8457 // -- For a non-type template-parameter of type pointer to data
8458 // member, qualification conversions (4.4) are applied.
8459 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
8460
8462 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8463 return ExprError();
8464 return Arg;
8465}
8466
8470
8471/// Check a template argument against its corresponding
8472/// template template parameter.
8473///
8474/// This routine implements the semantics of C++ [temp.arg.template].
8475/// It returns true if an error occurred, and false otherwise.
8477 TemplateParameterList *Params,
8479 bool IsDeduced) {
8481 TemplateDecl *Template = Name.getAsTemplateDecl();
8482 if (!Template) {
8483 // Any dependent template name is fine.
8484 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
8485 return false;
8486 }
8487
8488 if (Template->isInvalidDecl())
8489 return true;
8490
8491 // C++0x [temp.arg.template]p1:
8492 // A template-argument for a template template-parameter shall be
8493 // the name of a class template or an alias template, expressed as an
8494 // id-expression. When the template-argument names a class template, only
8495 // primary class templates are considered when matching the
8496 // template template argument with the corresponding parameter;
8497 // partial specializations are not considered even if their
8498 // parameter lists match that of the template template parameter.
8499 //
8500 // Note that we also allow template template parameters here, which
8501 // will happen when we are dealing with, e.g., class template
8502 // partial specializations.
8503 if (!isa<ClassTemplateDecl>(Template) &&
8504 !isa<TemplateTemplateParmDecl>(Template) &&
8505 !isa<TypeAliasTemplateDecl>(Template) &&
8506 !isa<BuiltinTemplateDecl>(Template)) {
8507 assert(isa<FunctionTemplateDecl>(Template) &&
8508 "Only function templates are possible here");
8509 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
8510 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
8511 << Template;
8512 }
8513
8514 // C++1z [temp.arg.template]p3: (DR 150)
8515 // A template-argument matches a template template-parameter P when P
8516 // is at least as specialized as the template-argument A.
8517 if (getLangOpts().RelaxedTemplateTemplateArgs) {
8518 // Quick check for the common case:
8519 // If P contains a parameter pack, then A [...] matches P if each of A's
8520 // template parameters matches the corresponding template parameter in
8521 // the template-parameter-list of P.
8523 Template->getTemplateParameters(), Params, false,
8525 // If the argument has no associated constraints, then the parameter is
8526 // definitely at least as specialized as the argument.
8527 // Otherwise - we need a more thorough check.
8528 !Template->hasAssociatedConstraints())
8529 return false;
8530
8532 Params, Template, Arg.getLocation(), IsDeduced)) {
8533 // P2113
8534 // C++20[temp.func.order]p2
8535 // [...] If both deductions succeed, the partial ordering selects the
8536 // more constrained template (if one exists) as determined below.
8537 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
8538 Params->getAssociatedConstraints(ParamsAC);
8539 // C++2a[temp.arg.template]p3
8540 // [...] In this comparison, if P is unconstrained, the constraints on A
8541 // are not considered.
8542 if (ParamsAC.empty())
8543 return false;
8544
8545 Template->getAssociatedConstraints(TemplateAC);
8546
8547 bool IsParamAtLeastAsConstrained;
8548 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
8549 IsParamAtLeastAsConstrained))
8550 return true;
8551 if (!IsParamAtLeastAsConstrained) {
8552 Diag(Arg.getLocation(),
8553 diag::err_template_template_parameter_not_at_least_as_constrained)
8554 << Template << Param << Arg.getSourceRange();
8555 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
8556 Diag(Template->getLocation(), diag::note_entity_declared_at)
8557 << Template;
8558 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
8559 TemplateAC);
8560 return true;
8561 }
8562 return false;
8563 }
8564 // FIXME: Produce better diagnostics for deduction failures.
8565 }
8566
8568 Params,
8569 true,
8571 Arg.getLocation());
8572}
8573
8575 unsigned HereDiagID,
8576 unsigned ExternalDiagID) {
8577 if (Decl.getLocation().isValid())
8578 return S.Diag(Decl.getLocation(), HereDiagID);
8579
8580 SmallString<128> Str;
8581 llvm::raw_svector_ostream Out(Str);
8583 PP.TerseOutput = 1;
8584 Decl.print(Out, PP);
8585 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
8586}
8587
8589 std::optional<SourceRange> ParamRange) {
8591 noteLocation(*this, Decl, diag::note_template_decl_here,
8592 diag::note_template_decl_external);
8593 if (ParamRange && ParamRange->isValid()) {
8594 assert(Decl.getLocation().isValid() &&
8595 "Parameter range has location when Decl does not");
8596 DB << *ParamRange;
8597 }
8598}
8599
8601 noteLocation(*this, Decl, diag::note_template_param_here,
8602 diag::note_template_param_external);
8603}
8604
8605/// Given a non-type template argument that refers to a
8606/// declaration and the type of its corresponding non-type template
8607/// parameter, produce an expression that properly refers to that
8608/// declaration.
8610 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
8612 // C++ [temp.param]p8:
8613 //
8614 // A non-type template-parameter of type "array of T" or
8615 // "function returning T" is adjusted to be of type "pointer to
8616 // T" or "pointer to function returning T", respectively.
8617 if (ParamType->isArrayType())
8618 ParamType = Context.getArrayDecayedType(ParamType);
8619 else if (ParamType->isFunctionType())
8620 ParamType = Context.getPointerType(ParamType);
8621
8622 // For a NULL non-type template argument, return nullptr casted to the
8623 // parameter's type.
8624 if (Arg.getKind() == TemplateArgument::NullPtr) {
8625 return ImpCastExprToType(
8627 ParamType,
8628 ParamType->getAs<MemberPointerType>()
8629 ? CK_NullToMemberPointer
8630 : CK_NullToPointer);
8631 }
8632 assert(Arg.getKind() == TemplateArgument::Declaration &&
8633 "Only declaration template arguments permitted here");
8634
8635 ValueDecl *VD = Arg.getAsDecl();
8636
8637 CXXScopeSpec SS;
8638 if (ParamType->isMemberPointerType()) {
8639 // If this is a pointer to member, we need to use a qualified name to
8640 // form a suitable pointer-to-member constant.
8641 assert(VD->getDeclContext()->isRecord() &&
8642 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8643 isa<IndirectFieldDecl>(VD)));
8644 QualType ClassType
8645 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
8646 NestedNameSpecifier *Qualifier
8647 = NestedNameSpecifier::Create(Context, nullptr, false,
8648 ClassType.getTypePtr());
8649 SS.MakeTrivial(Context, Qualifier, Loc);
8650 }
8651
8653 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8654 if (RefExpr.isInvalid())
8655 return ExprError();
8656
8657 // For a pointer, the argument declaration is the pointee. Take its address.
8658 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8659 if (ParamType->isPointerType() && !ElemT.isNull() &&
8660 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8661 // Decay an array argument if we want a pointer to its first element.
8662 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8663 if (RefExpr.isInvalid())
8664 return ExprError();
8665 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8666 // For any other pointer, take the address (or form a pointer-to-member).
8667 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8668 if (RefExpr.isInvalid())
8669 return ExprError();
8670 } else if (ParamType->isRecordType()) {
8671 assert(isa<TemplateParamObjectDecl>(VD) &&
8672 "arg for class template param not a template parameter object");
8673 // No conversions apply in this case.
8674 return RefExpr;
8675 } else {
8676 assert(ParamType->isReferenceType() &&
8677 "unexpected type for decl template argument");
8678 if (NonTypeTemplateParmDecl *NTTP =
8679 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
8680 QualType TemplateParamType = NTTP->getType();
8681 const AutoType *AT = TemplateParamType->getAs<AutoType>();
8682 if (AT && AT->isDecltypeAuto()) {
8684 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
8685 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
8686 /*PackIndex=*/std::nullopt,
8687 /*RefParam=*/true);
8688 }
8689 }
8690 }
8691
8692 // At this point we should have the right value category.
8693 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8694 "value kind mismatch for non-type template argument");
8695
8696 // The type of the template parameter can differ from the type of the
8697 // argument in various ways; convert it now if necessary.
8698 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8699 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8700 CastKind CK;
8701 QualType Ignored;
8702 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8703 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
8704 CK = CK_NoOp;
8705 } else if (ParamType->isVoidPointerType() &&
8706 RefExpr.get()->getType()->isPointerType()) {
8707 CK = CK_BitCast;
8708 } else {
8709 // FIXME: Pointers to members can need conversion derived-to-base or
8710 // base-to-derived conversions. We currently don't retain enough
8711 // information to convert properly (we need to track a cast path or
8712 // subobject number in the template argument).
8713 llvm_unreachable(
8714 "unexpected conversion required for non-type template argument");
8715 }
8716 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8717 RefExpr.get()->getValueKind());
8718 }
8719
8720 return RefExpr;
8721}
8722
8723/// Construct a new expression that refers to the given
8724/// integral template argument with the given source-location
8725/// information.
8726///
8727/// This routine takes care of the mapping from an integral template
8728/// argument (which may have any integral type) to the appropriate
8729/// literal value.
8731 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8732 assert(OrigT->isIntegralOrEnumerationType());
8733
8734 // If this is an enum type that we're instantiating, we need to use an integer
8735 // type the same size as the enumerator. We don't want to build an
8736 // IntegerLiteral with enum type. The integer type of an enum type can be of
8737 // any integral type with C++11 enum classes, make sure we create the right
8738 // type of literal for it.
8739 QualType T = OrigT;
8740 if (const EnumType *ET = OrigT->getAs<EnumType>())
8741 T = ET->getDecl()->getIntegerType();
8742
8743 Expr *E;
8744 if (T->isAnyCharacterType()) {
8746 if (T->isWideCharType())
8748 else if (T->isChar8Type() && S.getLangOpts().Char8)
8750 else if (T->isChar16Type())
8752 else if (T->isChar32Type())
8754 else
8756
8757 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8758 } else if (T->isBooleanType()) {
8759 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8760 } else {
8761 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8762 }
8763
8764 if (OrigT->isEnumeralType()) {
8765 // FIXME: This is a hack. We need a better way to handle substituted
8766 // non-type template parameters.
8767 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8768 nullptr, S.CurFPFeatureOverrides(),
8770 Loc, Loc);
8771 }
8772
8773 return E;
8774}
8775
8777 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8778 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8779 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8780 ILE->setType(T);
8781 return ILE;
8782 };
8783
8784 switch (Val.getKind()) {
8786 // This cannot occur in a template argument at all.
8787 case APValue::Array:
8788 case APValue::Struct:
8789 case APValue::Union:
8790 // These can only occur within a template parameter object, which is
8791 // represented as a TemplateArgument::Declaration.
8792 llvm_unreachable("unexpected template argument value");
8793
8794 case APValue::Int:
8796 Loc);
8797
8798 case APValue::Float:
8799 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8800 T, Loc);
8801
8804 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8805 Val.getFixedPoint().getScale());
8806
8807 case APValue::ComplexInt: {
8808 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8810 S, ElemT, Val.getComplexIntReal(), Loc),
8812 S, ElemT, Val.getComplexIntImag(), Loc)});
8813 }
8814
8815 case APValue::ComplexFloat: {
8816 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8817 return MakeInitList(
8819 ElemT, Loc),
8821 ElemT, Loc)});
8822 }
8823
8824 case APValue::Vector: {
8825 QualType ElemT = T->castAs<VectorType>()->getElementType();
8827 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8829 S, ElemT, Val.getVectorElt(I), Loc));
8830 return MakeInitList(Elts);
8831 }
8832
8833 case APValue::None:
8835 llvm_unreachable("Unexpected APValue kind.");
8836 case APValue::LValue:
8838 // There isn't necessarily a valid equivalent source-level syntax for
8839 // these; in particular, a naive lowering might violate access control.
8840 // So for now we lower to a ConstantExpr holding the value, wrapped around
8841 // an OpaqueValueExpr.
8842 // FIXME: We should have a better representation for this.
8844 if (T->isReferenceType()) {
8845 T = T->getPointeeType();
8846 VK = VK_LValue;
8847 }
8848 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8849 return ConstantExpr::Create(S.Context, OVE, Val);
8850 }
8851 llvm_unreachable("Unhandled APValue::ValueKind enum");
8852}
8853
8857 switch (Arg.getKind()) {
8863 llvm_unreachable("not a non-type template argument");
8864
8866 return Arg.getAsExpr();
8867
8872
8875 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8876
8879 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8880 }
8881 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8882}
8883
8884/// Match two template parameters within template parameter lists.
8886 Sema &S, NamedDecl *New,
8887 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8888 const NamedDecl *OldInstFrom, bool Complain,
8890 // Check the actual kind (type, non-type, template).
8891 if (Old->getKind() != New->getKind()) {
8892 if (Complain) {
8893 unsigned NextDiag = diag::err_template_param_different_kind;
8894 if (TemplateArgLoc.isValid()) {
8895 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8896 NextDiag = diag::note_template_param_different_kind;
8897 }
8898 S.Diag(New->getLocation(), NextDiag)
8899 << (Kind != Sema::TPL_TemplateMatch);
8900 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8901 << (Kind != Sema::TPL_TemplateMatch);
8902 }
8903
8904 return false;
8905 }
8906
8907 // Check that both are parameter packs or neither are parameter packs.
8908 // However, if we are matching a template template argument to a
8909 // template template parameter, the template template parameter can have
8910 // a parameter pack where the template template argument does not.
8911 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
8913 Old->isTemplateParameterPack())) {
8914 if (Complain) {
8915 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8916 if (TemplateArgLoc.isValid()) {
8917 S.Diag(TemplateArgLoc,
8918 diag::err_template_arg_template_params_mismatch);
8919 NextDiag = diag::note_template_parameter_pack_non_pack;
8920 }
8921
8922 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8923 : isa<NonTypeTemplateParmDecl>(New)? 1
8924 : 2;
8925 S.Diag(New->getLocation(), NextDiag)
8926 << ParamKind << New->isParameterPack();
8927 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8928 << ParamKind << Old->isParameterPack();
8929 }
8930
8931 return false;
8932 }
8933
8934 // For non-type template parameters, check the type of the parameter.
8935 if (NonTypeTemplateParmDecl *OldNTTP
8936 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8937 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
8938
8939 // If we are matching a template template argument to a template
8940 // template parameter and one of the non-type template parameter types
8941 // is dependent, then we must wait until template instantiation time
8942 // to actually compare the arguments.
8944 (!OldNTTP->getType()->isDependentType() &&
8945 !NewNTTP->getType()->isDependentType())) {
8946 // C++20 [temp.over.link]p6:
8947 // Two [non-type] template-parameters are equivalent [if] they have
8948 // equivalent types ignoring the use of type-constraints for
8949 // placeholder types
8950 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8951 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8952 if (!S.Context.hasSameType(OldType, NewType)) {
8953 if (Complain) {
8954 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8955 if (TemplateArgLoc.isValid()) {
8956 S.Diag(TemplateArgLoc,
8957 diag::err_template_arg_template_params_mismatch);
8958 NextDiag = diag::note_template_nontype_parm_different_type;
8959 }
8960 S.Diag(NewNTTP->getLocation(), NextDiag)
8961 << NewNTTP->getType()
8962 << (Kind != Sema::TPL_TemplateMatch);
8963 S.Diag(OldNTTP->getLocation(),
8964 diag::note_template_nontype_parm_prev_declaration)
8965 << OldNTTP->getType();
8966 }
8967
8968 return false;
8969 }
8970 }
8971 }
8972 // For template template parameters, check the template parameter types.
8973 // The template parameter lists of template template
8974 // parameters must agree.
8975 else if (TemplateTemplateParmDecl *OldTTP =
8976 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8977 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
8979 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8980 OldTTP->getTemplateParameters(), Complain,
8983 : Kind),
8984 TemplateArgLoc))
8985 return false;
8986 }
8987
8990 !isa<TemplateTemplateParmDecl>(Old)) {
8991 const Expr *NewC = nullptr, *OldC = nullptr;
8992
8993 if (isa<TemplateTypeParmDecl>(New)) {
8994 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8995 NewC = TC->getImmediatelyDeclaredConstraint();
8996 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8997 OldC = TC->getImmediatelyDeclaredConstraint();
8998 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8999 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
9000 ->getPlaceholderTypeConstraint())
9001 NewC = E;
9002 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
9003 ->getPlaceholderTypeConstraint())
9004 OldC = E;
9005 } else
9006 llvm_unreachable("unexpected template parameter type");
9007
9008 auto Diagnose = [&] {
9009 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
9010 diag::err_template_different_type_constraint);
9011 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
9012 diag::note_template_prev_declaration) << /*declaration*/0;
9013 };
9014
9015 if (!NewC != !OldC) {
9016 if (Complain)
9017 Diagnose();
9018 return false;
9019 }
9020
9021 if (NewC) {
9022 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
9023 NewC)) {
9024 if (Complain)
9025 Diagnose();
9026 return false;
9027 }
9028 }
9029 }
9030
9031 return true;
9032}
9033
9034/// Diagnose a known arity mismatch when comparing template argument
9035/// lists.
9036static
9041 SourceLocation TemplateArgLoc) {
9042 unsigned NextDiag = diag::err_template_param_list_different_arity;
9043 if (TemplateArgLoc.isValid()) {
9044 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
9045 NextDiag = diag::note_template_param_list_different_arity;
9046 }
9047 S.Diag(New->getTemplateLoc(), NextDiag)
9048 << (New->size() > Old->size())
9049 << (Kind != Sema::TPL_TemplateMatch)
9050 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
9051 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
9052 << (Kind != Sema::TPL_TemplateMatch)
9053 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
9054}
9055
9056/// Determine whether the given template parameter lists are
9057/// equivalent.
9058///
9059/// \param New The new template parameter list, typically written in the
9060/// source code as part of a new template declaration.
9061///
9062/// \param Old The old template parameter list, typically found via
9063/// name lookup of the template declared with this template parameter
9064/// list.
9065///
9066/// \param Complain If true, this routine will produce a diagnostic if
9067/// the template parameter lists are not equivalent.
9068///
9069/// \param Kind describes how we are to match the template parameter lists.
9070///
9071/// \param TemplateArgLoc If this source location is valid, then we
9072/// are actually checking the template parameter list of a template
9073/// argument (New) against the template parameter list of its
9074/// corresponding template template parameter (Old). We produce
9075/// slightly different diagnostics in this scenario.
9076///
9077/// \returns True if the template parameter lists are equal, false
9078/// otherwise.
9080 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
9081 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
9082 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
9083 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
9084 if (Complain)
9085 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
9086 TemplateArgLoc);
9087
9088 return false;
9089 }
9090
9091 // C++0x [temp.arg.template]p3:
9092 // A template-argument matches a template template-parameter (call it P)
9093 // when each of the template parameters in the template-parameter-list of
9094 // the template-argument's corresponding class template or alias template
9095 // (call it A) matches the corresponding template parameter in the
9096 // template-parameter-list of P. [...]
9097 TemplateParameterList::iterator NewParm = New->begin();
9098 TemplateParameterList::iterator NewParmEnd = New->end();
9099 for (TemplateParameterList::iterator OldParm = Old->begin(),
9100 OldParmEnd = Old->end();
9101 OldParm != OldParmEnd; ++OldParm) {
9103 !(*OldParm)->isTemplateParameterPack()) {
9104 if (NewParm == NewParmEnd) {
9105 if (Complain)
9106 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
9107 TemplateArgLoc);
9108
9109 return false;
9110 }
9111
9112 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
9113 OldInstFrom, Complain, Kind,
9114 TemplateArgLoc))
9115 return false;
9116
9117 ++NewParm;
9118 continue;
9119 }
9120
9121 // C++0x [temp.arg.template]p3:
9122 // [...] When P's template- parameter-list contains a template parameter
9123 // pack (14.5.3), the template parameter pack will match zero or more
9124 // template parameters or template parameter packs in the
9125 // template-parameter-list of A with the same type and form as the
9126 // template parameter pack in P (ignoring whether those template
9127 // parameters are template parameter packs).
9128 for (; NewParm != NewParmEnd; ++NewParm) {
9129 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
9130 OldInstFrom, Complain, Kind,
9131 TemplateArgLoc))
9132 return false;
9133 }
9134 }
9135
9136 // Make sure we exhausted all of the arguments.
9137 if (NewParm != NewParmEnd) {
9138 if (Complain)
9139 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
9140 TemplateArgLoc);
9141
9142 return false;
9143 }
9144
9147 const Expr *NewRC = New->getRequiresClause();
9148 const Expr *OldRC = Old->getRequiresClause();
9149
9150 auto Diagnose = [&] {
9151 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
9152 diag::err_template_different_requires_clause);
9153 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
9154 diag::note_template_prev_declaration) << /*declaration*/0;
9155 };
9156
9157 if (!NewRC != !OldRC) {
9158 if (Complain)
9159 Diagnose();
9160 return false;
9161 }
9162
9163 if (NewRC) {
9164 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
9165 NewRC)) {
9166 if (Complain)
9167 Diagnose();
9168 return false;
9169 }
9170 }
9171 }
9172
9173 return true;
9174}
9175
9176/// Check whether a template can be declared within this scope.
9177///
9178/// If the template declaration is valid in this scope, returns
9179/// false. Otherwise, issues a diagnostic and returns true.
9180bool
9182 if (!S)
9183 return false;
9184
9185 // Find the nearest enclosing declaration scope.
9186 S = S->getDeclParent();
9187
9188 // C++ [temp.pre]p6: [P2096]
9189 // A template, explicit specialization, or partial specialization shall not
9190 // have C linkage.
9191 DeclContext *Ctx = S->getEntity();
9192 if (Ctx && Ctx->isExternCContext()) {
9193 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
9194 << TemplateParams->getSourceRange();
9195 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
9196 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
9197 return true;
9198 }
9199 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
9200
9201 // C++ [temp]p2:
9202 // A template-declaration can appear only as a namespace scope or
9203 // class scope declaration.
9204 // C++ [temp.expl.spec]p3:
9205 // An explicit specialization may be declared in any scope in which the
9206 // corresponding primary template may be defined.
9207 // C++ [temp.class.spec]p6: [P2096]
9208 // A partial specialization may be declared in any scope in which the
9209 // corresponding primary template may be defined.
9210 if (Ctx) {
9211 if (Ctx->isFileContext())
9212 return false;
9213 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
9214 // C++ [temp.mem]p2:
9215 // A local class shall not have member templates.
9216 if (RD->isLocalClass())
9217 return Diag(TemplateParams->getTemplateLoc(),
9218 diag::err_template_inside_local_class)
9219 << TemplateParams->getSourceRange();
9220 else
9221 return false;
9222 }
9223 }
9224
9225 return Diag(TemplateParams->getTemplateLoc(),
9226 diag::err_template_outside_namespace_or_class_scope)
9227 << TemplateParams->getSourceRange();
9228}
9229
9230/// Determine what kind of template specialization the given declaration
9231/// is.
9233 if (!D)
9234 return TSK_Undeclared;
9235
9236 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
9237 return Record->getTemplateSpecializationKind();
9238 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
9239 return Function->getTemplateSpecializationKind();
9240 if (VarDecl *Var = dyn_cast<VarDecl>(D))
9241 return Var->getTemplateSpecializationKind();
9242
9243 return TSK_Undeclared;
9244}
9245
9246/// Check whether a specialization is well-formed in the current
9247/// context.
9248///
9249/// This routine determines whether a template specialization can be declared
9250/// in the current context (C++ [temp.expl.spec]p2).
9251///
9252/// \param S the semantic analysis object for which this check is being
9253/// performed.
9254///
9255/// \param Specialized the entity being specialized or instantiated, which
9256/// may be a kind of template (class template, function template, etc.) or
9257/// a member of a class template (member function, static data member,
9258/// member class).
9259///
9260/// \param PrevDecl the previous declaration of this entity, if any.
9261///
9262/// \param Loc the location of the explicit specialization or instantiation of
9263/// this entity.
9264///
9265/// \param IsPartialSpecialization whether this is a partial specialization of
9266/// a class template.
9267///
9268/// \returns true if there was an error that we cannot recover from, false
9269/// otherwise.
9271 NamedDecl *Specialized,
9272 NamedDecl *PrevDecl,
9275 // Keep these "kind" numbers in sync with the %select statements in the
9276 // various diagnostics emitted by this routine.
9277 int EntityKind = 0;
9278 if (isa<ClassTemplateDecl>(Specialized))
9279 EntityKind = IsPartialSpecialization? 1 : 0;
9280 else if (isa<VarTemplateDecl>(Specialized))
9281 EntityKind = IsPartialSpecialization ? 3 : 2;
9282 else if (isa<FunctionTemplateDecl>(Specialized))
9283 EntityKind = 4;
9284 else if (isa<CXXMethodDecl>(Specialized))
9285 EntityKind = 5;
9286 else if (isa<VarDecl>(Specialized))
9287 EntityKind = 6;
9288 else if (isa<RecordDecl>(Specialized))
9289 EntityKind = 7;
9290 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
9291 EntityKind = 8;
9292 else {
9293 S.Diag(Loc, diag::err_template_spec_unknown_kind)
9294 << S.getLangOpts().CPlusPlus11;
9295 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
9296 return true;
9297 }
9298
9299 // C++ [temp.expl.spec]p2:
9300 // An explicit specialization may be declared in any scope in which
9301 // the corresponding primary template may be defined.
9303 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
9304 << Specialized;
9305 return true;
9306 }
9307
9308 // C++ [temp.class.spec]p6:
9309 // A class template partial specialization may be declared in any
9310 // scope in which the primary template may be defined.
9311 DeclContext *SpecializedContext =
9312 Specialized->getDeclContext()->getRedeclContext();
9314
9315 // Make sure that this redeclaration (or definition) occurs in the same
9316 // scope or an enclosing namespace.
9317 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
9318 : DC->Equals(SpecializedContext))) {
9319 if (isa<TranslationUnitDecl>(SpecializedContext))
9320 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
9321 << EntityKind << Specialized;
9322 else {
9323 auto *ND = cast<NamedDecl>(SpecializedContext);
9324 int Diag = diag::err_template_spec_redecl_out_of_scope;
9325 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
9326 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
9327 S.Diag(Loc, Diag) << EntityKind << Specialized
9328 << ND << isa<CXXRecordDecl>(ND);
9329 }
9330
9331 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
9332
9333 // Don't allow specializing in the wrong class during error recovery.
9334 // Otherwise, things can go horribly wrong.
9335 if (DC->isRecord())
9336 return true;
9337 }
9338
9339 return false;
9340}
9341
9343 if (!E->isTypeDependent())
9344 return SourceLocation();
9345 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
9346 Checker.TraverseStmt(E);
9347 if (Checker.MatchLoc.isInvalid())
9348 return E->getSourceRange();
9349 return Checker.MatchLoc;
9350}
9351
9352static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
9353 if (!TL.getType()->isDependentType())
9354 return SourceLocation();
9355 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
9356 Checker.TraverseTypeLoc(TL);
9357 if (Checker.MatchLoc.isInvalid())
9358 return TL.getSourceRange();
9359 return Checker.MatchLoc;
9360}
9361
9362/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
9363/// that checks non-type template partial specialization arguments.
9365 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
9366 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
9367 for (unsigned I = 0; I != NumArgs; ++I) {
9368 if (Args[I].getKind() == TemplateArgument::Pack) {
9370 S, TemplateNameLoc, Param, Args[I].pack_begin(),
9371 Args[I].pack_size(), IsDefaultArgument))
9372 return true;
9373
9374 continue;
9375 }
9376
9377 if (Args[I].getKind() != TemplateArgument::Expression)
9378 continue;
9379
9380 Expr *ArgExpr = Args[I].getAsExpr();
9381
9382 // We can have a pack expansion of any of the bullets below.
9383 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
9384 ArgExpr = Expansion->getPattern();
9385
9386 // Strip off any implicit casts we added as part of type checking.
9387 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9388 ArgExpr = ICE->getSubExpr();
9389
9390 // C++ [temp.class.spec]p8:
9391 // A non-type argument is non-specialized if it is the name of a
9392 // non-type parameter. All other non-type arguments are
9393 // specialized.
9394 //
9395 // Below, we check the two conditions that only apply to
9396 // specialized non-type arguments, so skip any non-specialized
9397 // arguments.
9398 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
9399 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
9400 continue;
9401
9402 // C++ [temp.class.spec]p9:
9403 // Within the argument list of a class template partial
9404 // specialization, the following restrictions apply:
9405 // -- A partially specialized non-type argument expression
9406 // shall not involve a template parameter of the partial
9407 // specialization except when the argument expression is a
9408 // simple identifier.
9409 // -- The type of a template parameter corresponding to a
9410 // specialized non-type argument shall not be dependent on a
9411 // parameter of the specialization.
9412 // DR1315 removes the first bullet, leaving an incoherent set of rules.
9413 // We implement a compromise between the original rules and DR1315:
9414 // -- A specialized non-type template argument shall not be
9415 // type-dependent and the corresponding template parameter
9416 // shall have a non-dependent type.
9417 SourceRange ParamUseRange =
9418 findTemplateParameterInType(Param->getDepth(), ArgExpr);
9419 if (ParamUseRange.isValid()) {
9420 if (IsDefaultArgument) {
9421 S.Diag(TemplateNameLoc,
9422 diag::err_dependent_non_type_arg_in_partial_spec);
9423 S.Diag(ParamUseRange.getBegin(),
9424 diag::note_dependent_non_type_default_arg_in_partial_spec)
9425 << ParamUseRange;
9426 } else {
9427 S.Diag(ParamUseRange.getBegin(),
9428 diag::err_dependent_non_type_arg_in_partial_spec)
9429 << ParamUseRange;
9430 }
9431 return true;
9432 }
9433
9434 ParamUseRange = findTemplateParameter(
9435 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
9436 if (ParamUseRange.isValid()) {
9437 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
9438 diag::err_dependent_typed_non_type_arg_in_partial_spec)
9439 << Param->getType();
9441 return true;
9442 }
9443 }
9444
9445 return false;
9446}
9447
9448/// Check the non-type template arguments of a class template
9449/// partial specialization according to C++ [temp.class.spec]p9.
9450///
9451/// \param TemplateNameLoc the location of the template name.
9452/// \param PrimaryTemplate the template parameters of the primary class
9453/// template.
9454/// \param NumExplicit the number of explicitly-specified template arguments.
9455/// \param TemplateArgs the template arguments of the class template
9456/// partial specialization.
9457///
9458/// \returns \c true if there was an error, \c false otherwise.
9460 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
9461 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
9462 // We have to be conservative when checking a template in a dependent
9463 // context.
9464 if (PrimaryTemplate->getDeclContext()->isDependentContext())
9465 return false;
9466
9467 TemplateParameterList *TemplateParams =
9468 PrimaryTemplate->getTemplateParameters();
9469 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
9471 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
9472 if (!Param)
9473 continue;
9474
9475 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
9476 Param, &TemplateArgs[I],
9477 1, I >= NumExplicit))
9478 return true;
9479 }
9480
9481 return false;
9482}
9483
9485 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
9486 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
9488 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
9489 assert(TUK != TUK_Reference && "References are not specializations");
9490
9491 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
9492 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
9493 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
9494
9495 // Find the class template we're specializing
9496 TemplateName Name = TemplateId.Template.get();
9498 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
9499
9500 if (!ClassTemplate) {
9501 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
9502 << (Name.getAsTemplateDecl() &&
9503 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
9504 return true;
9505 }
9506
9507 bool isMemberSpecialization = false;
9508 bool isPartialSpecialization = false;
9509
9510 if (SS.isSet()) {
9511 if (TUK != TUK_Reference && TUK != TUK_Friend &&
9512 diagnoseQualifiedDeclaration(SS, ClassTemplate->getDeclContext(),
9513 ClassTemplate->getDeclName(),
9514 TemplateNameLoc, &TemplateId,
9515 /*IsMemberSpecialization=*/false))
9516 return true;
9517 }
9518
9519 // Check the validity of the template headers that introduce this
9520 // template.
9521 // FIXME: We probably shouldn't complain about these headers for
9522 // friend declarations.
9523 bool Invalid = false;
9524 TemplateParameterList *TemplateParams =
9526 KWLoc, TemplateNameLoc, SS, &TemplateId,
9527 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
9528 Invalid);
9529 if (Invalid)
9530 return true;
9531
9532 // Check that we can declare a template specialization here.
9533 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
9534 return true;
9535
9536 if (TemplateParams && TemplateParams->size() > 0) {
9537 isPartialSpecialization = true;
9538
9539 if (TUK == TUK_Friend) {
9540 Diag(KWLoc, diag::err_partial_specialization_friend)
9541 << SourceRange(LAngleLoc, RAngleLoc);
9542 return true;
9543 }
9544
9545 // C++ [temp.class.spec]p10:
9546 // The template parameter list of a specialization shall not
9547 // contain default template argument values.
9548 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
9549 Decl *Param = TemplateParams->getParam(I);
9550 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
9551 if (TTP->hasDefaultArgument()) {
9553 diag::err_default_arg_in_partial_spec);
9554 TTP->removeDefaultArgument();
9555 }
9556 } else if (NonTypeTemplateParmDecl *NTTP
9557 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
9558 if (Expr *DefArg = NTTP->getDefaultArgument()) {
9559 Diag(NTTP->getDefaultArgumentLoc(),
9560 diag::err_default_arg_in_partial_spec)
9561 << DefArg->getSourceRange();
9562 NTTP->removeDefaultArgument();
9563 }
9564 } else {
9565 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
9566 if (TTP->hasDefaultArgument()) {
9568 diag::err_default_arg_in_partial_spec)
9570 TTP->removeDefaultArgument();
9571 }
9572 }
9573 }
9574 } else if (TemplateParams) {
9575 if (TUK == TUK_Friend)
9576 Diag(KWLoc, diag::err_template_spec_friend)
9578 SourceRange(TemplateParams->getTemplateLoc(),
9579 TemplateParams->getRAngleLoc()))
9580 << SourceRange(LAngleLoc, RAngleLoc);
9581 } else {
9582 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
9583 }
9584
9585 // Check that the specialization uses the same tag kind as the
9586 // original template.
9588 assert(Kind != TagTypeKind::Enum &&
9589 "Invalid enum tag in class template spec!");
9590 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9591 Kind, TUK == TUK_Definition, KWLoc,
9592 ClassTemplate->getIdentifier())) {
9593 Diag(KWLoc, diag::err_use_with_wrong_tag)
9594 << ClassTemplate
9596 ClassTemplate->getTemplatedDecl()->getKindName());
9597 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9598 diag::note_previous_use);
9599 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9600 }
9601
9602 // Translate the parser's template argument list in our AST format.
9603 TemplateArgumentListInfo TemplateArgs =
9604 makeTemplateArgumentListInfo(*this, TemplateId);
9605
9606 // Check for unexpanded parameter packs in any of the template arguments.
9607 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9608 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
9609 isPartialSpecialization
9612 return true;
9613
9614 // Check that the template argument list is well-formed for this
9615 // template.
9616 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9617 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9618 false, SugaredConverted, CanonicalConverted,
9619 /*UpdateArgsWithConversions=*/true))
9620 return true;
9621
9622 // Find the class template (partial) specialization declaration that
9623 // corresponds to these arguments.
9624 if (isPartialSpecialization) {
9626 TemplateArgs.size(),
9627 CanonicalConverted))
9628 return true;
9629
9630 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
9631 // also do it during instantiation.
9632 if (!Name.isDependent() &&
9634 TemplateArgs, CanonicalConverted)) {
9635 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
9636 << ClassTemplate->getDeclName();
9637 isPartialSpecialization = false;
9638 Invalid = true;
9639 }
9640 }
9641
9642 void *InsertPos = nullptr;
9643 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
9644
9645 if (isPartialSpecialization)
9646 PrevDecl = ClassTemplate->findPartialSpecialization(
9647 CanonicalConverted, TemplateParams, InsertPos);
9648 else
9649 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9650
9652
9653 // Check whether we can declare a class template specialization in
9654 // the current scope.
9655 if (TUK != TUK_Friend &&
9657 TemplateNameLoc,
9658 isPartialSpecialization))
9659 return true;
9660
9661 // The canonical type
9662 QualType CanonType;
9663 if (isPartialSpecialization) {
9664 // Build the canonical type that describes the converted template
9665 // arguments of the class template partial specialization.
9666 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9667 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
9668 CanonicalConverted);
9669
9670 if (Context.hasSameType(CanonType,
9671 ClassTemplate->getInjectedClassNameSpecialization()) &&
9672 (!Context.getLangOpts().CPlusPlus20 ||
9673 !TemplateParams->hasAssociatedConstraints())) {
9674 // C++ [temp.class.spec]p9b3:
9675 //
9676 // -- The argument list of the specialization shall not be identical
9677 // to the implicit argument list of the primary template.
9678 //
9679 // This rule has since been removed, because it's redundant given DR1495,
9680 // but we keep it because it produces better diagnostics and recovery.
9681 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9682 << /*class template*/0 << (TUK == TUK_Definition)
9683 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9684 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
9685 ClassTemplate->getIdentifier(),
9686 TemplateNameLoc,
9687 Attr,
9688 TemplateParams,
9689 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
9690 /*FriendLoc*/SourceLocation(),
9691 TemplateParameterLists.size() - 1,
9692 TemplateParameterLists.data());
9693 }
9694
9695 // Create a new class template partial specialization declaration node.
9697 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9700 Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
9701 TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
9702 CanonType, PrevPartial);
9703 Partial->setTemplateArgsAsWritten(TemplateArgs);
9704 SetNestedNameSpecifier(*this, Partial, SS);
9705 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9707 Context, TemplateParameterLists.drop_back(1));
9708 }
9709
9710 if (!PrevPartial)
9711 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9712 Specialization = Partial;
9713
9714 // If we are providing an explicit specialization of a member class
9715 // template specialization, make a note of that.
9716 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9717 PrevPartial->setMemberSpecialization();
9718
9720 } else {
9721 // Create a new class template specialization declaration node for
9722 // this explicit specialization or friend declaration.
9724 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9725 ClassTemplate, CanonicalConverted, PrevDecl);
9726 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9728 if (TemplateParameterLists.size() > 0) {
9729 Specialization->setTemplateParameterListsInfo(Context,
9730 TemplateParameterLists);
9731 }
9732
9733 if (!PrevDecl)
9734 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9735
9737 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9738 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
9739 CanonicalConverted);
9740 } else {
9742 }
9743 }
9744
9745 // C++ [temp.expl.spec]p6:
9746 // If a template, a member template or the member of a class template is
9747 // explicitly specialized then that specialization shall be declared
9748 // before the first use of that specialization that would cause an implicit
9749 // instantiation to take place, in every translation unit in which such a
9750 // use occurs; no diagnostic is required.
9751 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9752 bool Okay = false;
9753 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9754 // Is there any previous explicit specialization declaration?
9756 Okay = true;
9757 break;
9758 }
9759 }
9760
9761 if (!Okay) {
9762 SourceRange Range(TemplateNameLoc, RAngleLoc);
9763 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9765
9766 Diag(PrevDecl->getPointOfInstantiation(),
9767 diag::note_instantiation_required_here)
9768 << (PrevDecl->getTemplateSpecializationKind()
9770 return true;
9771 }
9772 }
9773
9774 // If this is not a friend, note that this is an explicit specialization.
9775 if (TUK != TUK_Friend)
9776 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9777
9778 // Check that this isn't a redefinition of this specialization.
9779 if (TUK == TUK_Definition) {
9780 RecordDecl *Def = Specialization->getDefinition();
9781 NamedDecl *Hidden = nullptr;
9782 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
9783 SkipBody->ShouldSkip = true;
9784 SkipBody->Previous = Def;
9786 } else if (Def) {
9787 SourceRange Range(TemplateNameLoc, RAngleLoc);
9788 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9789 Diag(Def->getLocation(), diag::note_previous_definition);
9790 Specialization->setInvalidDecl();
9791 return true;
9792 }
9793 }
9794
9797
9798 // Add alignment attributes if necessary; these attributes are checked when
9799 // the ASTContext lays out the structure.
9800 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9803 }
9804
9805 if (ModulePrivateLoc.isValid())
9806 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9807 << (isPartialSpecialization? 1 : 0)
9808 << FixItHint::CreateRemoval(ModulePrivateLoc);
9809
9810 // C++ [temp.expl.spec]p9:
9811 // A template explicit specialization is in the scope of the
9812 // namespace in which the template was defined.
9813 //
9814 // We actually implement this paragraph where we set the semantic
9815 // context (in the creation of the ClassTemplateSpecializationDecl),
9816 // but we also maintain the lexical context where the actual
9817 // definition occurs.
9818 Specialization->setLexicalDeclContext(CurContext);
9819
9820 // We may be starting the definition of this specialization.
9821 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
9822 Specialization->startDefinition();
9823
9824 if (TUK == TUK_Friend) {
9825 // Build the fully-sugared type for this class template
9826 // specialization as the user wrote in the specialization
9827 // itself. This means that we'll pretty-print the type retrieved
9828 // from the specialization's declaration the way that the user
9829 // actually wrote the specialization, rather than formatting the
9830 // name based on the "canonical" representation used to store the
9831 // template arguments in the specialization.
9833 Name, TemplateNameLoc, TemplateArgs, CanonType);
9835 TemplateNameLoc,
9836 WrittenTy,
9837 /*FIXME:*/KWLoc);
9838 Friend->setAccess(AS_public);
9839 CurContext->addDecl(Friend);
9840 } else {
9841 // Add the specialization into its lexical context, so that it can
9842 // be seen when iterating through the list of declarations in that
9843 // context. However, specializations are not found by name lookup.
9845 }
9846
9847 if (SkipBody && SkipBody->ShouldSkip)
9848 return SkipBody->Previous;
9849
9850 Specialization->setInvalidDecl(Invalid);
9851 return Specialization;
9852}
9853
9855 MultiTemplateParamsArg TemplateParameterLists,
9856 Declarator &D) {
9857 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9858 ActOnDocumentableDecl(NewDecl);
9859 return NewDecl;
9860}
9861
9863 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9864 const IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr,
9865 const ParsedAttributesView &Attrs) {
9866 DeclContext *DC = CurContext;
9867
9868 if (!DC->getRedeclContext()->isFileContext()) {
9869 Diag(NameLoc,
9870 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9871 return nullptr;
9872 }
9873
9874 if (TemplateParameterLists.size() > 1) {
9875 Diag(NameLoc, diag::err_concept_extra_headers);
9876 return nullptr;
9877 }
9878
9879 TemplateParameterList *Params = TemplateParameterLists.front();
9880
9881 if (Params->size() == 0) {
9882 Diag(NameLoc, diag::err_concept_no_parameters);
9883 return nullptr;
9884 }
9885
9886 // Ensure that the parameter pack, if present, is the last parameter in the
9887 // template.
9888 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9889 ParamEnd = Params->end();
9890 ParamIt != ParamEnd; ++ParamIt) {
9891 Decl const *Param = *ParamIt;
9892 if (Param->isParameterPack()) {
9893 if (++ParamIt == ParamEnd)
9894 break;
9895 Diag(Param->getLocation(),
9896 diag::err_template_param_pack_must_be_last_template_parameter);
9897 return nullptr;
9898 }
9899 }
9900
9901 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
9902 return nullptr;
9903
9904 ConceptDecl *NewDecl =
9905 ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
9906
9907 if (NewDecl->hasAssociatedConstraints()) {
9908 // C++2a [temp.concept]p4:
9909 // A concept shall not have associated constraints.
9910 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9911 NewDecl->setInvalidDecl();
9912 }
9913
9914 // Check for conflicting previous declaration.
9915 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
9916 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9918 LookupName(Previous, S);
9919 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
9920 /*AllowInlineNamespace*/false);
9921 bool AddToScope = true;
9922 CheckConceptRedefinition(NewDecl, Previous, AddToScope);
9923
9924 ActOnDocumentableDecl(NewDecl);
9925 if (AddToScope)
9926 PushOnScopeChains(NewDecl, S);
9927
9928 ProcessDeclAttributeList(S, NewDecl, Attrs);
9929
9930 return NewDecl;
9931}
9932
9934 LookupResult &Previous, bool &AddToScope) {
9935 AddToScope = true;
9936
9937 if (Previous.empty())
9938 return;
9939
9940 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9941 if (!OldConcept) {
9942 auto *Old = Previous.getRepresentativeDecl();
9943 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9944 << NewDecl->getDeclName();
9945 notePreviousDefinition(Old, NewDecl->getLocation());
9946 AddToScope = false;
9947 return;
9948 }
9949 // Check if we can merge with a concept declaration.
9950 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9951 if (!IsSame) {
9952 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9953 << NewDecl->getDeclName();
9954 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9955 AddToScope = false;
9956 return;
9957 }
9958 if (hasReachableDefinition(OldConcept) &&
9959 IsRedefinitionInModule(NewDecl, OldConcept)) {
9960 Diag(NewDecl->getLocation(), diag::err_redefinition)
9961 << NewDecl->getDeclName();
9962 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9963 AddToScope = false;
9964 return;
9965 }
9966 if (!Previous.isSingleResult()) {
9967 // FIXME: we should produce an error in case of ambig and failed lookups.
9968 // Other decls (e.g. namespaces) also have this shortcoming.
9969 return;
9970 }
9971 // We unwrap canonical decl late to check for module visibility.
9972 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9973}
9974
9975/// \brief Strips various properties off an implicit instantiation
9976/// that has just been explicitly specialized.
9977static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9978 if (MinGW || (isa<FunctionDecl>(D) &&
9979 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9980 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9981
9982 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9983 FD->setInlineSpecified(false);
9984}
9985
9986/// Compute the diagnostic location for an explicit instantiation
9987// declaration or definition.
9989 NamedDecl* D, SourceLocation PointOfInstantiation) {
9990 // Explicit instantiations following a specialization have no effect and
9991 // hence no PointOfInstantiation. In that case, walk decl backwards
9992 // until a valid name loc is found.
9993 SourceLocation PrevDiagLoc = PointOfInstantiation;
9994 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9995 Prev = Prev->getPreviousDecl()) {
9996 PrevDiagLoc = Prev->getLocation();
9997 }
9998 assert(PrevDiagLoc.isValid() &&
9999 "Explicit instantiation without point of instantiation?");
10000 return PrevDiagLoc;
10001}
10002
10003/// Diagnose cases where we have an explicit template specialization
10004/// before/after an explicit template instantiation, producing diagnostics
10005/// for those cases where they are required and determining whether the
10006/// new specialization/instantiation will have any effect.
10007///
10008/// \param NewLoc the location of the new explicit specialization or
10009/// instantiation.
10010///
10011/// \param NewTSK the kind of the new explicit specialization or instantiation.
10012///
10013/// \param PrevDecl the previous declaration of the entity.
10014///
10015/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
10016///
10017/// \param PrevPointOfInstantiation if valid, indicates where the previous
10018/// declaration was instantiated (either implicitly or explicitly).
10019///
10020/// \param HasNoEffect will be set to true to indicate that the new
10021/// specialization or instantiation has no effect and should be ignored.
10022///
10023/// \returns true if there was an error that should prevent the introduction of
10024/// the new declaration into the AST, false otherwise.
10025bool
10028 NamedDecl *PrevDecl,
10030 SourceLocation PrevPointOfInstantiation,
10031 bool &HasNoEffect) {
10032 HasNoEffect = false;
10033
10034 switch (NewTSK) {
10035 case TSK_Undeclared:
10037 assert(
10038 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
10039 "previous declaration must be implicit!");
10040 return false;
10041
10043 switch (PrevTSK) {
10044 case TSK_Undeclared:
10046 // Okay, we're just specializing something that is either already
10047 // explicitly specialized or has merely been mentioned without any
10048 // instantiation.
10049 return false;
10050
10052 if (PrevPointOfInstantiation.isInvalid()) {
10053 // The declaration itself has not actually been instantiated, so it is
10054 // still okay to specialize it.
10056 PrevDecl,
10057 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
10058 return false;
10059 }
10060 // Fall through
10061 [[fallthrough]];
10062
10065 assert((PrevTSK == TSK_ImplicitInstantiation ||
10066 PrevPointOfInstantiation.isValid()) &&
10067 "Explicit instantiation without point of instantiation?");
10068
10069 // C++ [temp.expl.spec]p6:
10070 // If a template, a member template or the member of a class template
10071 // is explicitly specialized then that specialization shall be declared
10072 // before the first use of that specialization that would cause an
10073 // implicit instantiation to take place, in every translation unit in
10074 // which such a use occurs; no diagnostic is required.
10075 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
10076 // Is there any previous explicit specialization declaration?
10078 return false;
10079 }
10080
10081 Diag(NewLoc, diag::err_specialization_after_instantiation)
10082 << PrevDecl;
10083 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
10084 << (PrevTSK != TSK_ImplicitInstantiation);
10085
10086 return true;
10087 }
10088 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
10089
10091 switch (PrevTSK) {
10093 // This explicit instantiation declaration is redundant (that's okay).
10094 HasNoEffect = true;
10095 return false;
10096
10097 case TSK_Undeclared:
10099 // We're explicitly instantiating something that may have already been
10100 // implicitly instantiated; that's fine.
10101 return false;
10102
10104 // C++0x [temp.explicit]p4:
10105 // For a given set of template parameters, if an explicit instantiation
10106 // of a template appears after a declaration of an explicit
10107 // specialization for that template, the explicit instantiation has no
10108 // effect.
10109 HasNoEffect = true;
10110 return false;
10111
10113 // C++0x [temp.explicit]p10:
10114 // If an entity is the subject of both an explicit instantiation
10115 // declaration and an explicit instantiation definition in the same
10116 // translation unit, the definition shall follow the declaration.
10117 Diag(NewLoc,
10118 diag::err_explicit_instantiation_declaration_after_definition);
10119
10120 // Explicit instantiations following a specialization have no effect and
10121 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
10122 // until a valid name loc is found.
10123 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
10124 diag::note_explicit_instantiation_definition_here);
10125 HasNoEffect = true;
10126 return false;
10127 }
10128 llvm_unreachable("Unexpected TemplateSpecializationKind!");
10129
10131 switch (PrevTSK) {
10132 case TSK_Undeclared:
10134 // We're explicitly instantiating something that may have already been
10135 // implicitly instantiated; that's fine.
10136 return false;
10137
10139 // C++ DR 259, C++0x [temp.explicit]p4:
10140 // For a given set of template parameters, if an explicit
10141 // instantiation of a template appears after a declaration of
10142 // an explicit specialization for that template, the explicit
10143 // instantiation has no effect.
10144 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
10145 << PrevDecl;
10146 Diag(PrevDecl->getLocation(),
10147 diag::note_previous_template_specialization);
10148 HasNoEffect = true;
10149 return false;
10150
10152 // We're explicitly instantiating a definition for something for which we
10153 // were previously asked to suppress instantiations. That's fine.
10154
10155 // C++0x [temp.explicit]p4:
10156 // For a given set of template parameters, if an explicit instantiation
10157 // of a template appears after a declaration of an explicit
10158 // specialization for that template, the explicit instantiation has no
10159 // effect.
10160 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
10161 // Is there any previous explicit specialization declaration?
10163 HasNoEffect = true;
10164 break;
10165 }
10166 }
10167
10168 return false;
10169
10171 // C++0x [temp.spec]p5:
10172 // For a given template and a given set of template-arguments,
10173 // - an explicit instantiation definition shall appear at most once
10174 // in a program,
10175
10176 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
10177 Diag(NewLoc, (getLangOpts().MSVCCompat)
10178 ? diag::ext_explicit_instantiation_duplicate
10179 : diag::err_explicit_instantiation_duplicate)
10180 << PrevDecl;
10181 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
10182 diag::note_previous_explicit_instantiation);
10183 HasNoEffect = true;
10184 return false;
10185 }
10186 }
10187
10188 llvm_unreachable("Missing specialization/instantiation case?");
10189}
10190
10191/// Perform semantic analysis for the given dependent function
10192/// template specialization.
10193///
10194/// The only possible way to get a dependent function template specialization
10195/// is with a friend declaration, like so:
10196///
10197/// \code
10198/// template <class T> void foo(T);
10199/// template <class T> class A {
10200/// friend void foo<>(T);
10201/// };
10202/// \endcode
10203///
10204/// There really isn't any useful analysis we can do here, so we
10205/// just store the information.
10207 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
10209 // Remove anything from Previous that isn't a function template in
10210 // the correct context.
10211 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
10212 LookupResult::Filter F = Previous.makeFilter();
10213 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
10214 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
10215 while (F.hasNext()) {
10216 NamedDecl *D = F.next()->getUnderlyingDecl();
10217 if (!isa<FunctionTemplateDecl>(D)) {
10218 F.erase();
10219 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
10220 continue;
10221 }
10222
10223 if (!FDLookupContext->InEnclosingNamespaceSetOf(
10225 F.erase();
10226 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
10227 continue;
10228 }
10229 }
10230 F.done();
10231
10232 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
10233 if (Previous.empty()) {
10234 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
10235 << IsFriend;
10236 for (auto &P : DiscardedCandidates)
10237 Diag(P.second->getLocation(),
10238 diag::note_dependent_function_template_spec_discard_reason)
10239 << P.first << IsFriend;
10240 return true;
10241 }
10242
10244 ExplicitTemplateArgs);
10245 return false;
10246}
10247
10248/// Perform semantic analysis for the given function template
10249/// specialization.
10250///
10251/// This routine performs all of the semantic analysis required for an
10252/// explicit function template specialization. On successful completion,
10253/// the function declaration \p FD will become a function template
10254/// specialization.
10255///
10256/// \param FD the function declaration, which will be updated to become a
10257/// function template specialization.
10258///
10259/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
10260/// if any. Note that this may be valid info even when 0 arguments are
10261/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
10262/// as it anyway contains info on the angle brackets locations.
10263///
10264/// \param Previous the set of declarations that may be specialized by
10265/// this function specialization.
10266///
10267/// \param QualifiedFriend whether this is a lookup for a qualified friend
10268/// declaration with no explicit template argument list that might be
10269/// befriending a function template specialization.
10271 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
10272 LookupResult &Previous, bool QualifiedFriend) {
10273 // The set of function template specializations that could match this
10274 // explicit function template specialization.
10275 UnresolvedSet<8> Candidates;
10276 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
10277 /*ForTakingAddress=*/false);
10278
10279 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
10280 ConvertedTemplateArgs;
10281
10282 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
10283 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
10284 I != E; ++I) {
10285 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
10286 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
10287 // Only consider templates found within the same semantic lookup scope as
10288 // FD.
10289 if (!FDLookupContext->InEnclosingNamespaceSetOf(
10291 continue;
10292
10293 // When matching a constexpr member function template specialization
10294 // against the primary template, we don't yet know whether the
10295 // specialization has an implicit 'const' (because we don't know whether
10296 // it will be a static member function until we know which template it
10297 // specializes), so adjust it now assuming it specializes this template.
10298 QualType FT = FD->getType();
10299 if (FD->isConstexpr()) {
10300 CXXMethodDecl *OldMD =
10301 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
10302 if (OldMD && OldMD->isConst()) {
10303 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
10305 EPI.TypeQuals.addConst();
10307 FPT->getParamTypes(), EPI);
10308 }
10309 }
10310
10312 if (ExplicitTemplateArgs)
10313 Args = *ExplicitTemplateArgs;
10314
10315 // C++ [temp.expl.spec]p11:
10316 // A trailing template-argument can be left unspecified in the
10317 // template-id naming an explicit function template specialization
10318 // provided it can be deduced from the function argument type.
10319 // Perform template argument deduction to determine whether we may be
10320 // specializing this template.
10321 // FIXME: It is somewhat wasteful to build
10322 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10323 FunctionDecl *Specialization = nullptr;
10325 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
10326 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
10328 // Template argument deduction failed; record why it failed, so
10329 // that we can provide nifty diagnostics.
10330 FailedCandidates.addCandidate().set(
10331 I.getPair(), FunTmpl->getTemplatedDecl(),
10332 MakeDeductionFailureInfo(Context, TDK, Info));
10333 (void)TDK;
10334 continue;
10335 }
10336
10337 // Target attributes are part of the cuda function signature, so
10338 // the deduced template's cuda target must match that of the
10339 // specialization. Given that C++ template deduction does not
10340 // take target attributes into account, we reject candidates
10341 // here that have a different target.
10342 if (LangOpts.CUDA &&
10344 /* IgnoreImplicitHDAttr = */ true) !=
10345 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
10346 FailedCandidates.addCandidate().set(
10347 I.getPair(), FunTmpl->getTemplatedDecl(),
10350 continue;
10351 }
10352
10353 // Record this candidate.
10354 if (ExplicitTemplateArgs)
10355 ConvertedTemplateArgs[Specialization] = std::move(Args);
10356 Candidates.addDecl(Specialization, I.getAccess());
10357 }
10358 }
10359
10360 // For a qualified friend declaration (with no explicit marker to indicate
10361 // that a template specialization was intended), note all (template and
10362 // non-template) candidates.
10363 if (QualifiedFriend && Candidates.empty()) {
10364 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
10365 << FD->getDeclName() << FDLookupContext;
10366 // FIXME: We should form a single candidate list and diagnose all
10367 // candidates at once, to get proper sorting and limiting.
10368 for (auto *OldND : Previous) {
10369 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
10370 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
10371 }
10372 FailedCandidates.NoteCandidates(*this, FD->getLocation());
10373 return true;
10374 }
10375
10376 // Find the most specialized function template.
10378 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
10379 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
10380 PDiag(diag::err_function_template_spec_ambiguous)
10381 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
10382 PDiag(diag::note_function_template_spec_matched));
10383
10384 if (Result == Candidates.end())
10385 return true;
10386
10387 // Ignore access information; it doesn't figure into redeclaration checking.
10388 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
10389
10390 // C++23 [except.spec]p13:
10391 // An exception specification is considered to be needed when:
10392 // - [...]
10393 // - the exception specification is compared to that of another declaration
10394 // (e.g., an explicit specialization or an overriding virtual function);
10395 // - [...]
10396 //
10397 // The exception specification of a defaulted function is evaluated as
10398 // described above only when needed; similarly, the noexcept-specifier of a
10399 // specialization of a function template or member function of a class
10400 // template is instantiated only when needed.
10401 //
10402 // The standard doesn't specify what the "comparison with another declaration"
10403 // entails, nor the exact circumstances in which it occurs. Moreover, it does
10404 // not state which properties of an explicit specialization must match the
10405 // primary template.
10406 //
10407 // We assume that an explicit specialization must correspond with (per
10408 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
10409 // the declaration produced by substitution into the function template.
10410 //
10411 // Since the determination whether two function declarations correspond does
10412 // not consider exception specification, we only need to instantiate it once
10413 // we determine the primary template when comparing types per
10414 // [basic.link]p11.1.
10415 auto *SpecializationFPT =
10416 Specialization->getType()->castAs<FunctionProtoType>();
10417 // If the function has a dependent exception specification, resolve it after
10418 // we have selected the primary template so we can check whether it matches.
10419 if (getLangOpts().CPlusPlus17 &&
10420 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
10421 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
10422 return true;
10423
10425 = Specialization->getTemplateSpecializationInfo();
10426 assert(SpecInfo && "Function template specialization info missing?");
10427
10428 // Note: do not overwrite location info if previous template
10429 // specialization kind was explicit.
10431 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
10432 Specialization->setLocation(FD->getLocation());
10433 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
10434 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
10435 // function can differ from the template declaration with respect to
10436 // the constexpr specifier.
10437 // FIXME: We need an update record for this AST mutation.
10438 // FIXME: What if there are multiple such prior declarations (for instance,
10439 // from different modules)?
10440 Specialization->setConstexprKind(FD->getConstexprKind());
10441 }
10442
10443 // FIXME: Check if the prior specialization has a point of instantiation.
10444 // If so, we have run afoul of .
10445
10446 // If this is a friend declaration, then we're not really declaring
10447 // an explicit specialization.
10448 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
10449
10450 // Check the scope of this explicit specialization.
10451 if (!isFriend &&
10453 Specialization->getPrimaryTemplate(),
10455 false))
10456 return true;
10457
10458 // C++ [temp.expl.spec]p6:
10459 // If a template, a member template or the member of a class template is
10460 // explicitly specialized then that specialization shall be declared
10461 // before the first use of that specialization that would cause an implicit
10462 // instantiation to take place, in every translation unit in which such a
10463 // use occurs; no diagnostic is required.
10464 bool HasNoEffect = false;
10465 if (!isFriend &&
10470 SpecInfo->getPointOfInstantiation(),
10471 HasNoEffect))
10472 return true;
10473
10474 // Mark the prior declaration as an explicit specialization, so that later
10475 // clients know that this is an explicit specialization.
10476 if (!isFriend) {
10477 // Since explicit specializations do not inherit '=delete' from their
10478 // primary function template - check if the 'specialization' that was
10479 // implicitly generated (during template argument deduction for partial
10480 // ordering) from the most specialized of all the function templates that
10481 // 'FD' could have been specializing, has a 'deleted' definition. If so,
10482 // first check that it was implicitly generated during template argument
10483 // deduction by making sure it wasn't referenced, and then reset the deleted
10484 // flag to not-deleted, so that we can inherit that information from 'FD'.
10485 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
10486 !Specialization->getCanonicalDecl()->isReferenced()) {
10487 // FIXME: This assert will not hold in the presence of modules.
10488 assert(
10489 Specialization->getCanonicalDecl() == Specialization &&
10490 "This must be the only existing declaration of this specialization");
10491 // FIXME: We need an update record for this AST mutation.
10492 Specialization->setDeletedAsWritten(false);
10493 }
10494 // FIXME: We need an update record for this AST mutation.
10497 }
10498
10499 // Turn the given function declaration into a function template
10500 // specialization, with the template arguments from the previous
10501 // specialization.
10502 // Take copies of (semantic and syntactic) template argument lists.
10504 Context, Specialization->getTemplateSpecializationArgs()->asArray());
10505 FD->setFunctionTemplateSpecialization(
10506 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
10508 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
10509
10510 // A function template specialization inherits the target attributes
10511 // of its template. (We require the attributes explicitly in the
10512 // code to match, but a template may have implicit attributes by
10513 // virtue e.g. of being constexpr, and it passes these implicit
10514 // attributes on to its specializations.)
10515 if (LangOpts.CUDA)
10516 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
10517
10518 // The "previous declaration" for this function template specialization is
10519 // the prior function template specialization.
10520 Previous.clear();
10521 Previous.addDecl(Specialization);
10522 return false;
10523}
10524
10525/// Perform semantic analysis for the given non-template member
10526/// specialization.
10527///
10528/// This routine performs all of the semantic analysis required for an
10529/// explicit member function specialization. On successful completion,
10530/// the function declaration \p FD will become a member function
10531/// specialization.
10532///
10533/// \param Member the member declaration, which will be updated to become a
10534/// specialization.
10535///
10536/// \param Previous the set of declarations, one of which may be specialized
10537/// by this function specialization; the set will be modified to contain the
10538/// redeclared member.
10539bool
10541 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
10542
10543 // Try to find the member we are instantiating.
10544 NamedDecl *FoundInstantiation = nullptr;
10545 NamedDecl *Instantiation = nullptr;
10546 NamedDecl *InstantiatedFrom = nullptr;
10547 MemberSpecializationInfo *MSInfo = nullptr;
10548
10549 if (Previous.empty()) {
10550 // Nowhere to look anyway.
10551 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
10552 SmallVector<FunctionDecl *> Candidates;
10553 bool Ambiguous = false;
10554 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
10555 I != E; ++I) {
10556 CXXMethodDecl *Method =
10557 dyn_cast<CXXMethodDecl>((*I)->getUnderlyingDecl());
10558 if (!Method)
10559 continue;
10560 QualType Adjusted = Function->getType();
10561 if (!hasExplicitCallingConv(Adjusted))
10562 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
10563 // This doesn't handle deduced return types, but both function
10564 // declarations should be undeduced at this point.
10565 if (!Context.hasSameType(Adjusted, Method->getType()))
10566 continue;
10567 if (ConstraintSatisfaction Satisfaction;
10568 Method->getTrailingRequiresClause() &&
10569 (CheckFunctionConstraints(Method, Satisfaction,
10570 /*UsageLoc=*/Member->getLocation(),
10571 /*ForOverloadResolution=*/true) ||
10572 !Satisfaction.IsSatisfied))
10573 continue;
10574 Candidates.push_back(Method);
10575 FunctionDecl *MoreConstrained =
10576 Instantiation ? getMoreConstrainedFunction(
10577 Method, cast<FunctionDecl>(Instantiation))
10578 : Method;
10579 if (!MoreConstrained) {
10580 Ambiguous = true;
10581 continue;
10582 }
10583 if (MoreConstrained == Method) {
10584 Ambiguous = false;
10585 FoundInstantiation = *I;
10586 Instantiation = Method;
10587 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
10588 MSInfo = Method->getMemberSpecializationInfo();
10589 }
10590 }
10591 if (Ambiguous) {
10592 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
10593 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
10594 for (FunctionDecl *Candidate : Candidates)
10595 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
10596 << Candidate;
10597 return true;
10598 }
10599 } else if (isa<VarDecl>(Member)) {
10600 VarDecl *PrevVar;
10601 if (Previous.isSingleResult() &&
10602 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
10603 if (PrevVar->isStaticDataMember()) {
10604 FoundInstantiation = Previous.getRepresentativeDecl();
10605 Instantiation = PrevVar;
10606 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10607 MSInfo = PrevVar->getMemberSpecializationInfo();
10608 }
10609 } else if (isa<RecordDecl>(Member)) {
10610 CXXRecordDecl *PrevRecord;
10611 if (Previous.isSingleResult() &&
10612 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
10613 FoundInstantiation = Previous.getRepresentativeDecl();
10614 Instantiation = PrevRecord;
10615 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10616 MSInfo = PrevRecord->getMemberSpecializationInfo();
10617 }
10618 } else if (isa<EnumDecl>(Member)) {
10619 EnumDecl *PrevEnum;
10620 if (Previous.isSingleResult() &&
10621 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
10622 FoundInstantiation = Previous.getRepresentativeDecl();
10623 Instantiation = PrevEnum;
10624 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10625 MSInfo = PrevEnum->getMemberSpecializationInfo();
10626 }
10627 }
10628
10629 if (!Instantiation) {
10630 // There is no previous declaration that matches. Since member
10631 // specializations are always out-of-line, the caller will complain about
10632 // this mismatch later.
10633 return false;
10634 }
10635
10636 // A member specialization in a friend declaration isn't really declaring
10637 // an explicit specialization, just identifying a specific (possibly implicit)
10638 // specialization. Don't change the template specialization kind.
10639 //
10640 // FIXME: Is this really valid? Other compilers reject.
10641 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10642 // Preserve instantiation information.
10643 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10644 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10645 cast<CXXMethodDecl>(InstantiatedFrom),
10646 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
10647 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10648 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10649 cast<CXXRecordDecl>(InstantiatedFrom),
10650 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
10651 }
10652
10653 Previous.clear();
10654 Previous.addDecl(FoundInstantiation);
10655 return false;
10656 }
10657
10658 // Make sure that this is a specialization of a member.
10659 if (!InstantiatedFrom) {
10660 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10661 << Member;
10662 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10663 return true;
10664 }
10665
10666 // C++ [temp.expl.spec]p6:
10667 // If a template, a member template or the member of a class template is
10668 // explicitly specialized then that specialization shall be declared
10669 // before the first use of that specialization that would cause an implicit
10670 // instantiation to take place, in every translation unit in which such a
10671 // use occurs; no diagnostic is required.
10672 assert(MSInfo && "Member specialization info missing?");
10673
10674 bool HasNoEffect = false;
10677 Instantiation,
10679 MSInfo->getPointOfInstantiation(),
10680 HasNoEffect))
10681 return true;
10682
10683 // Check the scope of this explicit specialization.
10685 InstantiatedFrom,
10686 Instantiation, Member->getLocation(),
10687 false))
10688 return true;
10689
10690 // Note that this member specialization is an "instantiation of" the
10691 // corresponding member of the original template.
10692 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10693 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10694 if (InstantiationFunction->getTemplateSpecializationKind() ==
10696 // Explicit specializations of member functions of class templates do not
10697 // inherit '=delete' from the member function they are specializing.
10698 if (InstantiationFunction->isDeleted()) {
10699 // FIXME: This assert will not hold in the presence of modules.
10700 assert(InstantiationFunction->getCanonicalDecl() ==
10701 InstantiationFunction);
10702 // FIXME: We need an update record for this AST mutation.
10703 InstantiationFunction->setDeletedAsWritten(false);
10704 }
10705 }
10706
10707 MemberFunction->setInstantiationOfMemberFunction(
10708 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10709 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10710 MemberVar->setInstantiationOfStaticDataMember(
10711 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10712 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10713 MemberClass->setInstantiationOfMemberClass(
10714 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10715 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10716 MemberEnum->setInstantiationOfMemberEnum(
10717 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10718 } else {
10719 llvm_unreachable("unknown member specialization kind");
10720 }
10721
10722 // Save the caller the trouble of having to figure out which declaration
10723 // this specialization matches.
10724 Previous.clear();
10725 Previous.addDecl(FoundInstantiation);
10726 return false;
10727}
10728
10729/// Complete the explicit specialization of a member of a class template by
10730/// updating the instantiated member to be marked as an explicit specialization.
10731///
10732/// \param OrigD The member declaration instantiated from the template.
10733/// \param Loc The location of the explicit specialization of the member.
10734template<typename DeclT>
10735static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10737 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10738 return;
10739
10740 // FIXME: Inform AST mutation listeners of this AST mutation.
10741 // FIXME: If there are multiple in-class declarations of the member (from
10742 // multiple modules, or a declaration and later definition of a member type),
10743 // should we update all of them?
10744 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10745 OrigD->setLocation(Loc);
10746}
10747
10750 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10751 if (Instantiation == Member)
10752 return;
10753
10754 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10755 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10756 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10757 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10758 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10759 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10760 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10761 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10762 else
10763 llvm_unreachable("unknown member specialization kind");
10764}
10765
10766/// Check the scope of an explicit instantiation.
10767///
10768/// \returns true if a serious error occurs, false otherwise.
10770 SourceLocation InstLoc,
10771 bool WasQualifiedName) {
10773 DeclContext *CurContext = S.CurContext->getRedeclContext();
10774
10775 if (CurContext->isRecord()) {
10776 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10777 << D;
10778 return true;
10779 }
10780
10781 // C++11 [temp.explicit]p3:
10782 // An explicit instantiation shall appear in an enclosing namespace of its
10783 // template. If the name declared in the explicit instantiation is an
10784 // unqualified name, the explicit instantiation shall appear in the
10785 // namespace where its template is declared or, if that namespace is inline
10786 // (7.3.1), any namespace from its enclosing namespace set.
10787 //
10788 // This is DR275, which we do not retroactively apply to C++98/03.
10789 if (WasQualifiedName) {
10790 if (CurContext->Encloses(OrigContext))
10791 return false;
10792 } else {
10793 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10794 return false;
10795 }
10796
10797 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10798 if (WasQualifiedName)
10799 S.Diag(InstLoc,
10800 S.getLangOpts().CPlusPlus11?
10801 diag::err_explicit_instantiation_out_of_scope :
10802 diag::warn_explicit_instantiation_out_of_scope_0x)
10803 << D << NS;
10804 else
10805 S.Diag(InstLoc,
10806 S.getLangOpts().CPlusPlus11?
10807 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10808 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10809 << D << NS;
10810 } else
10811 S.Diag(InstLoc,
10812 S.getLangOpts().CPlusPlus11?
10813 diag::err_explicit_instantiation_must_be_global :
10814 diag::warn_explicit_instantiation_must_be_global_0x)
10815 << D;
10816 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10817 return false;
10818}
10819
10820/// Common checks for whether an explicit instantiation of \p D is valid.
10822 SourceLocation InstLoc,
10823 bool WasQualifiedName,
10825 // C++ [temp.explicit]p13:
10826 // An explicit instantiation declaration shall not name a specialization of
10827 // a template with internal linkage.
10830 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10831 return true;
10832 }
10833
10834 // C++11 [temp.explicit]p3: [DR 275]
10835 // An explicit instantiation shall appear in an enclosing namespace of its
10836 // template.
10837 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10838 return true;
10839
10840 return false;
10841}
10842
10843/// Determine whether the given scope specifier has a template-id in it.
10845 if (!SS.isSet())
10846 return false;
10847
10848 // C++11 [temp.explicit]p3:
10849 // If the explicit instantiation is for a member function, a member class
10850 // or a static data member of a class template specialization, the name of
10851 // the class template specialization in the qualified-id for the member
10852 // name shall be a simple-template-id.
10853 //
10854 // C++98 has the same restriction, just worded differently.
10855 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
10856 NNS = NNS->getPrefix())
10857 if (const Type *T = NNS->getAsType())
10858 if (isa<TemplateSpecializationType>(T))
10859 return true;
10860
10861 return false;
10862}
10863
10864/// Make a dllexport or dllimport attr on a class template specialization take
10865/// effect.
10868 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10869 assert(A && "dllExportImportClassTemplateSpecialization called "
10870 "on Def without dllexport or dllimport");
10871
10872 // We reject explicit instantiations in class scope, so there should
10873 // never be any delayed exported classes to worry about.
10874 assert(S.DelayedDllExportClasses.empty() &&
10875 "delayed exports present at explicit instantiation");
10877
10878 // Propagate attribute to base class templates.
10879 for (auto &B : Def->bases()) {
10880 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10881 B.getType()->getAsCXXRecordDecl()))
10883 }
10884
10886}
10887
10888// Explicit instantiation of a class template specialization
10890 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10891 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10892 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10893 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10894 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10895 // Find the class template we're specializing
10896 TemplateName Name = TemplateD.get();
10897 TemplateDecl *TD = Name.getAsTemplateDecl();
10898 // Check that the specialization uses the same tag kind as the
10899 // original template.
10901 assert(Kind != TagTypeKind::Enum &&
10902 "Invalid enum tag in class template explicit instantiation!");
10903
10904 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10905
10906 if (!ClassTemplate) {
10907 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10908 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
10909 << TD << NTK << llvm::to_underlying(Kind);
10910 Diag(TD->getLocation(), diag::note_previous_use);
10911 return true;
10912 }
10913
10914 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10915 Kind, /*isDefinition*/false, KWLoc,
10916 ClassTemplate->getIdentifier())) {
10917 Diag(KWLoc, diag::err_use_with_wrong_tag)
10918 << ClassTemplate
10920 ClassTemplate->getTemplatedDecl()->getKindName());
10921 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10922 diag::note_previous_use);
10923 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10924 }
10925
10926 // C++0x [temp.explicit]p2:
10927 // There are two forms of explicit instantiation: an explicit instantiation
10928 // definition and an explicit instantiation declaration. An explicit
10929 // instantiation declaration begins with the extern keyword. [...]
10930 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10933
10935 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10936 // Check for dllexport class template instantiation declarations,
10937 // except for MinGW mode.
10938 for (const ParsedAttr &AL : Attr) {
10939 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10940 Diag(ExternLoc,
10941 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10942 Diag(AL.getLoc(), diag::note_attribute);
10943 break;
10944 }
10945 }
10946
10947 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10948 Diag(ExternLoc,
10949 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10950 Diag(A->getLocation(), diag::note_attribute);
10951 }
10952 }
10953
10954 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10955 // instantiation declarations for most purposes.
10956 bool DLLImportExplicitInstantiationDef = false;
10959 // Check for dllimport class template instantiation definitions.
10960 bool DLLImport =
10961 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10962 for (const ParsedAttr &AL : Attr) {
10963 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10964 DLLImport = true;
10965 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10966 // dllexport trumps dllimport here.
10967 DLLImport = false;
10968 break;
10969 }
10970 }
10971 if (DLLImport) {
10973 DLLImportExplicitInstantiationDef = true;
10974 }
10975 }
10976
10977 // Translate the parser's template argument list in our AST format.
10978 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10979 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10980
10981 // Check that the template argument list is well-formed for this
10982 // template.
10983 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
10984 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10985 false, SugaredConverted, CanonicalConverted,
10986 /*UpdateArgsWithConversions=*/true))
10987 return true;
10988
10989 // Find the class template specialization declaration that
10990 // corresponds to these arguments.
10991 void *InsertPos = nullptr;
10993 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
10994
10995 TemplateSpecializationKind PrevDecl_TSK
10996 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10997
10998 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10999 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
11000 // Check for dllexport class template instantiation definitions in MinGW
11001 // mode, if a previous declaration of the instantiation was seen.
11002 for (const ParsedAttr &AL : Attr) {
11003 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
11004 Diag(AL.getLoc(),
11005 diag::warn_attribute_dllexport_explicit_instantiation_def);
11006 break;
11007 }
11008 }
11009 }
11010
11011 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
11012 SS.isSet(), TSK))
11013 return true;
11014
11016
11017 bool HasNoEffect = false;
11018 if (PrevDecl) {
11019 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
11020 PrevDecl, PrevDecl_TSK,
11021 PrevDecl->getPointOfInstantiation(),
11022 HasNoEffect))
11023 return PrevDecl;
11024
11025 // Even though HasNoEffect == true means that this explicit instantiation
11026 // has no effect on semantics, we go on to put its syntax in the AST.
11027
11028 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
11029 PrevDecl_TSK == TSK_Undeclared) {
11030 // Since the only prior class template specialization with these
11031 // arguments was referenced but not declared, reuse that
11032 // declaration node as our own, updating the source location
11033 // for the template name to reflect our new declaration.
11034 // (Other source locations will be updated later.)
11035 Specialization = PrevDecl;
11036 Specialization->setLocation(TemplateNameLoc);
11037 PrevDecl = nullptr;
11038 }
11039
11040 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
11041 DLLImportExplicitInstantiationDef) {
11042 // The new specialization might add a dllimport attribute.
11043 HasNoEffect = false;
11044 }
11045 }
11046
11047 if (!Specialization) {
11048 // Create a new class template specialization declaration node for
11049 // this explicit specialization.
11051 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
11052 ClassTemplate, CanonicalConverted, PrevDecl);
11054
11055 // A MSInheritanceAttr attached to the previous declaration must be
11056 // propagated to the new node prior to instantiation.
11057 if (PrevDecl) {
11058 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
11059 auto *Clone = A->clone(getASTContext());
11060 Clone->setInherited(true);
11061 Specialization->addAttr(Clone);
11063 }
11064 }
11065
11066 if (!HasNoEffect && !PrevDecl) {
11067 // Insert the new specialization.
11068 ClassTemplate->AddSpecialization(Specialization, InsertPos);
11069 }
11070 }
11071
11072 Specialization->setTemplateArgsAsWritten(TemplateArgs);
11073
11074 // Set source locations for keywords.
11075 Specialization->setExternKeywordLoc(ExternLoc);
11076 Specialization->setTemplateKeywordLoc(TemplateLoc);
11077 Specialization->setBraceRange(SourceRange());
11078
11079 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
11082
11083 // Add the explicit instantiation into its lexical context. However,
11084 // since explicit instantiations are never found by name lookup, we
11085 // just put it into the declaration context directly.
11086 Specialization->setLexicalDeclContext(CurContext);
11088
11089 // Syntax is now OK, so return if it has no other effect on semantics.
11090 if (HasNoEffect) {
11091 // Set the template specialization kind.
11092 Specialization->setTemplateSpecializationKind(TSK);
11093 return Specialization;
11094 }
11095
11096 // C++ [temp.explicit]p3:
11097 // A definition of a class template or class member template
11098 // shall be in scope at the point of the explicit instantiation of
11099 // the class template or class member template.
11100 //
11101 // This check comes when we actually try to perform the
11102 // instantiation.
11104 = cast_or_null<ClassTemplateSpecializationDecl>(
11105 Specialization->getDefinition());
11106 if (!Def)
11108 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11109 MarkVTableUsed(TemplateNameLoc, Specialization, true);
11110 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
11111 }
11112
11113 // Instantiate the members of this class template specialization.
11114 Def = cast_or_null<ClassTemplateSpecializationDecl>(
11115 Specialization->getDefinition());
11116 if (Def) {
11118 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
11119 // TSK_ExplicitInstantiationDefinition
11120 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
11122 DLLImportExplicitInstantiationDef)) {
11123 // FIXME: Need to notify the ASTMutationListener that we did this.
11125
11126 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
11128 !Context.getTargetInfo().getTriple().isPS())) {
11129 // An explicit instantiation definition can add a dll attribute to a
11130 // template with a previous instantiation declaration. MinGW doesn't
11131 // allow this.
11132 auto *A = cast<InheritableAttr>(
11134 A->setInherited(true);
11135 Def->addAttr(A);
11137 }
11138 }
11139
11140 // Fix a TSK_ImplicitInstantiation followed by a
11141 // TSK_ExplicitInstantiationDefinition
11142 bool NewlyDLLExported =
11143 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
11144 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
11146 !Context.getTargetInfo().getTriple().isPS())) {
11147 // An explicit instantiation definition can add a dll attribute to a
11148 // template with a previous implicit instantiation. MinGW doesn't allow
11149 // this. We limit clang to only adding dllexport, to avoid potentially
11150 // strange codegen behavior. For example, if we extend this conditional
11151 // to dllimport, and we have a source file calling a method on an
11152 // implicitly instantiated template class instance and then declaring a
11153 // dllimport explicit instantiation definition for the same template
11154 // class, the codegen for the method call will not respect the dllimport,
11155 // while it will with cl. The Def will already have the DLL attribute,
11156 // since the Def and Specialization will be the same in the case of
11157 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
11158 // attribute to the Specialization; we just need to make it take effect.
11159 assert(Def == Specialization &&
11160 "Def and Specialization should match for implicit instantiation");
11162 }
11163
11164 // In MinGW mode, export the template instantiation if the declaration
11165 // was marked dllexport.
11166 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
11167 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
11168 PrevDecl->hasAttr<DLLExportAttr>()) {
11170 }
11171
11172 // Set the template specialization kind. Make sure it is set before
11173 // instantiating the members which will trigger ASTConsumer callbacks.
11174 Specialization->setTemplateSpecializationKind(TSK);
11175 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
11176 } else {
11177
11178 // Set the template specialization kind.
11179 Specialization->setTemplateSpecializationKind(TSK);
11180 }
11181
11182 return Specialization;
11183}
11184
11185// Explicit instantiation of a member class of a class template.
11188 SourceLocation TemplateLoc, unsigned TagSpec,
11189 SourceLocation KWLoc, CXXScopeSpec &SS,
11190 IdentifierInfo *Name, SourceLocation NameLoc,
11191 const ParsedAttributesView &Attr) {
11192
11193 bool Owned = false;
11194 bool IsDependent = false;
11195 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
11196 NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
11197 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
11198 false, TypeResult(), /*IsTypeSpecifier*/ false,
11199 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
11200 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
11201
11202 if (!TagD)
11203 return true;
11204
11205 TagDecl *Tag = cast<TagDecl>(TagD);
11206 assert(!Tag->isEnum() && "shouldn't see enumerations here");
11207
11208 if (Tag->isInvalidDecl())
11209 return true;
11210
11211 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
11212 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
11213 if (!Pattern) {
11214 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
11216 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
11217 return true;
11218 }
11219
11220 // C++0x [temp.explicit]p2:
11221 // If the explicit instantiation is for a class or member class, the
11222 // elaborated-type-specifier in the declaration shall include a
11223 // simple-template-id.
11224 //
11225 // C++98 has the same restriction, just worded differently.
11227 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
11228 << Record << SS.getRange();
11229
11230 // C++0x [temp.explicit]p2:
11231 // There are two forms of explicit instantiation: an explicit instantiation
11232 // definition and an explicit instantiation declaration. An explicit
11233 // instantiation declaration begins with the extern keyword. [...]
11237
11238 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
11239
11240 // Verify that it is okay to explicitly instantiate here.
11241 CXXRecordDecl *PrevDecl
11242 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
11243 if (!PrevDecl && Record->getDefinition())
11244 PrevDecl = Record;
11245 if (PrevDecl) {
11247 bool HasNoEffect = false;
11248 assert(MSInfo && "No member specialization information?");
11249 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
11250 PrevDecl,
11252 MSInfo->getPointOfInstantiation(),
11253 HasNoEffect))
11254 return true;
11255 if (HasNoEffect)
11256 return TagD;
11257 }
11258
11259 CXXRecordDecl *RecordDef
11260 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
11261 if (!RecordDef) {
11262 // C++ [temp.explicit]p3:
11263 // A definition of a member class of a class template shall be in scope
11264 // at the point of an explicit instantiation of the member class.
11265 CXXRecordDecl *Def
11266 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
11267 if (!Def) {
11268 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
11269 << 0 << Record->getDeclName() << Record->getDeclContext();
11270 Diag(Pattern->getLocation(), diag::note_forward_declaration)
11271 << Pattern;
11272 return true;
11273 } else {
11274 if (InstantiateClass(NameLoc, Record, Def,
11276 TSK))
11277 return true;
11278
11279 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
11280 if (!RecordDef)
11281 return true;
11282 }
11283 }
11284
11285 // Instantiate all of the members of the class.
11286 InstantiateClassMembers(NameLoc, RecordDef,
11288
11290 MarkVTableUsed(NameLoc, RecordDef, true);
11291
11292 // FIXME: We don't have any representation for explicit instantiations of
11293 // member classes. Such a representation is not needed for compilation, but it
11294 // should be available for clients that want to see all of the declarations in
11295 // the source code.
11296 return TagD;
11297}
11298
11300 SourceLocation ExternLoc,
11301 SourceLocation TemplateLoc,
11302 Declarator &D) {
11303 // Explicit instantiations always require a name.
11304 // TODO: check if/when DNInfo should replace Name.
11306 DeclarationName Name = NameInfo.getName();
11307 if (!Name) {
11308 if (!D.isInvalidType())
11310 diag::err_explicit_instantiation_requires_name)
11312
11313 return true;
11314 }
11315
11316 // Get the innermost enclosing declaration scope.
11317 S = S->getDeclParent();
11318
11319 // Determine the type of the declaration.
11321 QualType R = T->getType();
11322 if (R.isNull())
11323 return true;
11324
11325 // C++ [dcl.stc]p1:
11326 // A storage-class-specifier shall not be specified in [...] an explicit
11327 // instantiation (14.7.2) directive.
11329 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
11330 << Name;
11331 return true;
11332 } else if (D.getDeclSpec().getStorageClassSpec()
11334 // Complain about then remove the storage class specifier.
11335 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
11337
11339 }
11340
11341 // C++0x [temp.explicit]p1:
11342 // [...] An explicit instantiation of a function template shall not use the
11343 // inline or constexpr specifiers.
11344 // Presumably, this also applies to member functions of class templates as
11345 // well.
11349 diag::err_explicit_instantiation_inline :
11350 diag::warn_explicit_instantiation_inline_0x)
11353 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
11354 // not already specified.
11356 diag::err_explicit_instantiation_constexpr);
11357
11358 // A deduction guide is not on the list of entities that can be explicitly
11359 // instantiated.
11360 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
11361 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
11362 << /*explicit instantiation*/ 0;
11363 return true;
11364 }
11365
11366 // C++0x [temp.explicit]p2:
11367 // There are two forms of explicit instantiation: an explicit instantiation
11368 // definition and an explicit instantiation declaration. An explicit
11369 // instantiation declaration begins with the extern keyword. [...]
11373
11374 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
11376 /*ObjectType=*/QualType());
11377
11378 if (!R->isFunctionType()) {
11379 // C++ [temp.explicit]p1:
11380 // A [...] static data member of a class template can be explicitly
11381 // instantiated from the member definition associated with its class
11382 // template.
11383 // C++1y [temp.explicit]p1:
11384 // A [...] variable [...] template specialization can be explicitly
11385 // instantiated from its template.
11386 if (Previous.isAmbiguous())
11387 return true;
11388
11389 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
11390 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
11391
11392 if (!PrevTemplate) {
11393 if (!Prev || !Prev->isStaticDataMember()) {
11394 // We expect to see a static data member here.
11395 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
11396 << Name;
11397 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11398 P != PEnd; ++P)
11399 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
11400 return true;
11401 }
11402
11404 // FIXME: Check for explicit specialization?
11406 diag::err_explicit_instantiation_data_member_not_instantiated)
11407 << Prev;
11408 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
11409 // FIXME: Can we provide a note showing where this was declared?
11410 return true;
11411 }
11412 } else {
11413 // Explicitly instantiate a variable template.
11414
11415 // C++1y [dcl.spec.auto]p6:
11416 // ... A program that uses auto or decltype(auto) in a context not
11417 // explicitly allowed in this section is ill-formed.
11418 //
11419 // This includes auto-typed variable template instantiations.
11420 if (R->isUndeducedType()) {
11421 Diag(T->getTypeLoc().getBeginLoc(),
11422 diag::err_auto_not_allowed_var_inst);
11423 return true;
11424 }
11425
11427 // C++1y [temp.explicit]p3:
11428 // If the explicit instantiation is for a variable, the unqualified-id
11429 // in the declaration shall be a template-id.
11431 diag::err_explicit_instantiation_without_template_id)
11432 << PrevTemplate;
11433 Diag(PrevTemplate->getLocation(),
11434 diag::note_explicit_instantiation_here);
11435 return true;
11436 }
11437
11438 // Translate the parser's template argument list into our AST format.
11439 TemplateArgumentListInfo TemplateArgs =
11441
11442 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
11443 D.getIdentifierLoc(), TemplateArgs);
11444 if (Res.isInvalid())
11445 return true;
11446
11447 if (!Res.isUsable()) {
11448 // We somehow specified dependent template arguments in an explicit
11449 // instantiation. This should probably only happen during error
11450 // recovery.
11451 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
11452 return true;
11453 }
11454
11455 // Ignore access control bits, we don't need them for redeclaration
11456 // checking.
11457 Prev = cast<VarDecl>(Res.get());
11458 }
11459
11460 // C++0x [temp.explicit]p2:
11461 // If the explicit instantiation is for a member function, a member class
11462 // or a static data member of a class template specialization, the name of
11463 // the class template specialization in the qualified-id for the member
11464 // name shall be a simple-template-id.
11465 //
11466 // C++98 has the same restriction, just worded differently.
11467 //
11468 // This does not apply to variable template specializations, where the
11469 // template-id is in the unqualified-id instead.
11470 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
11472 diag::ext_explicit_instantiation_without_qualified_id)
11473 << Prev << D.getCXXScopeSpec().getRange();
11474
11475 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
11476
11477 // Verify that it is okay to explicitly instantiate here.
11480 bool HasNoEffect = false;
11482 PrevTSK, POI, HasNoEffect))
11483 return true;
11484
11485 if (!HasNoEffect) {
11486 // Instantiate static data member or variable template.
11488 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
11489 VTSD->setExternKeywordLoc(ExternLoc);
11490 VTSD->setTemplateKeywordLoc(TemplateLoc);
11491 }
11492
11493 // Merge attributes.
11495 if (PrevTemplate)
11496 ProcessAPINotes(Prev);
11497
11500 }
11501
11502 // Check the new variable specialization against the parsed input.
11503 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
11504 Diag(T->getTypeLoc().getBeginLoc(),
11505 diag::err_invalid_var_template_spec_type)
11506 << 0 << PrevTemplate << R << Prev->getType();
11507 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
11508 << 2 << PrevTemplate->getDeclName();
11509 return true;
11510 }
11511
11512 // FIXME: Create an ExplicitInstantiation node?
11513 return (Decl*) nullptr;
11514 }
11515
11516 // If the declarator is a template-id, translate the parser's template
11517 // argument list into our AST format.
11518 bool HasExplicitTemplateArgs = false;
11519 TemplateArgumentListInfo TemplateArgs;
11521 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
11522 HasExplicitTemplateArgs = true;
11523 }
11524
11525 // C++ [temp.explicit]p1:
11526 // A [...] function [...] can be explicitly instantiated from its template.
11527 // A member function [...] of a class template can be explicitly
11528 // instantiated from the member definition associated with its class
11529 // template.
11530 UnresolvedSet<8> TemplateMatches;
11531 FunctionDecl *NonTemplateMatch = nullptr;
11532 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
11533 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11534 P != PEnd; ++P) {
11535 NamedDecl *Prev = *P;
11536 if (!HasExplicitTemplateArgs) {
11537 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
11538 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
11539 /*AdjustExceptionSpec*/true);
11540 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
11541 if (Method->getPrimaryTemplate()) {
11542 TemplateMatches.addDecl(Method, P.getAccess());
11543 } else {
11544 // FIXME: Can this assert ever happen? Needs a test.
11545 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
11546 NonTemplateMatch = Method;
11547 }
11548 }
11549 }
11550 }
11551
11552 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
11553 if (!FunTmpl)
11554 continue;
11555
11556 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11557 FunctionDecl *Specialization = nullptr;
11559 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
11560 Specialization, Info);
11562 // Keep track of almost-matches.
11563 FailedCandidates.addCandidate()
11564 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
11565 MakeDeductionFailureInfo(Context, TDK, Info));
11566 (void)TDK;
11567 continue;
11568 }
11569
11570 // Target attributes are part of the cuda function signature, so
11571 // the cuda target of the instantiated function must match that of its
11572 // template. Given that C++ template deduction does not take
11573 // target attributes into account, we reject candidates here that
11574 // have a different target.
11575 if (LangOpts.CUDA &&
11577 /* IgnoreImplicitHDAttr = */ true) !=
11579 FailedCandidates.addCandidate().set(
11580 P.getPair(), FunTmpl->getTemplatedDecl(),
11583 continue;
11584 }
11585
11586 TemplateMatches.addDecl(Specialization, P.getAccess());
11587 }
11588
11589 FunctionDecl *Specialization = NonTemplateMatch;
11590 if (!Specialization) {
11591 // Find the most specialized function template specialization.
11593 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
11594 D.getIdentifierLoc(),
11595 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11596 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11597 PDiag(diag::note_explicit_instantiation_candidate));
11598
11599 if (Result == TemplateMatches.end())
11600 return true;
11601
11602 // Ignore access control bits, we don't need them for redeclaration checking.
11603 Specialization = cast<FunctionDecl>(*Result);
11604 }
11605
11606 // C++11 [except.spec]p4
11607 // In an explicit instantiation an exception-specification may be specified,
11608 // but is not required.
11609 // If an exception-specification is specified in an explicit instantiation
11610 // directive, it shall be compatible with the exception-specifications of
11611 // other declarations of that function.
11612 if (auto *FPT = R->getAs<FunctionProtoType>())
11613 if (FPT->hasExceptionSpec()) {
11614 unsigned DiagID =
11615 diag::err_mismatched_exception_spec_explicit_instantiation;
11616 if (getLangOpts().MicrosoftExt)
11617 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11619 PDiag(DiagID) << Specialization->getType(),
11620 PDiag(diag::note_explicit_instantiation_here),
11621 Specialization->getType()->getAs<FunctionProtoType>(),
11622 Specialization->getLocation(), FPT, D.getBeginLoc());
11623 // In Microsoft mode, mismatching exception specifications just cause a
11624 // warning.
11625 if (!getLangOpts().MicrosoftExt && Result)
11626 return true;
11627 }
11628
11629 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11631 diag::err_explicit_instantiation_member_function_not_instantiated)
11633 << (Specialization->getTemplateSpecializationKind() ==
11635 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11636 return true;
11637 }
11638
11639 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11640 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11641 PrevDecl = Specialization;
11642
11643 if (PrevDecl) {
11644 bool HasNoEffect = false;
11646 PrevDecl,
11648 PrevDecl->getPointOfInstantiation(),
11649 HasNoEffect))
11650 return true;
11651
11652 // FIXME: We may still want to build some representation of this
11653 // explicit specialization.
11654 if (HasNoEffect)
11655 return (Decl*) nullptr;
11656 }
11657
11658 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11659 // functions
11660 // valarray<size_t>::valarray(size_t) and
11661 // valarray<size_t>::~valarray()
11662 // that it declared to have internal linkage with the internal_linkage
11663 // attribute. Ignore the explicit instantiation declaration in this case.
11664 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11666 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11667 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11668 RD->isInStdNamespace())
11669 return (Decl*) nullptr;
11670 }
11671
11674
11675 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11676 // instantiation declarations.
11678 Specialization->hasAttr<DLLImportAttr>() &&
11681
11682 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11683
11684 if (Specialization->isDefined()) {
11685 // Let the ASTConsumer know that this function has been explicitly
11686 // instantiated now, and its linkage might have changed.
11688 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11690
11691 // C++0x [temp.explicit]p2:
11692 // If the explicit instantiation is for a member function, a member class
11693 // or a static data member of a class template specialization, the name of
11694 // the class template specialization in the qualified-id for the member
11695 // name shall be a simple-template-id.
11696 //
11697 // C++98 has the same restriction, just worded differently.
11698 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11699 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11700 D.getCXXScopeSpec().isSet() &&
11703 diag::ext_explicit_instantiation_without_qualified_id)
11705
11707 *this,
11708 FunTmpl ? (NamedDecl *)FunTmpl
11709 : Specialization->getInstantiatedFromMemberFunction(),
11710 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11711
11712 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11713 return (Decl*) nullptr;
11714}
11715
11717 const CXXScopeSpec &SS,
11718 const IdentifierInfo *Name,
11719 SourceLocation TagLoc,
11720 SourceLocation NameLoc) {
11721 // This has to hold, because SS is expected to be defined.
11722 assert(Name && "Expected a name in a dependent tag");
11723
11724 NestedNameSpecifier *NNS = SS.getScopeRep();
11725 if (!NNS)
11726 return true;
11727
11729
11730 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
11731 Diag(NameLoc, diag::err_dependent_tag_decl)
11732 << (TUK == TUK_Definition) << llvm::to_underlying(Kind)
11733 << SS.getRange();
11734 return true;
11735 }
11736
11737 // Create the resulting type.
11739 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11740
11741 // Create type-source location information for this type.
11742 TypeLocBuilder TLB;
11744 TL.setElaboratedKeywordLoc(TagLoc);
11746 TL.setNameLoc(NameLoc);
11748}
11749
11751 const CXXScopeSpec &SS,
11752 const IdentifierInfo &II,
11753 SourceLocation IdLoc,
11754 ImplicitTypenameContext IsImplicitTypename) {
11755 if (SS.isInvalid())
11756 return true;
11757
11758 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11759 Diag(TypenameLoc,
11761 diag::warn_cxx98_compat_typename_outside_of_template :
11762 diag::ext_typename_outside_of_template)
11763 << FixItHint::CreateRemoval(TypenameLoc);
11764
11766 TypeSourceInfo *TSI = nullptr;
11767 QualType T =
11768 CheckTypenameType((TypenameLoc.isValid() ||
11769 IsImplicitTypename == ImplicitTypenameContext::Yes)
11772 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11773 /*DeducedTSTContext=*/true);
11774 if (T.isNull())
11775 return true;
11776 return CreateParsedType(T, TSI);
11777}
11778
11781 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11782 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11783 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11784 ASTTemplateArgsPtr TemplateArgsIn,
11785 SourceLocation RAngleLoc) {
11786 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11787 Diag(TypenameLoc,
11789 diag::warn_cxx98_compat_typename_outside_of_template :
11790 diag::ext_typename_outside_of_template)
11791 << FixItHint::CreateRemoval(TypenameLoc);
11792
11793 // Strangely, non-type results are not ignored by this lookup, so the
11794 // program is ill-formed if it finds an injected-class-name.
11795 if (TypenameLoc.isValid()) {
11796 auto *LookupRD =
11797 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11798 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11799 Diag(TemplateIILoc,
11800 diag::ext_out_of_line_qualified_id_type_names_constructor)
11801 << TemplateII << 0 /*injected-class-name used as template name*/
11802 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11803 }
11804 }
11805
11806 // Translate the parser's template argument list in our AST format.
11807 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11808 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11809
11810 TemplateName Template = TemplateIn.get();
11811 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
11812 // Construct a dependent template specialization type.
11813 assert(DTN && "dependent template has non-dependent name?");
11814 assert(DTN->getQualifier() == SS.getScopeRep());
11816 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
11817 DTN->getIdentifier(), TemplateArgs.arguments());
11818
11819 // Create source-location information for this type.
11820 TypeLocBuilder Builder;
11823 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
11825 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11826 SpecTL.setTemplateNameLoc(TemplateIILoc);
11827 SpecTL.setLAngleLoc(LAngleLoc);
11828 SpecTL.setRAngleLoc(RAngleLoc);
11829 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11830 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11831 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
11832 }
11833
11834 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
11835 if (T.isNull())
11836 return true;
11837
11838 // Provide source-location information for the template specialization type.
11839 TypeLocBuilder Builder;
11841 = Builder.push<TemplateSpecializationTypeLoc>(T);
11842 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11843 SpecTL.setTemplateNameLoc(TemplateIILoc);
11844 SpecTL.setLAngleLoc(LAngleLoc);
11845 SpecTL.setRAngleLoc(RAngleLoc);
11846 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11847 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11848
11850 SS.getScopeRep(), T);
11851 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
11852 TL.setElaboratedKeywordLoc(TypenameLoc);
11854
11855 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11856 return CreateParsedType(T, TSI);
11857}
11858
11859/// Determine whether this failed name lookup should be treated as being
11860/// disabled by a usage of std::enable_if.
11862 SourceRange &CondRange, Expr *&Cond) {
11863 // We must be looking for a ::type...
11864 if (!II.isStr("type"))
11865 return false;
11866
11867 // ... within an explicitly-written template specialization...
11868 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
11869 return false;
11870 TypeLoc EnableIfTy = NNS.getTypeLoc();
11871 TemplateSpecializationTypeLoc EnableIfTSTLoc =
11873 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11874 return false;
11875 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11876
11877 // ... which names a complete class template declaration...
11878 const TemplateDecl *EnableIfDecl =
11879 EnableIfTST->getTemplateName().getAsTemplateDecl();
11880 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11881 return false;
11882
11883 // ... called "enable_if".
11884 const IdentifierInfo *EnableIfII =
11885 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11886 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11887 return false;
11888
11889 // Assume the first template argument is the condition.
11890 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11891
11892 // Dig out the condition.
11893 Cond = nullptr;
11894 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11896 return true;
11897
11898 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11899
11900 // Ignore Boolean literals; they add no value.
11901 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11902 Cond = nullptr;
11903
11904 return true;
11905}
11906
11909 SourceLocation KeywordLoc,
11910 NestedNameSpecifierLoc QualifierLoc,
11911 const IdentifierInfo &II,
11912 SourceLocation IILoc,
11913 TypeSourceInfo **TSI,
11914 bool DeducedTSTContext) {
11915 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11916 DeducedTSTContext);
11917 if (T.isNull())
11918 return QualType();
11919
11921 if (isa<DependentNameType>(T)) {
11923 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
11924 TL.setElaboratedKeywordLoc(KeywordLoc);
11925 TL.setQualifierLoc(QualifierLoc);
11926 TL.setNameLoc(IILoc);
11927 } else {
11928 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
11929 TL.setElaboratedKeywordLoc(KeywordLoc);
11930 TL.setQualifierLoc(QualifierLoc);
11931 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
11932 }
11933 return T;
11934}
11935
11936/// Build the type that describes a C++ typename specifier,
11937/// e.g., "typename T::type".
11940 SourceLocation KeywordLoc,
11941 NestedNameSpecifierLoc QualifierLoc,
11942 const IdentifierInfo &II,
11943 SourceLocation IILoc, bool DeducedTSTContext) {
11944 CXXScopeSpec SS;
11945 SS.Adopt(QualifierLoc);
11946
11947 DeclContext *Ctx = nullptr;
11948 if (QualifierLoc) {
11949 Ctx = computeDeclContext(SS);
11950 if (!Ctx) {
11951 // If the nested-name-specifier is dependent and couldn't be
11952 // resolved to a type, build a typename type.
11953 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
11954 return Context.getDependentNameType(Keyword,
11955 QualifierLoc.getNestedNameSpecifier(),
11956 &II);
11957 }
11958
11959 // If the nested-name-specifier refers to the current instantiation,
11960 // the "typename" keyword itself is superfluous. In C++03, the
11961 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11962 // allows such extraneous "typename" keywords, and we retroactively
11963 // apply this DR to C++03 code with only a warning. In any case we continue.
11964
11965 if (RequireCompleteDeclContext(SS, Ctx))
11966 return QualType();
11967 }
11968
11969 DeclarationName Name(&II);
11970 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11971 if (Ctx)
11972 LookupQualifiedName(Result, Ctx, SS);
11973 else
11974 LookupName(Result, CurScope);
11975 unsigned DiagID = 0;
11976 Decl *Referenced = nullptr;
11977 switch (Result.getResultKind()) {
11979 // If we're looking up 'type' within a template named 'enable_if', produce
11980 // a more specific diagnostic.
11981 SourceRange CondRange;
11982 Expr *Cond = nullptr;
11983 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11984 // If we have a condition, narrow it down to the specific failed
11985 // condition.
11986 if (Cond) {
11987 Expr *FailedCond;
11988 std::string FailedDescription;
11989 std::tie(FailedCond, FailedDescription) =
11991
11992 Diag(FailedCond->getExprLoc(),
11993 diag::err_typename_nested_not_found_requirement)
11994 << FailedDescription
11995 << FailedCond->getSourceRange();
11996 return QualType();
11997 }
11998
11999 Diag(CondRange.getBegin(),
12000 diag::err_typename_nested_not_found_enable_if)
12001 << Ctx << CondRange;
12002 return QualType();
12003 }
12004
12005 DiagID = Ctx ? diag::err_typename_nested_not_found
12006 : diag::err_unknown_typename;
12007 break;
12008 }
12009
12011 // We found a using declaration that is a value. Most likely, the using
12012 // declaration itself is meant to have the 'typename' keyword.
12013 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
12014 IILoc);
12015 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
12016 << Name << Ctx << FullRange;
12017 if (UnresolvedUsingValueDecl *Using
12018 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
12019 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
12020 Diag(Loc, diag::note_using_value_decl_missing_typename)
12021 << FixItHint::CreateInsertion(Loc, "typename ");
12022 }
12023 }
12024 // Fall through to create a dependent typename type, from which we can recover
12025 // better.
12026 [[fallthrough]];
12027
12029 // Okay, it's a member of an unknown instantiation.
12030 return Context.getDependentNameType(Keyword,
12031 QualifierLoc.getNestedNameSpecifier(),
12032 &II);
12033
12035 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
12036 // C++ [class.qual]p2:
12037 // In a lookup in which function names are not ignored and the
12038 // nested-name-specifier nominates a class C, if the name specified
12039 // after the nested-name-specifier, when looked up in C, is the
12040 // injected-class-name of C [...] then the name is instead considered
12041 // to name the constructor of class C.
12042 //
12043 // Unlike in an elaborated-type-specifier, function names are not ignored
12044 // in typename-specifier lookup. However, they are ignored in all the
12045 // contexts where we form a typename type with no keyword (that is, in
12046 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
12047 //
12048 // FIXME: That's not strictly true: mem-initializer-id lookup does not
12049 // ignore functions, but that appears to be an oversight.
12050 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
12051 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
12052 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
12053 FoundRD->isInjectedClassName() &&
12054 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
12055 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
12056 << &II << 1 << 0 /*'typename' keyword used*/;
12057
12058 // We found a type. Build an ElaboratedType, since the
12059 // typename-specifier was just sugar.
12060 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
12061 return Context.getElaboratedType(Keyword,
12062 QualifierLoc.getNestedNameSpecifier(),
12064 }
12065
12066 // C++ [dcl.type.simple]p2:
12067 // A type-specifier of the form
12068 // typename[opt] nested-name-specifier[opt] template-name
12069 // is a placeholder for a deduced class type [...].
12070 if (getLangOpts().CPlusPlus17) {
12071 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
12072 if (!DeducedTSTContext) {
12073 QualType T(QualifierLoc
12074 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
12075 : nullptr, 0);
12076 if (!T.isNull())
12077 Diag(IILoc, diag::err_dependent_deduced_tst)
12079 else
12080 Diag(IILoc, diag::err_deduced_tst)
12083 return QualType();
12084 }
12086 Keyword, QualifierLoc.getNestedNameSpecifier(),
12088 QualType(), false));
12089 }
12090 }
12091
12092 DiagID = Ctx ? diag::err_typename_nested_not_type
12093 : diag::err_typename_not_type;
12094 Referenced = Result.getFoundDecl();
12095 break;
12096
12098 DiagID = Ctx ? diag::err_typename_nested_not_type
12099 : diag::err_typename_not_type;
12100 Referenced = *Result.begin();
12101 break;
12102
12104 return QualType();
12105 }
12106
12107 // If we get here, it's because name lookup did not find a
12108 // type. Emit an appropriate diagnostic and return an error.
12109 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
12110 IILoc);
12111 if (Ctx)
12112 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
12113 else
12114 Diag(IILoc, DiagID) << FullRange << Name;
12115 if (Referenced)
12116 Diag(Referenced->getLocation(),
12117 Ctx ? diag::note_typename_member_refers_here
12118 : diag::note_typename_refers_here)
12119 << Name;
12120 return QualType();
12121}
12122
12123namespace {
12124 // See Sema::RebuildTypeInCurrentInstantiation
12125 class CurrentInstantiationRebuilder
12126 : public TreeTransform<CurrentInstantiationRebuilder> {
12128 DeclarationName Entity;
12129
12130 public:
12132
12133 CurrentInstantiationRebuilder(Sema &SemaRef,
12135 DeclarationName Entity)
12136 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
12137 Loc(Loc), Entity(Entity) { }
12138
12139 /// Determine whether the given type \p T has already been
12140 /// transformed.
12141 ///
12142 /// For the purposes of type reconstruction, a type has already been
12143 /// transformed if it is NULL or if it is not dependent.
12144 bool AlreadyTransformed(QualType T) {
12145 return T.isNull() || !T->isInstantiationDependentType();
12146 }
12147
12148 /// Returns the location of the entity whose type is being
12149 /// rebuilt.
12150 SourceLocation getBaseLocation() { return Loc; }
12151
12152 /// Returns the name of the entity whose type is being rebuilt.
12153 DeclarationName getBaseEntity() { return Entity; }
12154
12155 /// Sets the "base" location and entity when that
12156 /// information is known based on another transformation.
12157 void setBase(SourceLocation Loc, DeclarationName Entity) {
12158 this->Loc = Loc;
12159 this->Entity = Entity;
12160 }
12161
12162 ExprResult TransformLambdaExpr(LambdaExpr *E) {
12163 // Lambdas never need to be transformed.
12164 return E;
12165 }
12166 };
12167} // end anonymous namespace
12168
12169/// Rebuilds a type within the context of the current instantiation.
12170///
12171/// The type \p T is part of the type of an out-of-line member definition of
12172/// a class template (or class template partial specialization) that was parsed
12173/// and constructed before we entered the scope of the class template (or
12174/// partial specialization thereof). This routine will rebuild that type now
12175/// that we have entered the declarator's scope, which may produce different
12176/// canonical types, e.g.,
12177///
12178/// \code
12179/// template<typename T>
12180/// struct X {
12181/// typedef T* pointer;
12182/// pointer data();
12183/// };
12184///
12185/// template<typename T>
12186/// typename X<T>::pointer X<T>::data() { ... }
12187/// \endcode
12188///
12189/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
12190/// since we do not know that we can look into X<T> when we parsed the type.
12191/// This function will rebuild the type, performing the lookup of "pointer"
12192/// in X<T> and returning an ElaboratedType whose canonical type is the same
12193/// as the canonical type of T*, allowing the return types of the out-of-line
12194/// definition and the declaration to match.
12197 DeclarationName Name) {
12198 if (!T || !T->getType()->isInstantiationDependentType())
12199 return T;
12200
12201 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
12202 return Rebuilder.TransformType(T);
12203}
12204
12206 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
12207 DeclarationName());
12208 return Rebuilder.TransformExpr(E);
12209}
12210
12212 if (SS.isInvalid())
12213 return true;
12214
12216 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
12217 DeclarationName());
12219 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
12220 if (!Rebuilt)
12221 return true;
12222
12223 SS.Adopt(Rebuilt);
12224 return false;
12225}
12226
12227/// Rebuild the template parameters now that we know we're in a current
12228/// instantiation.
12230 TemplateParameterList *Params) {
12231 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
12232 Decl *Param = Params->getParam(I);
12233
12234 // There is nothing to rebuild in a type parameter.
12235 if (isa<TemplateTypeParmDecl>(Param))
12236 continue;
12237
12238 // Rebuild the template parameter list of a template template parameter.
12240 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
12242 TTP->getTemplateParameters()))
12243 return true;
12244
12245 continue;
12246 }
12247
12248 // Rebuild the type of a non-type template parameter.
12249 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
12250 TypeSourceInfo *NewTSI
12252 NTTP->getLocation(),
12253 NTTP->getDeclName());
12254 if (!NewTSI)
12255 return true;
12256
12257 if (NewTSI->getType()->isUndeducedType()) {
12258 // C++17 [temp.dep.expr]p3:
12259 // An id-expression is type-dependent if it contains
12260 // - an identifier associated by name lookup with a non-type
12261 // template-parameter declared with a type that contains a
12262 // placeholder type (7.1.7.4),
12263 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
12264 }
12265
12266 if (NewTSI != NTTP->getTypeSourceInfo()) {
12267 NTTP->setTypeSourceInfo(NewTSI);
12268 NTTP->setType(NewTSI->getType());
12269 }
12270 }
12271
12272 return false;
12273}
12274
12275/// Produces a formatted string that describes the binding of
12276/// template parameters to template arguments.
12277std::string
12279 const TemplateArgumentList &Args) {
12280 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
12281}
12282
12283std::string
12285 const TemplateArgument *Args,
12286 unsigned NumArgs) {
12287 SmallString<128> Str;
12288 llvm::raw_svector_ostream Out(Str);
12289
12290 if (!Params || Params->size() == 0 || NumArgs == 0)
12291 return std::string();
12292
12293 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
12294 if (I >= NumArgs)
12295 break;
12296
12297 if (I == 0)
12298 Out << "[with ";
12299 else
12300 Out << ", ";
12301
12302 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
12303 Out << Id->getName();
12304 } else {
12305 Out << '$' << I;
12306 }
12307
12308 Out << " = ";
12309 Args[I].print(getPrintingPolicy(), Out,
12311 getPrintingPolicy(), Params, I));
12312 }
12313
12314 Out << ']';
12315 return std::string(Out.str());
12316}
12317
12319 CachedTokens &Toks) {
12320 if (!FD)
12321 return;
12322
12323 auto LPT = std::make_unique<LateParsedTemplate>();
12324
12325 // Take tokens to avoid allocations
12326 LPT->Toks.swap(Toks);
12327 LPT->D = FnD;
12328 LPT->FPO = getCurFPFeatures();
12329 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
12330
12331 FD->setLateTemplateParsed(true);
12332}
12333
12335 if (!FD)
12336 return;
12337 FD->setLateTemplateParsed(false);
12338}
12339
12341 DeclContext *DC = CurContext;
12342
12343 while (DC) {
12344 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
12345 const FunctionDecl *FD = RD->isLocalClass();
12346 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
12347 } else if (DC->isTranslationUnit() || DC->isNamespace())
12348 return false;
12349
12350 DC = DC->getParent();
12351 }
12352 return false;
12353}
12354
12355namespace {
12356/// Walk the path from which a declaration was instantiated, and check
12357/// that every explicit specialization along that path is visible. This enforces
12358/// C++ [temp.expl.spec]/6:
12359///
12360/// If a template, a member template or a member of a class template is
12361/// explicitly specialized then that specialization shall be declared before
12362/// the first use of that specialization that would cause an implicit
12363/// instantiation to take place, in every translation unit in which such a
12364/// use occurs; no diagnostic is required.
12365///
12366/// and also C++ [temp.class.spec]/1:
12367///
12368/// A partial specialization shall be declared before the first use of a
12369/// class template specialization that would make use of the partial
12370/// specialization as the result of an implicit or explicit instantiation
12371/// in every translation unit in which such a use occurs; no diagnostic is
12372/// required.
12373class ExplicitSpecializationVisibilityChecker {
12374 Sema &S;
12378
12379public:
12380 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
12382 : S(S), Loc(Loc), Kind(Kind) {}
12383
12384 void check(NamedDecl *ND) {
12385 if (auto *FD = dyn_cast<FunctionDecl>(ND))
12386 return checkImpl(FD);
12387 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
12388 return checkImpl(RD);
12389 if (auto *VD = dyn_cast<VarDecl>(ND))
12390 return checkImpl(VD);
12391 if (auto *ED = dyn_cast<EnumDecl>(ND))
12392 return checkImpl(ED);
12393 }
12394
12395private:
12396 void diagnose(NamedDecl *D, bool IsPartialSpec) {
12397 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
12398 : Sema::MissingImportKind::ExplicitSpecialization;
12399 const bool Recover = true;
12400
12401 // If we got a custom set of modules (because only a subset of the
12402 // declarations are interesting), use them, otherwise let
12403 // diagnoseMissingImport intelligently pick some.
12404 if (Modules.empty())
12405 S.diagnoseMissingImport(Loc, D, Kind, Recover);
12406 else
12407 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
12408 }
12409
12410 bool CheckMemberSpecialization(const NamedDecl *D) {
12411 return Kind == Sema::AcceptableKind::Visible
12414 }
12415
12416 bool CheckExplicitSpecialization(const NamedDecl *D) {
12417 return Kind == Sema::AcceptableKind::Visible
12420 }
12421
12422 bool CheckDeclaration(const NamedDecl *D) {
12423 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
12425 }
12426
12427 // Check a specific declaration. There are three problematic cases:
12428 //
12429 // 1) The declaration is an explicit specialization of a template
12430 // specialization.
12431 // 2) The declaration is an explicit specialization of a member of an
12432 // templated class.
12433 // 3) The declaration is an instantiation of a template, and that template
12434 // is an explicit specialization of a member of a templated class.
12435 //
12436 // We don't need to go any deeper than that, as the instantiation of the
12437 // surrounding class / etc is not triggered by whatever triggered this
12438 // instantiation, and thus should be checked elsewhere.
12439 template<typename SpecDecl>
12440 void checkImpl(SpecDecl *Spec) {
12441 bool IsHiddenExplicitSpecialization = false;
12442 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
12443 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
12444 ? !CheckMemberSpecialization(Spec)
12445 : !CheckExplicitSpecialization(Spec);
12446 } else {
12447 checkInstantiated(Spec);
12448 }
12449
12450 if (IsHiddenExplicitSpecialization)
12451 diagnose(Spec->getMostRecentDecl(), false);
12452 }
12453
12454 void checkInstantiated(FunctionDecl *FD) {
12455 if (auto *TD = FD->getPrimaryTemplate())
12456 checkTemplate(TD);
12457 }
12458
12459 void checkInstantiated(CXXRecordDecl *RD) {
12460 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
12461 if (!SD)
12462 return;
12463
12464 auto From = SD->getSpecializedTemplateOrPartial();
12465 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
12466 checkTemplate(TD);
12467 else if (auto *TD =
12468 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
12469 if (!CheckDeclaration(TD))
12470 diagnose(TD, true);
12471 checkTemplate(TD);
12472 }
12473 }
12474
12475 void checkInstantiated(VarDecl *RD) {
12476 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
12477 if (!SD)
12478 return;
12479
12480 auto From = SD->getSpecializedTemplateOrPartial();
12481 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
12482 checkTemplate(TD);
12483 else if (auto *TD =
12484 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
12485 if (!CheckDeclaration(TD))
12486 diagnose(TD, true);
12487 checkTemplate(TD);
12488 }
12489 }
12490
12491 void checkInstantiated(EnumDecl *FD) {}
12492
12493 template<typename TemplDecl>
12494 void checkTemplate(TemplDecl *TD) {
12495 if (TD->isMemberSpecialization()) {
12496 if (!CheckMemberSpecialization(TD))
12497 diagnose(TD->getMostRecentDecl(), false);
12498 }
12499 }
12500};
12501} // end anonymous namespace
12502
12504 if (!getLangOpts().Modules)
12505 return;
12506
12507 ExplicitSpecializationVisibilityChecker(*this, Loc,
12509 .check(Spec);
12510}
12511
12513 NamedDecl *Spec) {
12514 if (!getLangOpts().CPlusPlusModules)
12515 return checkSpecializationVisibility(Loc, Spec);
12516
12517 ExplicitSpecializationVisibilityChecker(*this, Loc,
12519 .check(Spec);
12520}
12521
12522/// Returns the top most location responsible for the definition of \p N.
12523/// If \p N is a a template specialization, this is the location
12524/// of the top of the instantiation stack.
12525/// Otherwise, the location of \p N is returned.
12528 return N->getLocation();
12529 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
12531 return FD->getLocation();
12534 return N->getLocation();
12535 }
12536 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12537 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12538 continue;
12539 return CSC.PointOfInstantiation;
12540 }
12541 return N->getLocation();
12542}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
StringRef P
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1125
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.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6941
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
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 CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static bool CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, ArrayRef< TemplateArgument > Args)
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static TypeSourceInfo * SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Defines utilities for dealing with stack allocation and stack space.
static const TemplateArgument & getArgument(const TemplateArgument &A)
StateNode * Previous
__device__ int
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
const LValueBase getLValueBase() const
Definition: APValue.cpp:974
APSInt & getInt()
Definition: APValue.h:423
APSInt & getComplexIntImag()
Definition: APValue.h:461
ValueKind getKind() const
Definition: APValue.h:395
APFixedPoint & getFixedPoint()
Definition: APValue.h:445
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
bool isMemberPointer() const
Definition: APValue.h:411
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp: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:1010
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
unsigned getIntWidth(QualType T) const
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2575
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2591
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType NullPtrTy
Definition: ASTContext.h:1118
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:1591
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1119
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:1100
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2157
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType OverloadTy
Definition: ASTContext.h:1119
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2618
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2341
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:1569
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2000
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1039
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:3688
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:42
AutoTypeKeyword getAutoKeyword() const
Definition: TypeLoc.h:2189
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2207
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2257
ConceptDecl * getNamedConcept() const
Definition: TypeLoc.h:2231
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2250
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2225
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2237
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5981
bool isDecltypeAuto() const
Definition: Type.h:6004
A fixed int type of a specified bitwidth.
Definition: Type.h:7242
Pointer to a block type.
Definition: Type.h:3349
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:2981
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:2105
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition: ExprCXX.h:732
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2606
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1952
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal)
Definition: DeclCXX.cpp:2157
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3676
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1484
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isConst() const
Definition: DeclCXX.h:2112
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition: DeclCXX.h:540
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1876
base_class_range bases()
Definition: DeclCXX.h:619
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1905
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1901
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1883
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1916
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:531
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:126
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:152
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:132
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1062
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
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:3086
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
bool isTypeConcept() const
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr)
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:94
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:3556
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:4167
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:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1993
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1316
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
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:1975
bool isNamespace() const
Definition: DeclBase.h:2151
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1716
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1956
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1233
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1333
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1337
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1352
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1365
ValueDecl * getDecl()
Definition: Expr.h:1328
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1355
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:645
void ClearStorageClassSpecs()
Definition: DeclSpec.h:512
bool isNoreturnSpecified() const
Definition: DeclSpec.h:658
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SCS getStorageClassSpec() const
Definition: DeclSpec.h:498
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:572
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:571
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:659
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:651
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:499
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:870
bool isInlineSpecified() const
Definition: DeclSpec.h:634
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:508
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:646
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:833
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:637
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:648
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:834
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:1051
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:579
void addAttr(Attr *A)
Definition: DeclBase.cpp:991
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:262
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:833
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:803
void dropAttrs()
Definition: DeclBase.cpp:984
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:1032
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:1170
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2739
bool isInvalidDecl() const
Definition: DeclBase.h:594
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
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:908
bool hasAttr() const
Definition: DeclBase.h:583
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:448
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:813
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2047
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2336
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:2726
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2083
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2066
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2062
bool hasEllipsis() const
Definition: DeclSpec.h:2725
bool isInvalidType() const
Definition: DeclSpec.h:2714
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2082
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2054
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2330
Represents the type decltype(expr) (C++11).
Definition: Type.h:5358
Represents a C++17 deduced template specialization type.
Definition: Type.h:6029
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5947
bool isDeduced() const
Definition: Type.h:5969
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3859
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6452
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3316
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:482
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3801
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3899
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4226
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:488
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:547
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:544
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:550
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2472
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2492
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2460
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2516
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2508
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2524
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2500
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6504
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4021
bool isEmpty() const
Definition: TypeLoc.h:2365
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2361
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6371
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3867
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4126
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4938
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5575
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
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:3064
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:3059
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:817
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
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:3923
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:4061
Represents a member of a struct/union/class.
Definition: Decl.h:3057
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:999
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1078
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:34
Represents a function declaration or definition.
Definition: Decl.h:1971
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2438
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4054
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4360
QualType getReturnType() const
Definition: Decl.h:2754
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2683
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4021
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3617
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2502
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3993
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2432
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:4226
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition: Decl.h:2331
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4266
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3126
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4014
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4611
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3775
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5012
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4900
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4896
ArrayRef< QualType > param_types() const
Definition: Type.h:5044
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:467
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:542
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:553
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:525
unsigned getNumParams() const
Definition: TypeLoc.h:1500
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1452
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1448
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1464
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1507
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1491
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1472
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1456
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1486
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1444
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1460
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1468
QualType getReturnType() const
Definition: Type.h:4573
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:3655
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition: Type.h:3703
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:4847
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:8601
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:6221
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:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3424
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1950
Represents a linkage specification.
Definition: DeclCXX.h:2934
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h: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
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
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
bool isSuppressingAmbiguousDiagnostics() const
Determines whether this lookup is suppressing ambiguous lookup diagnostics.
Definition: Lookup.h:648
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
void setNotFoundInCurrentInstantiation()
Note that while no result was found in the current instantiation, there were dependent base classes t...
Definition: Lookup.h:501
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:4289
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
QualType getPointeeType() const
Definition: Type.h:3476
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:637
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:655
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
void addOuterRetainedLevel()
Add an outermost level that we are not substituting.
Definition: Template.h:257
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
void setKind(TemplateSubstitutionKind K)
Definition: Template.h:109
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
NamedDecl * getMostRecentDecl()
Definition: Decl.h:476
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:686
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1927
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
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.
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.
Expr * getDefaultArgument() const
Retrieve the default argument, if any.
void setDefaultArgument(Expr *DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6952
Represents a pointer to an Objective C object.
Definition: Type.h:7008
Represents a class type in Objective C.
Definition: Type.h:6754
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(TemplateName P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4173
Represents a pack expansion of types.
Definition: Type.h:6569
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
Represents a parameter to a function.
Definition: Decl.h:1761
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1821
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2985
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2915
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3016
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1811
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:7208
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
QualType getPointeeType() const
Definition: Type.h:3149
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
A (possibly-)qualified type.
Definition: Type.h:940
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7448
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3469
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
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:7560
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
void * getAsOpaquePtr() const
Definition: Type.h:987
bool isCanonical() const
Definition: Type.h:7416
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7405
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
The collection of all-type qualifiers we support.
Definition: Type.h:318
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
void addConst()
Definition: Type.h:446
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:534
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3442
Represents a struct/union/class.
Definition: Decl.h:4168
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4359
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:5549
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:860
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:865
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4994
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3380
QualType getPointeeType() const
Definition: Type.h:3398
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:262
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
@ 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:56
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
Definition: SemaCUDA.cpp:1053
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:10223
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6478
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2531
Whether and why a template name is required in this lookup.
Definition: Sema.h:8746
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:8754
bool hasTemplateKeyword() const
Definition: Sema.h:8757
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5708
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:8970
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6350
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:10157
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9703
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.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:688
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:1585
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15428
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:7285
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7289
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7297
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7292
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19512
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:40
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:6198
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:7476
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6165
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:993
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...
Decl * ActOnConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
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 ...
FunctionTemplateDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6326
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:17081
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition: SemaAttr.cpp:53
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1422
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.
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:8717
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:9067
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:9070
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:9074
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:848
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2667
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5864
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:514
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1523
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:517
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
Definition: SemaDecl.cpp:1756
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:645
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool IsDeduced)
Check a template argument against its corresponding template template parameter.
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:9217
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:765
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:17035
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2208
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:8707
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc, bool IsDeduced)
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:9160
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:9178
@ TPL_TemplateTemplateArgumentMatch
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:9189
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:9168
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:9199
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:8767
@ 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:8700
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
FPOptions & getCurFPFeatures()
Definition: Sema.h:512
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:65
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:10757
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:10745
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:10754
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:10748
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:10772
const LangOptions & getLangOpts() const
Definition: Sema.h:510
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
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:847
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, std::optional< unsigned > NumExpansions)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
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:11164
const LangOptions & LangOpts
Definition: Sema.h:846
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 ...
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition: Sema.h:6975
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, 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...
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:19933
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:7277
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:9316
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:7905
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:17006
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:1215
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:10754
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:652
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3273
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:986
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15009
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5870
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool 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.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6213
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1479
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1311
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4767
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:8953
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3145
@ NTK_TypeAliasTemplate
Definition: Sema.h:3153
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
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,...
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
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:228
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:11584
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
@ CTK_ErrorRecovery
Definition: Sema.h:7529
RedeclarationKind forRedeclarationInCurContext() const
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:7951
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:3157
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:1948
ASTConsumer & Consumer
Definition: Sema.h:849
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:9436
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:5678
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:17229
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:8831
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
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:8744
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:528
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
@ TUK_Definition
Definition: Sema.h:3168
@ TUK_Declaration
Definition: Sema.h:3167
@ TUK_Friend
Definition: Sema.h:3169
@ TUK_Reference
Definition: Sema.h:3166
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:15046
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:8897
@ TPC_ClassTemplate
Definition: Sema.h:8898
@ TPC_FriendFunctionTemplate
Definition: Sema.h:8903
@ TPC_ClassTemplateMember
Definition: Sema.h:8901
@ TPC_FunctionTemplate
Definition: Sema.h:8900
@ TPC_FriendClassTemplate
Definition: Sema.h:8902
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:8904
@ TPC_TypeAliasTemplate
Definition: Sema.h:8905
@ TPC_VarTemplate
Definition: Sema.h:8899
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:1607
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:1590
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2349
@ OOK_Outside
Definition: Sema.h:3174
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:520
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:4589
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:21042
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15275
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1730
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output)
@ 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:2805
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:2524
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:8709
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition: Sema.h:7485
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:9635
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6119
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:218
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6652
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4466
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:5889
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:5819
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3584
bool isEnum() const
Definition: Decl.h:3791
StringRef getKindName() const
Definition: Decl.h:3775
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4737
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4820
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3808
TagKind getTagKind() const
Definition: Decl.h:3779
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:4012
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:1256
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1294
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:283
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
SourceLocation getLocation() const
Definition: TemplateBase.h:563
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:623
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:616
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:609
Expr * getSourceExpression() const
Definition: TemplateBase.h:584
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:418
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:298
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
bool hasAssociatedConstraints() const
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:426
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
bool isNull() const
Determine whether this template name is NULL.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
bool hasAssociatedConstraints() const
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:129
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1695
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6089
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6157
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6155
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, ArrayRef< TemplateArgument > Converted)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:4201
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.
bool wasDeclaredWithTypename() const
Whether this template type parameter was declared with the 'typename' keyword.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
unsigned getIndex() const
Retrieve the index of the template parameter.
bool hasTypeConstraint() const
Determine whether this template parameter has a type-constraint.
TypeSourceInfo * getDefaultArgumentInfo() const
Retrieves the default argument's source information, if any.
const TypeConstraint * getTypeConstraint() const
Returns the type constraint associated with this template parameter (if any).
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a template type parameter pack that has a known list of different type-cons...
void removeDefaultArgument()
Removes the default argument of this template parameter.
void setDefaultArgument(TypeSourceInfo *DefArg)
Set the default argument for this template parameter.
bool isParameterPack() const
Returns whether this is a parameter pack.
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint)
unsigned getNumExpansionParameters() const
Retrieves the number of parameters in an expanded parameter pack.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
TemplateTypeParmDecl * getDecl() const
Definition: TypeLoc.h:760
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:5782
unsigned getIndex() const
Definition: Type.h:5779
unsigned getDepth() const
Definition: Type.h:5778
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:3555
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5554
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:231
Represents a declaration of a type.
Definition: Decl.h:3390
const Type * getTypeForDecl() const
Definition: Decl.h:3414
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3417
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:740
bool isNull() const
Definition: TypeLoc.h:121
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
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:5274
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5322
A container of type source information.
Definition: Type.h:7330
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:7341
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:528
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
static TypeTraitExpr * Create(const ASTContext &C, QualType T, SourceLocation Loc, TypeTrait Kind, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc, bool Value)
Create a new type trait expression.
Definition: ExprCXX.cpp:1828
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:3152
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3134
The base class of the type hierarchy.
Definition: Type.h:1813
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2400
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isBooleanType() const
Definition: Type.h:8033
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2156
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2206
bool isRValueReferenceType() const
Definition: Type.h:7632
bool isVoidPointerType() const
Definition: Type.cpp:655
bool isArrayType() const
Definition: Type.h:7678
bool isPointerType() const
Definition: Type.h:7612
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
bool isEnumeralType() const
Definition: Type.h:7710
bool isScalarType() const
Definition: Type.h:8004
bool isChar8Type() const
Definition: Type.cpp:2094
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2047
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:427
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8020
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2114
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:7752
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2758
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2661
bool isLValueReferenceType() const
Definition: Type.h:7628
bool isBitIntType() const
Definition: Type.h:7840
bool isStructuralType() const
Determine if this type is a structural type, per C++20 [temp.param]p7.
Definition: Type.cpp:2958
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool isChar16Type() const
Definition: Type.cpp:2100
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2000
QualType getCanonicalTypeInternal() const
Definition: Type.h:2936
bool isMemberPointerType() const
Definition: Type.h:7660
bool isChar32Type() const
Definition: Type.cpp:2106
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2671
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4898
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8039
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:4519
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
bool isFunctionType() const
Definition: Type.h:7608
bool isVectorType() const
Definition: Type.h:7718
bool isWideCharType() const
Definition: Type.cpp:2087
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isNullPtrType() const
Definition: Type.h:7938
bool isRecordType() const
Definition: Type.h:7706
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5503
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3432
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3482
QualType getUnderlyingType() const
Definition: Decl.h:3487
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
TypedefNameDecl * getTypedefNameDecl() const
Definition: TypeLoc.h:695
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
A unary type transform, which is a type constructed from another.
Definition: Type.h:5466
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1107
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1077
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3197
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5144
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3862
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3384
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
TLSKind getTLSKind() const
Definition: Decl.cpp:2165
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2749
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2876
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1155
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2777
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2756
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2867
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
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:3747
Represents a GCC generic vector type.
Definition: Type.h:3969
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeCanonical()
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
ImplicitTypenameContext
Definition: DeclSpec.h:1883
bool isa(CodeGen::Address addr)
Definition: Address.h:294
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus17
Definition: LangStandard.h:58
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Extern
Definition: Specifiers.h:248
@ SC_None
Definition: Specifiers.h:247
@ TSCS_unspecified
Definition: Specifiers.h:233
@ CRK_None
Candidate is not a rewritten candidate.
Definition: Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6299
@ Enum
The "enum" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:307
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:304
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
CastKind
CastKind - The kind of operation required for a conversion.
std::optional< unsigned > getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg, const NamedDecl *Param, ArrayRef< TemplateArgument > Args, unsigned Depth)
Make a best-effort determination of whether the type T can be produced by substituting Args into the ...
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
@ TNK_Dependent_template_name
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
Definition: TemplateKinds.h:26
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
@ TNK_Non_template
The name does not refer to a template.
Definition: TemplateKinds.h:22
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
Definition: TemplateKinds.h:50
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
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:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:367
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
ActionResult< Decl * > DeclResult
Definition: Ownership.h:254
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6274
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
@ Parens
New-expression has a C++98 paren-delimited initializer.
CharacterLiteralKind
Definition: Expr.h:1584
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
#define false
Definition: stdbool.h: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
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:4735
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:9720
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:9827
A stack object to be created when performing template instantiation.
Definition: Sema.h:9905
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:10059
NamedDecl * Previous
Definition: Sema.h:354
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.