clang 23.0.0git
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
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 C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/DeclBase.h"
21#include "clang/AST/Expr.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Sema.h"
35#include "clang/Sema/Template.h"
38#include "llvm/ADT/SmallVectorExtras.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/SaveAndRestore.h"
42#include "llvm/Support/TimeProfiler.h"
43#include <optional>
44
45using namespace clang;
46using namespace sema;
47
48//===----------------------------------------------------------------------===/
49// Template Instantiation Support
50//===----------------------------------------------------------------------===/
51
52namespace {
54struct Response {
55 const Decl *NextDecl = nullptr;
56 bool IsDone = false;
57 bool ClearRelativeToPrimary = true;
58 static Response Done() {
59 Response R;
60 R.IsDone = true;
61 return R;
62 }
63 static Response ChangeDecl(const Decl *ND) {
64 Response R;
65 R.NextDecl = ND;
66 return R;
67 }
68 static Response ChangeDecl(const DeclContext *Ctx) {
69 Response R;
70 R.NextDecl = Decl::castFromDeclContext(Ctx);
71 return R;
72 }
73
74 static Response UseNextDecl(const Decl *CurDecl) {
75 return ChangeDecl(CurDecl->getDeclContext());
76 }
77
78 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
79 Response R = Response::UseNextDecl(CurDecl);
80 R.ClearRelativeToPrimary = false;
81 return R;
82 }
83};
84
85// Retrieve the primary template for a lambda call operator. It's
86// unfortunate that we only have the mappings of call operators rather
87// than lambda classes.
88const FunctionDecl *
89getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
90 if (!isLambdaCallOperator(LambdaCallOperator))
91 return LambdaCallOperator;
92 while (true) {
93 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
94 LambdaCallOperator->getDescribedTemplate());
95 FTD && FTD->getInstantiatedFromMemberTemplate()) {
96 LambdaCallOperator =
97 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
98 } else if (LambdaCallOperator->getPrimaryTemplate()) {
99 // Cases where the lambda operator is instantiated in
100 // TemplateDeclInstantiator::VisitCXXMethodDecl.
101 LambdaCallOperator =
102 LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
103 } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)
104 ->getInstantiatedFromMemberFunction())
105 LambdaCallOperator = Prev;
106 else
107 break;
108 }
109 return LambdaCallOperator;
110}
111
112struct EnclosingTypeAliasTemplateDetails {
114 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
115 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
116
117 explicit operator bool() noexcept { return Template; }
118};
119
120// Find the enclosing type alias template Decl from CodeSynthesisContexts, as
121// well as its primary template and instantiating template arguments.
122EnclosingTypeAliasTemplateDetails
123getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
124 for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
126 TypeAliasTemplateInstantiation)
127 continue;
128 EnclosingTypeAliasTemplateDetails Result;
129 auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),
130 *Next = TATD->getInstantiatedFromMemberTemplate();
131 Result = {
132 /*Template=*/TATD,
133 /*PrimaryTypeAliasDecl=*/TATD,
134 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
135 };
136 while (Next) {
137 Result.PrimaryTypeAliasDecl = Next;
138 Next = Next->getInstantiatedFromMemberTemplate();
139 }
140 return Result;
141 }
142 return {};
143}
144
145// Check if we are currently inside of a lambda expression that is
146// surrounded by a using alias declaration. e.g.
147// template <class> using type = decltype([](auto) { ^ }());
148// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
149// a DeclContext, nor does it have an associated specialization Decl from which
150// we could collect these template arguments.
151bool isLambdaEnclosedByTypeAliasDecl(
152 const FunctionDecl *LambdaCallOperator,
153 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
154 struct Visitor : DynamicRecursiveASTVisitor {
155 Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
156 bool VisitLambdaExpr(LambdaExpr *LE) override {
157 // Return true to bail out of the traversal, implying the Decl contains
158 // the lambda.
159 return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=
160 CallOperator;
161 }
162 const FunctionDecl *CallOperator;
163 };
164
165 QualType Underlying =
166 PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
167
168 return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
169 .TraverseType(Underlying);
170}
171
172// Add template arguments from a variable template instantiation.
173Response
174HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
176 bool SkipForSpecialization) {
177 // For a class-scope explicit specialization, there are no template arguments
178 // at this level, but there may be enclosing template arguments.
179 if (VarTemplSpec->isClassScopeExplicitSpecialization())
180 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
181
182 // We're done when we hit an explicit specialization.
183 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
185 return Response::Done();
186
187 // If this variable template specialization was instantiated from a
188 // specialized member that is a variable template, we're done.
189 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
190 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
191 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
193 dyn_cast<VarTemplatePartialSpecializationDecl *>(Specialized)) {
194 if (!SkipForSpecialization)
195 Result.addOuterTemplateArguments(
196 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
197 /*Final=*/false);
198 if (Partial->isMemberSpecialization())
199 return Response::Done();
200 } else {
201 VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Specialized);
202 if (!SkipForSpecialization)
203 Result.addOuterTemplateArguments(
204 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
205 /*Final=*/false);
206 if (Tmpl->isMemberSpecialization())
207 return Response::Done();
208 }
209 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
210}
211
212// If we have a template template parameter with translation unit context,
213// then we're performing substitution into a default template argument of
214// this template template parameter before we've constructed the template
215// that will own this template template parameter. In this case, we
216// use empty template parameter lists for all of the outer templates
217// to avoid performing any substitutions.
218Response
219HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
221 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
222 Result.addOuterTemplateArguments(std::nullopt);
223 return Response::Done();
224}
225
226Response HandlePartialClassTemplateSpec(
227 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
228 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
229 if (!SkipForSpecialization)
230 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
231 return Response::Done();
232}
233
234// Add template arguments from a class template instantiation.
235Response
236HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
238 bool SkipForSpecialization) {
239 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
240 // We're done when we hit an explicit specialization.
241 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
243 return Response::Done();
244
245 if (!SkipForSpecialization)
246 Result.addOuterTemplateArguments(
247 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
248 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
249 /*Final=*/false);
250
251 // If this class template specialization was instantiated from a
252 // specialized member that is a class template, we're done.
253 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
254 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
255 return Response::Done();
256
257 // If this was instantiated from a partial template specialization, we need
258 // to get the next level of declaration context from the partial
259 // specialization, as the ClassTemplateSpecializationDecl's
260 // DeclContext/LexicalDeclContext will be for the primary template.
261 if (auto *InstFromPartialTempl =
262 ClassTemplSpec->getSpecializedTemplateOrPartial()
264 return Response::ChangeDecl(
265 InstFromPartialTempl->getLexicalDeclContext());
266 }
267 return Response::UseNextDecl(ClassTemplSpec);
268}
269
270Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
272 const FunctionDecl *Pattern, bool RelativeToPrimary,
273 bool ForConstraintInstantiation,
274 bool ForDefaultArgumentSubstitution) {
275 // Add template arguments from a function template specialization.
276 if (!RelativeToPrimary &&
277 Function->getTemplateSpecializationKindForInstantiation() ==
279 return Response::Done();
280
281 if (!RelativeToPrimary &&
282 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
283 // This is an implicit instantiation of an explicit specialization. We
284 // don't get any template arguments from this function but might get
285 // some from an enclosing template.
286 return Response::UseNextDecl(Function);
287 } else if (const TemplateArgumentList *TemplateArgs =
288 Function->getTemplateSpecializationArgs()) {
289 // Add the template arguments for this specialization.
290 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
291 TemplateArgs->asArray(),
292 /*Final=*/false);
293
294 if (RelativeToPrimary &&
295 (Function->getTemplateSpecializationKind() ==
297 (Function->getFriendObjectKind() &&
298 !Function->getPrimaryTemplate()->getFriendObjectKind())))
299 return Response::UseNextDecl(Function);
300
301 // If this function was instantiated from a specialized member that is
302 // a function template, we're done.
303 assert(Function->getPrimaryTemplate() && "No function template?");
304 if (!ForDefaultArgumentSubstitution &&
305 Function->getPrimaryTemplate()->isMemberSpecialization())
306 return Response::Done();
307
308 // If this function is a generic lambda specialization, we are done.
309 if (!ForConstraintInstantiation &&
311 return Response::Done();
312
313 } else if (auto *Template = Function->getDescribedFunctionTemplate()) {
314 assert(
315 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
316 "Outer template not instantiated?");
317 if (ForConstraintInstantiation) {
318 for (auto &Inst : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
320 Inst.Entity == Template) {
321 // After CWG2369, the outer templates are not instantiated when
322 // checking its associated constraints. So add them back through the
323 // synthesis context; this is useful for e.g. nested constraints
324 // involving lambdas.
325 Result.addOuterTemplateArguments(Template, Inst.template_arguments(),
326 /*Final=*/false);
327 break;
328 }
329 }
330 }
331 }
332 // If this is a friend or local declaration and it declares an entity at
333 // namespace scope, take arguments from its lexical parent
334 // instead of its semantic parent, unless of course the pattern we're
335 // instantiating actually comes from the file's context!
336 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
337 Function->getNonTransparentDeclContext()->isFileContext() &&
338 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
339 return Response::ChangeDecl(Function->getLexicalDeclContext());
340 }
341
342 if (ForConstraintInstantiation && Function->getFriendObjectKind())
343 return Response::ChangeDecl(Function->getLexicalDeclContext());
344 return Response::UseNextDecl(Function);
345}
346
347Response HandleFunctionTemplateDecl(Sema &SemaRef,
348 const FunctionTemplateDecl *FTD,
351 Result.addOuterTemplateArguments(
352 const_cast<FunctionTemplateDecl *>(FTD),
353 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(
354 SemaRef.Context),
355 /*Final=*/false);
356
358
359 for (const Type *Ty = NNS.getKind() == NestedNameSpecifier::Kind::Type
360 ? NNS.getAsType()
361 : nullptr,
362 *NextTy = nullptr;
364 Ty = std::exchange(NextTy, nullptr)) {
365 if (NestedNameSpecifier P = Ty->getPrefix();
367 NextTy = P.getAsType();
368 const auto *TSTy = dyn_cast<TemplateSpecializationType>(Ty);
369 if (!TSTy)
370 continue;
371
372 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
373 // Prefer template arguments from the injected-class-type if possible.
374 // For example,
375 // ```cpp
376 // template <class... Pack> struct S {
377 // template <class T> void foo();
378 // };
379 // template <class... Pack> template <class T>
380 // ^^^^^^^^^^^^^ InjectedTemplateArgs
381 // They're of kind TemplateArgument::Pack, not of
382 // TemplateArgument::Type.
383 // void S<Pack...>::foo() {}
384 // ^^^^^^^
385 // TSTy->template_arguments() (which are of PackExpansionType)
386 // ```
387 // This meets the contract in
388 // TreeTransform::TryExpandParameterPacks that the template arguments
389 // for unexpanded parameters should be of a Pack kind.
390 if (TSTy->isCurrentInstantiation()) {
391 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
392 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
393 Arguments = CTD->getInjectedTemplateArgs(SemaRef.Context);
394 else if (auto *Specialization =
395 dyn_cast<ClassTemplateSpecializationDecl>(RD))
396 Arguments = Specialization->getTemplateInstantiationArgs().asArray();
397 }
398 Result.addOuterTemplateArguments(
399 TSTy->getTemplateName().getAsTemplateDecl(), Arguments,
400 /*Final=*/false);
401 }
402 }
403
404 return Response::ChangeDecl(FTD->getLexicalDeclContext());
405}
406
407Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
409 ASTContext &Context,
410 bool ForConstraintInstantiation) {
411 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
412 assert(
413 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
414 "Outer template not instantiated?");
415 if (ClassTemplate->isMemberSpecialization())
416 return Response::Done();
417 if (ForConstraintInstantiation)
418 Result.addOuterTemplateArguments(
419 const_cast<CXXRecordDecl *>(Rec),
420 ClassTemplate->getInjectedTemplateArgs(SemaRef.Context),
421 /*Final=*/false);
422 }
423
424 if (const MemberSpecializationInfo *MSInfo =
426 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
427 return Response::Done();
428
429 bool IsFriend = Rec->getFriendObjectKind() ||
432 if (ForConstraintInstantiation && IsFriend &&
434 return Response::ChangeDecl(Rec->getLexicalDeclContext());
435 }
436
437 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
438 // TypeAliasTemplateDecl that this lambda is defined inside of.
439 if (Rec->isLambda()) {
440 if (const Decl *LCD = Rec->getLambdaContextDecl())
441 return Response::ChangeDecl(LCD);
442 // Retrieve the template arguments for a using alias declaration.
443 // This is necessary for constraint checking, since we always keep
444 // constraints relative to the primary template.
445 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);
446 ForConstraintInstantiation && TypeAlias) {
447 if (isLambdaEnclosedByTypeAliasDecl(Rec->getLambdaCallOperator(),
448 TypeAlias.PrimaryTypeAliasDecl)) {
449 Result.addOuterTemplateArguments(TypeAlias.Template,
450 TypeAlias.AssociatedTemplateArguments,
451 /*Final=*/false);
452 // Visit the parent of the current type alias declaration rather than
453 // the lambda thereof.
454 // E.g., in the following example:
455 // struct S {
456 // template <class> using T = decltype([]<Concept> {} ());
457 // };
458 // void foo() {
459 // S::T var;
460 // }
461 // The instantiated lambda expression (which we're visiting at 'var')
462 // has a function DeclContext 'foo' rather than the Record DeclContext
463 // S. This seems to be an oversight to me that we may want to set a
464 // Sema Context from the CXXScopeSpec before substituting into T.
465 return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
466 }
467 }
468 }
469
470 return Response::UseNextDecl(Rec);
471}
472
473Response HandleImplicitConceptSpecializationDecl(
476 Result.addOuterTemplateArguments(
477 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
479 /*Final=*/false);
480 return Response::UseNextDecl(CSD);
481}
482
483Response HandleGenericDeclContext(const Decl *CurDecl) {
484 return Response::UseNextDecl(CurDecl);
485}
486} // namespace TemplateInstArgsHelpers
487} // namespace
488
490 const NamedDecl *ND, const DeclContext *DC, bool Final,
491 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
492 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
493 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
494 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
495 // Accumulate the set of template argument lists in this structure.
497
498 using namespace TemplateInstArgsHelpers;
499 const Decl *CurDecl = ND;
500
501 if (Innermost) {
502 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
503 Final);
504 // Populate placeholder template arguments for TemplateTemplateParmDecls.
505 // This is essential for the case e.g.
506 //
507 // template <class> concept Concept = false;
508 // template <template <Concept C> class T> void foo(T<int>)
509 //
510 // where parameter C has a depth of 1 but the substituting argument `int`
511 // has a depth of 0.
512 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
513 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
514 CurDecl = DC ? Decl::castFromDeclContext(DC)
515 : Response::UseNextDecl(CurDecl).NextDecl;
516 } else if (!CurDecl)
517 CurDecl = Decl::castFromDeclContext(DC);
518
519 while (!CurDecl->isFileContextDecl()) {
520 Response R;
521 if (const auto *VarTemplSpec =
522 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
523 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
524 } else if (const auto *PartialClassTemplSpec =
525 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
526 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
527 SkipForSpecialization);
528 } else if (const auto *ClassTemplSpec =
529 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
530 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
531 SkipForSpecialization);
532 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
533 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
534 ForConstraintInstantiation,
535 ForDefaultArgumentSubstitution);
536 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
537 R = HandleRecordDecl(*this, Rec, Result, Context,
538 ForConstraintInstantiation);
539 } else if (const auto *CSD =
540 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
541 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
542 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
543 R = HandleFunctionTemplateDecl(*this, FTD, Result);
544 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
545 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
546 } else if (!isa<DeclContext>(CurDecl)) {
547 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
548 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
549 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
550 }
551 } else {
552 R = HandleGenericDeclContext(CurDecl);
553 }
554
555 if (R.IsDone)
556 return Result;
557 if (R.ClearRelativeToPrimary)
558 RelativeToPrimary = false;
559 assert(R.NextDecl);
560 CurDecl = R.NextDecl;
561 }
562 return Result;
563}
564
605
608 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
609 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs)
610 : SemaRef(SemaRef) {
611 // Don't allow further instantiation if a fatal error and an uncompilable
612 // error have occurred. Any diagnostics we might have raised will not be
613 // visible, and we do not need to construct a correct AST.
614 if (SemaRef.Diags.hasFatalErrorOccurred() &&
615 SemaRef.hasUncompilableErrorOccurred()) {
616 Invalid = true;
617 return;
618 }
619
621 Inst.Kind = Kind;
622 Inst.PointOfInstantiation = PointOfInstantiation;
623 Inst.Entity = Entity;
624 Inst.Template = Template;
625 Inst.TemplateArgs = TemplateArgs.data();
626 Inst.NumTemplateArgs = TemplateArgs.size();
627 Inst.InstantiationRange = InstantiationRange;
628 Inst.InConstraintSubstitution =
630 Inst.InParameterMappingSubstitution =
632 if (!SemaRef.CodeSynthesisContexts.empty()) {
633 Inst.InConstraintSubstitution |=
634 SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution;
635 Inst.InParameterMappingSubstitution |=
636 SemaRef.CodeSynthesisContexts.back().InParameterMappingSubstitution;
637 }
638
639 Invalid = SemaRef.pushCodeSynthesisContext(Inst);
640 if (!Invalid)
641 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
642}
643
645 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
646 SourceRange InstantiationRange)
647 : InstantiatingTemplate(SemaRef,
648 CodeSynthesisContext::TemplateInstantiation,
649 PointOfInstantiation, InstantiationRange, Entity) {}
650
652 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
653 ExceptionSpecification, SourceRange InstantiationRange)
655 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
656 PointOfInstantiation, InstantiationRange, Entity) {}
657
659 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
661 SourceRange InstantiationRange)
663 SemaRef,
664 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
665 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
666 Template, TemplateArgs) {}
667
680
682 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
683 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
685 SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
686 PointOfInstantiation, InstantiationRange, Template, nullptr,
687 TemplateArgs) {}
688
690 Sema &SemaRef, SourceLocation PointOfInstantiation,
692 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
694 SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
695 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
696 TemplateArgs) {}
697
699 Sema &SemaRef, SourceLocation PointOfInstantiation,
701 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
703 SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
704 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
705 TemplateArgs) {}
706
708 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
709 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
711 SemaRef,
712 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
713 PointOfInstantiation, InstantiationRange, Param, nullptr,
714 TemplateArgs) {}
715
717 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
719 SourceRange InstantiationRange)
721 SemaRef,
722 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
723 PointOfInstantiation, InstantiationRange, Param, Template,
724 TemplateArgs) {}
725
727 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
729 SourceRange InstantiationRange)
731 SemaRef,
732 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
733 PointOfInstantiation, InstantiationRange, Param, Template,
734 TemplateArgs) {}
735
737 Sema &SemaRef, SourceLocation PointOfInstantiation,
739 SourceRange InstantiationRange)
741 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
742 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
743 /*Template=*/nullptr, TemplateArgs) {}
744
746 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
747 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
748 SourceRange InstantiationRange)
750 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
751 PointOfInstantiation, InstantiationRange, Param, Template,
752 TemplateArgs) {}
753
755 Sema &SemaRef, SourceLocation PointOfInstantiation,
756 concepts::Requirement *Req, SourceRange InstantiationRange)
758 SemaRef, CodeSynthesisContext::RequirementInstantiation,
759 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
760 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
761
763 Sema &SemaRef, SourceLocation PointOfInstantiation,
765 SourceRange InstantiationRange)
767 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
768 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
769 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
770
772 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
773 SourceRange InstantiationRange)
775 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
776 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
777 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
778
780 Sema &SemaRef, SourceLocation PointOfInstantiation,
782 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
785 PointOfInstantiation, InstantiationRange, Template, nullptr,
786 TemplateArgs) {}
787
789 Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution,
790 NamedDecl *Template, SourceRange InstantiationRange)
793 PointOfInstantiation, InstantiationRange, Template, nullptr, {}) {}
794
796 Sema &SemaRef, SourceLocation PointOfInstantiation,
798 SourceRange InstantiationRange)
801 PointOfInstantiation, InstantiationRange, Template) {}
802
804 Sema &SemaRef, SourceLocation PointOfInstantiation,
806 SourceRange InstantiationRange)
809 PointOfInstantiation, InstantiationRange, Template) {}
810
812 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
813 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
815 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
816 PointOfInstantiation, InstantiationRange, Entity) {}
817
819 Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP,
820 TemplateDecl *PArg, SourceRange InstantiationRange)
822 ArgLoc, InstantiationRange, PArg) {}
823
825 if (!Ctx.isInstantiationRecord()) {
827 } else {
828 assert(SemaRef.NonInstantiationEntries <=
829 SemaRef.CodeSynthesisContexts.size());
830 if ((SemaRef.CodeSynthesisContexts.size() -
831 SemaRef.NonInstantiationEntries) >
832 SemaRef.getLangOpts().InstantiationDepth) {
834 diag::err_template_recursion_depth_exceeded)
835 << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange;
837 diag::note_template_recursion_depth)
838 << SemaRef.getLangOpts().InstantiationDepth;
839 return true;
840 }
841 }
842
843 CodeSynthesisContexts.push_back(Ctx);
844
845 // Check to see if we're low on stack space. We can't do anything about this
846 // from here, but we can at least warn the user.
847 StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);
848 return false;
849}
850
852 auto &Active = CodeSynthesisContexts.back();
853 if (!Active.isInstantiationRecord()) {
854 assert(NonInstantiationEntries > 0);
856 }
857
858 // Name lookup no longer looks in this template's defining module.
859 assert(CodeSynthesisContexts.size() >=
861 "forgot to remove a lookup module for a template instantiation");
862 if (CodeSynthesisContexts.size() ==
865 LookupModulesCache.erase(M);
867 }
868
869 // If we've left the code synthesis context for the current context stack,
870 // stop remembering that we've emitted that stack.
871 if (CodeSynthesisContexts.size() ==
874
875 CodeSynthesisContexts.pop_back();
876}
877
879 if (!Invalid) {
880 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
881 SemaRef.CodeSynthesisContexts.back());
882
883 SemaRef.popCodeSynthesisContext();
884 Invalid = true;
885 }
886}
887
888static std::string convertCallArgsToString(Sema &S,
890 std::string Result;
891 llvm::raw_string_ostream OS(Result);
892 llvm::ListSeparator Comma;
893 for (const Expr *Arg : Args) {
894 OS << Comma;
895 Arg->IgnoreParens()->printPretty(OS, nullptr,
897 }
898 return Result;
899}
900
902 // Determine which template instantiations to skip, if any.
903 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
904 unsigned Limit = Diags.getTemplateBacktraceLimit();
905 if (Limit && Limit < CodeSynthesisContexts.size()) {
906 SkipStart = Limit / 2 + Limit % 2;
907 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
908 }
909
910 // FIXME: In all of these cases, we need to show the template arguments
911 unsigned InstantiationIdx = 0;
913 Active = CodeSynthesisContexts.rbegin(),
914 ActiveEnd = CodeSynthesisContexts.rend();
915 Active != ActiveEnd;
916 ++Active, ++InstantiationIdx) {
917 // Skip this instantiation?
918 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
919 if (InstantiationIdx == SkipStart) {
920 // Note that we're skipping instantiations.
921 DiagFunc(Active->PointOfInstantiation,
922 PDiag(diag::note_instantiation_contexts_suppressed)
923 << unsigned(CodeSynthesisContexts.size() - Limit));
924 }
925 continue;
926 }
927
928 switch (Active->Kind) {
930 Decl *D = Active->Entity;
931 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
932 unsigned DiagID = diag::note_template_member_class_here;
934 DiagID = diag::note_template_class_instantiation_here;
935 DiagFunc(Active->PointOfInstantiation,
936 PDiag(DiagID) << Record << Active->InstantiationRange);
937 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
938 unsigned DiagID;
939 if (Function->getPrimaryTemplate())
940 DiagID = diag::note_function_template_spec_here;
941 else
942 DiagID = diag::note_template_member_function_here;
943 DiagFunc(Active->PointOfInstantiation,
944 PDiag(DiagID) << Function << Active->InstantiationRange);
945 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
946 DiagFunc(Active->PointOfInstantiation,
947 PDiag(VD->isStaticDataMember()
948 ? diag::note_template_static_data_member_def_here
949 : diag::note_template_variable_def_here)
950 << VD << Active->InstantiationRange);
951 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
952 DiagFunc(Active->PointOfInstantiation,
953 PDiag(diag::note_template_enum_def_here)
954 << ED << Active->InstantiationRange);
955 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
956 DiagFunc(Active->PointOfInstantiation,
957 PDiag(diag::note_template_nsdmi_here)
958 << FD << Active->InstantiationRange);
959 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
960 DiagFunc(Active->PointOfInstantiation,
961 PDiag(diag::note_template_class_instantiation_here)
962 << CTD << Active->InstantiationRange);
963 }
964 break;
965 }
966
968 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
969 SmallString<128> TemplateArgsStr;
970 llvm::raw_svector_ostream OS(TemplateArgsStr);
971 Template->printName(OS, getPrintingPolicy());
972 printTemplateArgumentList(OS, Active->template_arguments(),
974 DiagFunc(Active->PointOfInstantiation,
975 PDiag(diag::note_default_arg_instantiation_here)
976 << OS.str() << Active->InstantiationRange);
977 break;
978 }
979
981 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
982 DiagFunc(Active->PointOfInstantiation,
983 PDiag(diag::note_explicit_template_arg_substitution_here)
984 << FnTmpl
986 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
987 Active->NumTemplateArgs)
988 << Active->InstantiationRange);
989 break;
990 }
991
993 if (FunctionTemplateDecl *FnTmpl =
994 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
995 DiagFunc(
996 Active->PointOfInstantiation,
997 PDiag(diag::note_function_template_deduction_instantiation_here)
998 << FnTmpl
1000 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
1001 Active->NumTemplateArgs)
1002 << Active->InstantiationRange);
1003 } else {
1004 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1005 isa<VarTemplateSpecializationDecl>(Active->Entity);
1006 bool IsTemplate = false;
1007 TemplateParameterList *Params;
1008 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1009 IsTemplate = true;
1010 Params = D->getTemplateParameters();
1011 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1012 Active->Entity)) {
1013 Params = D->getTemplateParameters();
1014 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1015 Active->Entity)) {
1016 Params = D->getTemplateParameters();
1017 } else {
1018 llvm_unreachable("unexpected template kind");
1019 }
1020
1021 DiagFunc(Active->PointOfInstantiation,
1022 PDiag(diag::note_deduced_template_arg_substitution_here)
1023 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1025 Active->TemplateArgs,
1026 Active->NumTemplateArgs)
1027 << Active->InstantiationRange);
1028 }
1029 break;
1030 }
1031
1033 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1034 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1035
1036 SmallString<128> TemplateArgsStr;
1037 llvm::raw_svector_ostream OS(TemplateArgsStr);
1039 printTemplateArgumentList(OS, Active->template_arguments(),
1041 DiagFunc(Active->PointOfInstantiation,
1042 PDiag(diag::note_default_function_arg_instantiation_here)
1043 << OS.str() << Active->InstantiationRange);
1044 break;
1045 }
1046
1048 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1049 std::string Name;
1050 if (!Parm->getName().empty())
1051 Name = std::string(" '") + Parm->getName().str() + "'";
1052
1053 TemplateParameterList *TemplateParams = nullptr;
1054 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1055 TemplateParams = Template->getTemplateParameters();
1056 else
1057 TemplateParams =
1059 ->getTemplateParameters();
1060 DiagFunc(Active->PointOfInstantiation,
1061 PDiag(diag::note_prior_template_arg_substitution)
1062 << isa<TemplateTemplateParmDecl>(Parm) << Name
1063 << getTemplateArgumentBindingsText(TemplateParams,
1064 Active->TemplateArgs,
1065 Active->NumTemplateArgs)
1066 << Active->InstantiationRange);
1067 break;
1068 }
1069
1071 TemplateParameterList *TemplateParams = nullptr;
1072 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1073 TemplateParams = Template->getTemplateParameters();
1074 else
1075 TemplateParams =
1077 ->getTemplateParameters();
1078
1079 DiagFunc(Active->PointOfInstantiation,
1080 PDiag(diag::note_template_default_arg_checking)
1081 << getTemplateArgumentBindingsText(TemplateParams,
1082 Active->TemplateArgs,
1083 Active->NumTemplateArgs)
1084 << Active->InstantiationRange);
1085 break;
1086 }
1087
1089 DiagFunc(Active->PointOfInstantiation,
1090 PDiag(diag::note_evaluating_exception_spec_here)
1091 << cast<FunctionDecl>(Active->Entity));
1092 break;
1093
1095 DiagFunc(Active->PointOfInstantiation,
1096 PDiag(diag::note_template_exception_spec_instantiation_here)
1097 << cast<FunctionDecl>(Active->Entity)
1098 << Active->InstantiationRange);
1099 break;
1100
1102 DiagFunc(Active->PointOfInstantiation,
1103 PDiag(diag::note_template_requirement_instantiation_here)
1104 << Active->InstantiationRange);
1105 break;
1107 DiagFunc(Active->PointOfInstantiation,
1108 PDiag(diag::note_template_requirement_params_instantiation_here)
1109 << Active->InstantiationRange);
1110 break;
1111
1113 DiagFunc(Active->PointOfInstantiation,
1114 PDiag(diag::note_nested_requirement_here)
1115 << Active->InstantiationRange);
1116 break;
1117
1119 DiagFunc(Active->PointOfInstantiation,
1120 PDiag(diag::note_in_declaration_of_implicit_special_member)
1121 << cast<CXXRecordDecl>(Active->Entity)
1122 << Active->SpecialMember);
1123 break;
1124
1126 DiagFunc(
1127 Active->Entity->getLocation(),
1128 PDiag(diag::note_in_declaration_of_implicit_equality_comparison));
1129 break;
1130
1132 // FIXME: For synthesized functions that are not defaulted,
1133 // produce a note.
1134 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1135 // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind()
1136 // will ensure that DFK.isComparison() is false. This is important because
1137 // we will uncondtionally dereference FD in the else if.
1140 if (DFK.isSpecialMember()) {
1141 auto *MD = cast<CXXMethodDecl>(FD);
1142 DiagFunc(Active->PointOfInstantiation,
1143 PDiag(diag::note_member_synthesized_at)
1144 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
1145 << Context.getCanonicalTagType(MD->getParent()));
1146 } else if (DFK.isComparison()) {
1147 QualType RecordType = FD->getParamDecl(0)
1148 ->getType()
1149 .getNonReferenceType()
1150 .getUnqualifiedType();
1151 DiagFunc(Active->PointOfInstantiation,
1152 PDiag(diag::note_comparison_synthesized_at)
1153 << (int)DFK.asComparison() << RecordType);
1154 }
1155 break;
1156 }
1157
1159 DiagFunc(Active->Entity->getLocation(),
1160 PDiag(diag::note_rewriting_operator_as_spaceship));
1161 break;
1162
1164 DiagFunc(Active->PointOfInstantiation,
1165 PDiag(diag::note_in_binding_decl_init)
1166 << cast<BindingDecl>(Active->Entity));
1167 break;
1168
1170 DiagFunc(Active->PointOfInstantiation,
1171 PDiag(diag::note_due_to_dllexported_class)
1172 << cast<CXXRecordDecl>(Active->Entity)
1173 << !getLangOpts().CPlusPlus11);
1174 break;
1175
1177 DiagFunc(Active->PointOfInstantiation,
1178 PDiag(diag::note_building_builtin_dump_struct_call)
1180 *this, llvm::ArrayRef(Active->CallArgs,
1181 Active->NumCallArgs)));
1182 break;
1183
1185 break;
1186
1188 DiagFunc(Active->PointOfInstantiation,
1189 PDiag(diag::note_lambda_substitution_here));
1190 break;
1192 unsigned DiagID = 0;
1193 if (!Active->Entity) {
1194 DiagFunc(Active->PointOfInstantiation,
1195 PDiag(diag::note_nested_requirement_here)
1196 << Active->InstantiationRange);
1197 break;
1198 }
1199 if (isa<ConceptDecl>(Active->Entity))
1200 DiagID = diag::note_concept_specialization_here;
1201 else if (isa<TemplateDecl>(Active->Entity))
1202 DiagID = diag::note_checking_constraints_for_template_id_here;
1203 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1204 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1205 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1206 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1207 else {
1208 assert(isa<FunctionDecl>(Active->Entity));
1209 DiagID = diag::note_checking_constraints_for_function_here;
1210 }
1211 SmallString<128> TemplateArgsStr;
1212 llvm::raw_svector_ostream OS(TemplateArgsStr);
1213 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1214 if (!isa<FunctionDecl>(Active->Entity)) {
1215 printTemplateArgumentList(OS, Active->template_arguments(),
1217 }
1218 DiagFunc(Active->PointOfInstantiation,
1219 PDiag(DiagID) << OS.str() << Active->InstantiationRange);
1220 break;
1221 }
1223 DiagFunc(Active->PointOfInstantiation,
1224 PDiag(diag::note_constraint_substitution_here)
1225 << Active->InstantiationRange);
1226 break;
1228 DiagFunc(Active->PointOfInstantiation,
1229 PDiag(diag::note_constraint_normalization_here)
1230 << cast<NamedDecl>(Active->Entity)
1231 << Active->InstantiationRange);
1232 break;
1234 DiagFunc(Active->PointOfInstantiation,
1235 PDiag(diag::note_parameter_mapping_substitution_here)
1236 << Active->InstantiationRange);
1237 break;
1239 DiagFunc(Active->PointOfInstantiation,
1240 PDiag(diag::note_building_deduction_guide_here));
1241 break;
1243 // Workaround for a workaround: don't produce a note if we are merely
1244 // instantiating some other template which contains this alias template.
1245 // This would be redundant either with the error itself, or some other
1246 // context note attached to it.
1247 if (Active->NumTemplateArgs == 0)
1248 break;
1249 DiagFunc(Active->PointOfInstantiation,
1250 PDiag(diag::note_template_type_alias_instantiation_here)
1251 << cast<TypeAliasTemplateDecl>(Active->Entity)
1252 << Active->InstantiationRange);
1253 break;
1255 DiagFunc(Active->PointOfInstantiation,
1256 PDiag(diag::note_template_arg_template_params_mismatch));
1257 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1258 ParamLoc.isValid())
1259 DiagFunc(ParamLoc, PDiag(diag::note_template_prev_declaration)
1260 << /*isTemplateTemplateParam=*/true
1261 << Active->InstantiationRange);
1262 break;
1263 }
1264 }
1265}
1266
1267//===----------------------------------------------------------------------===/
1268// Template Instantiation for Types
1269//===----------------------------------------------------------------------===/
1270namespace {
1271
1272 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1273 const MultiLevelTemplateArgumentList &TemplateArgs;
1274 SourceLocation Loc;
1275 DeclarationName Entity;
1276 // Whether to evaluate the C++20 constraints or simply substitute into them.
1277 bool EvaluateConstraints = true;
1278 // Whether Substitution was Incomplete, that is, we tried to substitute in
1279 // any user provided template arguments which were null.
1280 bool IsIncomplete = false;
1281 // Whether an incomplete substituion should be treated as an error.
1282 bool BailOutOnIncomplete;
1283
1284 // CWG2770: Function parameters should be instantiated when they are
1285 // needed by a satisfaction check of an atomic constraint or
1286 // (recursively) by another function parameter.
1287 bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm);
1288
1289 public:
1290 typedef TreeTransform<TemplateInstantiator> inherited;
1291
1292 TemplateInstantiator(Sema &SemaRef,
1293 const MultiLevelTemplateArgumentList &TemplateArgs,
1294 SourceLocation Loc, DeclarationName Entity,
1295 bool BailOutOnIncomplete = false)
1296 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1297 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1298
1299 void setEvaluateConstraints(bool B) {
1300 EvaluateConstraints = B;
1301 }
1302 bool getEvaluateConstraints() {
1303 return EvaluateConstraints;
1304 }
1305
1306 inline static struct ForParameterMappingSubstitution_t {
1307 } ForParameterMappingSubstitution;
1308
1309 TemplateInstantiator(ForParameterMappingSubstitution_t, Sema &SemaRef,
1310 SourceLocation Loc,
1311 const MultiLevelTemplateArgumentList &TemplateArgs)
1312 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1313 BailOutOnIncomplete(false) {}
1314
1315 /// Determine whether the given type \p T has already been
1316 /// transformed.
1317 ///
1318 /// For the purposes of template instantiation, a type has already been
1319 /// transformed if it is NULL or if it is not dependent.
1320 bool AlreadyTransformed(QualType T);
1321
1322 /// Returns the location of the entity being instantiated, if known.
1323 SourceLocation getBaseLocation() { return Loc; }
1324
1325 /// Returns the name of the entity being instantiated, if any.
1326 DeclarationName getBaseEntity() { return Entity; }
1327
1328 /// Returns whether any substitution so far was incomplete.
1329 bool getIsIncomplete() const { return IsIncomplete; }
1330
1331 /// Sets the "base" location and entity when that
1332 /// information is known based on another transformation.
1333 void setBase(SourceLocation Loc, DeclarationName Entity) {
1334 this->Loc = Loc;
1335 this->Entity = Entity;
1336 }
1337
1338 unsigned TransformTemplateDepth(unsigned Depth) {
1339 return TemplateArgs.getNewDepth(Depth);
1340 }
1341
1342 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1343 SourceRange PatternRange,
1344 ArrayRef<UnexpandedParameterPack> Unexpanded,
1345 bool FailOnPackProducingTemplates,
1346 bool &ShouldExpand, bool &RetainExpansion,
1347 UnsignedOrNone &NumExpansions) {
1348 if (SemaRef.CurrentInstantiationScope &&
1349 (SemaRef.inConstraintSubstitution() ||
1350 SemaRef.inParameterMappingSubstitution())) {
1351 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1352 NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>();
1353 if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(VD);
1354 PVD && maybeInstantiateFunctionParameterToScope(PVD))
1355 return true;
1356 }
1357 }
1358
1359 return getSema().CheckParameterPacksForExpansion(
1360 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1361 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1362 NumExpansions);
1363 }
1364
1365 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1367 }
1368
1369 TemplateArgument ForgetPartiallySubstitutedPack() {
1370 TemplateArgument Result;
1371 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1373 MultiLevelTemplateArgumentList &TemplateArgs =
1374 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1375 unsigned Depth, Index;
1376 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1377 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1378 Result = TemplateArgs(Depth, Index);
1379 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1380 } else {
1381 IsIncomplete = true;
1382 if (BailOutOnIncomplete)
1383 return TemplateArgument();
1384 }
1385 }
1386
1387 return Result;
1388 }
1389
1390 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1391 if (Arg.isNull())
1392 return;
1393
1394 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1396 MultiLevelTemplateArgumentList &TemplateArgs =
1397 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1398 unsigned Depth, Index;
1399 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1400 TemplateArgs.setArgument(Depth, Index, Arg);
1401 }
1402 }
1403
1404 MultiLevelTemplateArgumentList ForgetSubstitution() {
1405 MultiLevelTemplateArgumentList New;
1406 New.addOuterRetainedLevels(this->TemplateArgs.getNumLevels());
1407
1408 MultiLevelTemplateArgumentList Old =
1409 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1410 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1411 std::move(New);
1412 return Old;
1413 }
1414
1415 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1416 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = Old;
1417 }
1418
1419 TemplateArgument
1420 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1421 if (TA.getKind() != TemplateArgument::Pack)
1422 return TA;
1423 if (SemaRef.ArgPackSubstIndex)
1424 return SemaRef.getPackSubstitutedTemplateArgument(TA);
1425 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1426 "unexpected pack arguments in template rewrite");
1427 TemplateArgument Arg = *TA.pack_begin();
1428 if (Arg.isPackExpansion())
1429 Arg = Arg.getPackExpansionPattern();
1430 return Arg;
1431 }
1432
1433 /// Transform the given declaration by instantiating a reference to
1434 /// this declaration.
1435 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1436
1437 void transformAttrs(Decl *Old, Decl *New) {
1438 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1439 }
1440
1441 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1442 if (Old->isParameterPack() &&
1443 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1445 for (auto *New : NewDecls)
1447 Old, cast<VarDecl>(New));
1448 return;
1449 }
1450
1451 assert(NewDecls.size() == 1 &&
1452 "should only have multiple expansions for a pack");
1453 Decl *New = NewDecls.front();
1454
1455 // If we've instantiated the call operator of a lambda or the call
1456 // operator template of a generic lambda, update the "instantiation of"
1457 // information.
1458 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1459 if (NewMD && isLambdaCallOperator(NewMD)) {
1460 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1461 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1462 NewTD->setInstantiatedFromMemberTemplate(
1463 OldMD->getDescribedFunctionTemplate());
1464 else
1465 NewMD->setInstantiationOfMemberFunction(OldMD,
1467 }
1468
1470
1471 // We recreated a local declaration, but not by instantiating it. There
1472 // may be pending dependent diagnostics to produce.
1473 if (auto *DC = dyn_cast<DeclContext>(Old);
1474 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1475 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1476 }
1477
1478 /// Transform the definition of the given declaration by
1479 /// instantiating it.
1480 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1481
1482 /// Transform the first qualifier within a scope by instantiating the
1483 /// declaration.
1484 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1485
1486 bool TransformExceptionSpec(SourceLocation Loc,
1487 FunctionProtoType::ExceptionSpecInfo &ESI,
1488 SmallVectorImpl<QualType> &Exceptions,
1489 bool &Changed);
1490
1491 /// Rebuild the exception declaration and register the declaration
1492 /// as an instantiated local.
1493 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1494 TypeSourceInfo *Declarator,
1495 SourceLocation StartLoc,
1496 SourceLocation NameLoc,
1497 IdentifierInfo *Name);
1498
1499 /// Rebuild the Objective-C exception declaration and register the
1500 /// declaration as an instantiated local.
1501 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1502 TypeSourceInfo *TSInfo, QualType T);
1503
1505 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1506 SourceLocation TemplateKWLoc, TemplateName Name,
1507 SourceLocation NameLoc,
1508 QualType ObjectType = QualType(),
1509 NamedDecl *FirstQualifierInScope = nullptr,
1510 bool AllowInjectedClassName = false);
1511
1512 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1513 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1514 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1515 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1516 const Stmt *InstS,
1517 const NoInlineAttr *A);
1518 const AlwaysInlineAttr *
1519 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1520 const AlwaysInlineAttr *A);
1521 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1522 const OpenACCRoutineDeclAttr *
1523 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1524 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1525 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1526 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1527
1528 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1529 NonTypeTemplateParmDecl *D);
1530
1531 /// Rebuild a DeclRefExpr for a VarDecl reference.
1532 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1533
1534 /// Transform a reference to a function or init-capture parameter pack.
1535 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1536
1537 /// Transform a FunctionParmPackExpr which was built when we couldn't
1538 /// expand a function parameter pack reference which refers to an expanded
1539 /// pack.
1540 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1541
1542 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1543 FunctionProtoTypeLoc TL) {
1544 // Call the base version; it will forward to our overridden version below.
1545 return inherited::TransformFunctionProtoType(TLB, TL);
1546 }
1547
1548 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1549 auto Type = inherited::TransformTagType(TLB, TL);
1550 if (!Type.isNull())
1551 return Type;
1552 // Special case for transforming a deduction guide, we return a
1553 // transformed TemplateSpecializationType.
1554 // FIXME: Why is this hack necessary?
1555 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(TL.getTypePtr());
1556 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1558 Type = inherited::TransformType(
1559 ICNT->getDecl()->getCanonicalTemplateSpecializationType(
1560 SemaRef.Context));
1561 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1562 }
1563 return Type;
1564 }
1565 // Override the default version to handle a rewrite-template-arg-pack case
1566 // for building a deduction guide.
1567 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1568 TemplateArgumentLoc &Output,
1569 bool Uneval = false) {
1570 const TemplateArgument &Arg = Input.getArgument();
1571 std::vector<TemplateArgument> TArgs;
1572 switch (Arg.getKind()) {
1574 assert(SemaRef.CodeSynthesisContexts.empty() ||
1575 SemaRef.CodeSynthesisContexts.back().Kind ==
1577 // Literally rewrite the template argument pack, instead of unpacking
1578 // it.
1579 for (auto &pack : Arg.getPackAsArray()) {
1580 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1581 pack, QualType(), SourceLocation{});
1582 TemplateArgumentLoc Output;
1583 if (TransformTemplateArgument(Input, Output, Uneval))
1584 return true; // fails
1585 TArgs.push_back(Output.getArgument());
1586 }
1587 Output = SemaRef.getTrivialTemplateArgumentLoc(
1588 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1589 QualType(), SourceLocation{});
1590 return false;
1591 default:
1592 break;
1593 }
1594 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1595 }
1596
1598 QualType
1599 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1600 TemplateSpecializationTypeLoc TL) {
1601 auto *T = TL.getTypePtr();
1602 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1603 !isPackProducingBuiltinTemplateName(T->getTemplateName()))
1605 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1606 // need to substitute into.
1607
1608 // `TransformType` code below will handle picking the element from a pack
1609 // with the index `ArgPackSubstIndex`.
1610 // FIXME: add ability to represent sugarred type for N-th element of a
1611 // builtin pack and produce the sugar here.
1612 QualType R = TransformType(T->desugar());
1613 TLB.pushTrivial(getSema().getASTContext(), R, TL.getBeginLoc());
1614 return R;
1615 }
1616
1617 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1618 ArrayRef<TemplateArgument> PackArgs) {
1619 // Don't do this when rewriting template parameters for CTAD:
1620 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1621 // expanded size, but this never applies since Subst* nodes are not
1622 // created in rewrite scenarios.
1623 //
1624 // 2) The heuristic substitutes into the pattern with pack expansion
1625 // suppressed, which does not meet the requirements for argument
1626 // rewriting when template arguments include a non-pack matching against
1627 // a pack, particularly when rewriting an alias CTAD.
1628 if (TemplateArgs.isRewrite())
1629 return std::nullopt;
1630
1631 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1632 }
1633
1634 template<typename Fn>
1635 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1636 FunctionProtoTypeLoc TL,
1637 CXXRecordDecl *ThisContext,
1638 Qualifiers ThisTypeQuals,
1639 Fn TransformExceptionSpec);
1640
1641 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1642 int indexAdjustment,
1643 UnsignedOrNone NumExpansions,
1644 bool ExpectParameterPack);
1645
1646 using inherited::TransformTemplateTypeParmType;
1647 /// Transforms a template type parameter type by performing
1648 /// substitution of the corresponding template type argument.
1649 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1650 TemplateTypeParmTypeLoc TL,
1651 bool SuppressObjCLifetime);
1652
1653 QualType BuildSubstTemplateTypeParmType(
1654 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1655 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1656 TemplateArgument Arg, SourceLocation NameLoc);
1657
1658 /// Transforms an already-substituted template type parameter pack
1659 /// into either itself (if we aren't substituting into its pack expansion)
1660 /// or the appropriate substituted argument.
1661 using inherited::TransformSubstTemplateTypeParmPackType;
1662 QualType
1663 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1664 SubstTemplateTypeParmPackTypeLoc TL,
1665 bool SuppressObjCLifetime);
1666 QualType
1667 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1668 SubstBuiltinTemplatePackTypeLoc TL);
1669
1671 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1672 if (auto TypeAlias =
1673 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1674 getSema());
1675 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1676 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1677 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1678 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1679 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1680 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1681 if (TA.isDependent())
1682 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1683 }
1684 return inherited::ComputeLambdaDependency(LSI);
1685 }
1686
1687 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1688 // Do not rebuild lambdas to avoid creating a new type.
1689 // Lambdas have already been processed inside their eval contexts.
1691 return E;
1692 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1693 /*InstantiatingLambdaOrBlock=*/true);
1694 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1695
1696 return inherited::TransformLambdaExpr(E);
1697 }
1698
1699 ExprResult TransformBlockExpr(BlockExpr *E) {
1700 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1701 /*InstantiatingLambdaOrBlock=*/true);
1702 return inherited::TransformBlockExpr(E);
1703 }
1704
1705 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1706 LambdaScopeInfo *LSI) {
1707 CXXMethodDecl *MD = LSI->CallOperator;
1708 for (ParmVarDecl *PVD : MD->parameters()) {
1709 assert(PVD && "null in a parameter list");
1710 if (!PVD->hasDefaultArg())
1711 continue;
1712 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1713 // FIXME: Obtain the source location for the '=' token.
1714 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1715 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1716 // If substitution fails, the default argument is set to a
1717 // RecoveryExpr that wraps the uninstantiated default argument so
1718 // that downstream diagnostics are omitted.
1719 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1720 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1721 UninstExpr->getType());
1722 if (ErrorResult.isUsable())
1723 PVD->setDefaultArg(ErrorResult.get());
1724 }
1725 }
1726 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1727 }
1728
1729 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1730 // Currently, we instantiate the body when instantiating the lambda
1731 // expression. However, `EvaluateConstraints` is disabled during the
1732 // instantiation of the lambda expression, causing the instantiation
1733 // failure of the return type requirement in the body. If p0588r1 is fully
1734 // implemented, the body will be lazily instantiated, and this problem
1735 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1736 // `true` to temporarily fix this issue.
1737 // FIXME: This temporary fix can be removed after fully implementing
1738 // p0588r1.
1739 llvm::SaveAndRestore _(EvaluateConstraints, true);
1740 return inherited::TransformLambdaBody(E, Body);
1741 }
1742
1743 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1744 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1745 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1746 if (TransReq.isInvalid())
1747 return TransReq;
1748 assert(TransReq.get() != E &&
1749 "Do not change value of isSatisfied for the existing expression. "
1750 "Create a new expression instead.");
1751 if (E->getBody()->isDependentContext()) {
1752 Sema::SFINAETrap Trap(SemaRef);
1753 // We recreate the RequiresExpr body, but not by instantiating it.
1754 // Produce pending diagnostics for dependent access check.
1755 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1756 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1757 if (Trap.hasErrorOccurred())
1758 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1759 }
1760 return TransReq;
1761 }
1762
1763 bool TransformRequiresExprRequirements(
1764 ArrayRef<concepts::Requirement *> Reqs,
1765 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1766 bool SatisfactionDetermined = false;
1767 for (concepts::Requirement *Req : Reqs) {
1768 concepts::Requirement *TransReq = nullptr;
1769 if (!SatisfactionDetermined) {
1770 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1771 TransReq = TransformTypeRequirement(TypeReq);
1772 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1773 TransReq = TransformExprRequirement(ExprReq);
1774 else
1775 TransReq = TransformNestedRequirement(
1777 if (!TransReq)
1778 return true;
1779 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1780 // [expr.prim.req]p6
1781 // [...] The substitution and semantic constraint checking
1782 // proceeds in lexical order and stops when a condition that
1783 // determines the result of the requires-expression is
1784 // encountered. [..]
1785 SatisfactionDetermined = true;
1786 } else
1787 TransReq = Req;
1788 Transformed.push_back(TransReq);
1789 }
1790 return false;
1791 }
1792
1793 TemplateParameterList *TransformTemplateParameterList(
1794 TemplateParameterList *OrigTPL) {
1795 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1796
1797 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1798 TemplateDeclInstantiator DeclInstantiator(getSema(),
1799 /* DeclContext *Owner */ Owner, TemplateArgs);
1800 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1801 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1802 }
1803
1804 concepts::TypeRequirement *
1805 TransformTypeRequirement(concepts::TypeRequirement *Req);
1806 concepts::ExprRequirement *
1807 TransformExprRequirement(concepts::ExprRequirement *Req);
1808 concepts::NestedRequirement *
1809 TransformNestedRequirement(concepts::NestedRequirement *Req);
1810 ExprResult TransformRequiresTypeParams(
1811 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1812 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1813 SmallVectorImpl<QualType> &PTypes,
1814 SmallVectorImpl<ParmVarDecl *> &TransParams,
1815 Sema::ExtParameterInfoBuilder &PInfos);
1816 };
1817}
1818
1819bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1820 if (T.isNull())
1821 return true;
1822
1825 return false;
1826
1827 getSema().MarkDeclarationsReferencedInType(Loc, T);
1828 return true;
1829}
1830
1831Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1832 if (!D)
1833 return nullptr;
1834
1835 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1836 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1837 // If the corresponding template argument is NULL or non-existent, it's
1838 // because we are performing instantiation from explicitly-specified
1839 // template arguments in a function template, but there were some
1840 // arguments left unspecified.
1841 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1842 TTP->getPosition())) {
1843 IsIncomplete = true;
1844 return BailOutOnIncomplete ? nullptr : D;
1845 }
1846
1847 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1848
1849 if (TTP->isParameterPack()) {
1850 assert(Arg.getKind() == TemplateArgument::Pack &&
1851 "Missing argument pack");
1852 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1853 }
1854
1856 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1857 "Wrong kind of template template argument");
1858 return Template.getAsTemplateDecl();
1859 }
1860
1861 // Fall through to find the instantiated declaration for this template
1862 // template parameter.
1863 }
1864
1865 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D);
1866 PVD && SemaRef.CurrentInstantiationScope &&
1867 (SemaRef.inConstraintSubstitution() ||
1868 SemaRef.inParameterMappingSubstitution()) &&
1869 maybeInstantiateFunctionParameterToScope(PVD))
1870 return nullptr;
1871
1872 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1873}
1874
1875bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope(
1876 ParmVarDecl *OldParm) {
1877 if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(OldParm))
1878 return false;
1879
1880 if (!OldParm->isParameterPack())
1881 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
1882 /*NumExpansions=*/std::nullopt,
1883 /*ExpectParameterPack=*/false);
1884
1885 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1886
1887 // Find the parameter packs that could be expanded.
1888 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
1889 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
1890 TypeLoc Pattern = ExpansionTL.getPatternLoc();
1891 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1892 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
1893
1894 bool ShouldExpand = false;
1895 bool RetainExpansion = false;
1896 UnsignedOrNone OrigNumExpansions =
1897 ExpansionTL.getTypePtr()->getNumExpansions();
1898 UnsignedOrNone NumExpansions = OrigNumExpansions;
1899 if (TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
1900 Pattern.getSourceRange(), Unexpanded,
1901 /*FailOnPackProducingTemplates=*/true,
1902 ShouldExpand, RetainExpansion, NumExpansions))
1903 return true;
1904
1905 assert(ShouldExpand && !RetainExpansion &&
1906 "Shouldn't preserve pack expansion when evaluating constraints");
1907 ExpandingFunctionParameterPack(OldParm);
1908 for (unsigned I = 0; I != *NumExpansions; ++I) {
1909 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
1910 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
1911 /*NumExpansions=*/OrigNumExpansions,
1912 /*ExpectParameterPack=*/false))
1913 return true;
1914 }
1915 return false;
1916}
1917
1918Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1919 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1920 if (!Inst)
1921 return nullptr;
1922
1923 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1924 return Inst;
1925}
1926
1927bool TemplateInstantiator::TransformExceptionSpec(
1928 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
1929 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1930 if (ESI.Type == EST_Uninstantiated) {
1931 ESI.instantiate();
1932 Changed = true;
1933 }
1934 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1935}
1936
1937NamedDecl *
1938TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1939 SourceLocation Loc) {
1940 // If the first part of the nested-name-specifier was a template type
1941 // parameter, instantiate that type parameter down to a tag type.
1942 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1943 const TemplateTypeParmType *TTP
1944 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1945
1946 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1947 // FIXME: This needs testing w/ member access expressions.
1948 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1949
1950 if (TTP->isParameterPack()) {
1951 assert(Arg.getKind() == TemplateArgument::Pack &&
1952 "Missing argument pack");
1953
1954 if (!getSema().ArgPackSubstIndex)
1955 return nullptr;
1956
1957 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1958 }
1959
1960 QualType T = Arg.getAsType();
1961 if (T.isNull())
1962 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1963
1964 if (const TagType *Tag = T->getAs<TagType>())
1965 return Tag->getDecl();
1966
1967 // The resulting type is not a tag; complain.
1968 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1969 return nullptr;
1970 }
1971 }
1972
1973 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1974}
1975
1976VarDecl *
1977TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1978 TypeSourceInfo *Declarator,
1979 SourceLocation StartLoc,
1980 SourceLocation NameLoc,
1981 IdentifierInfo *Name) {
1982 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1983 StartLoc, NameLoc, Name);
1984 if (Var)
1985 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1986 return Var;
1987}
1988
1989VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1990 TypeSourceInfo *TSInfo,
1991 QualType T) {
1992 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1993 if (Var)
1994 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1995 return Var;
1996}
1997
1998TemplateName TemplateInstantiator::TransformTemplateName(
1999 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2000 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2001 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2002 if (Name.getKind() == TemplateName::Template) {
2003 assert(!QualifierLoc && "Unexpected qualifier");
2004 if (auto *TTP =
2005 dyn_cast<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
2006 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2007 // If the corresponding template argument is NULL or non-existent, it's
2008 // because we are performing instantiation from explicitly-specified
2009 // template arguments in a function template, but there were some
2010 // arguments left unspecified.
2011 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2012 TTP->getPosition())) {
2013 IsIncomplete = true;
2014 return BailOutOnIncomplete ? TemplateName() : Name;
2015 }
2016
2017 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2018
2019 if (TemplateArgs.isRewrite()) {
2020 // We're rewriting the template parameter as a reference to another
2021 // template parameter.
2022 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2023 assert(Arg.getKind() == TemplateArgument::Template &&
2024 "unexpected nontype template argument kind in template rewrite");
2025 return Arg.getAsTemplate();
2026 }
2027
2028 auto [AssociatedDecl, Final] =
2029 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2030 UnsignedOrNone PackIndex = std::nullopt;
2031 if (TTP->isParameterPack()) {
2032 assert(Arg.getKind() == TemplateArgument::Pack &&
2033 "Missing argument pack");
2034
2035 if (!getSema().ArgPackSubstIndex) {
2036 // We have the template argument pack to substitute, but we're not
2037 // actually expanding the enclosing pack expansion yet. So, just
2038 // keep the entire argument pack.
2039 return getSema().Context.getSubstTemplateTemplateParmPack(
2040 Arg, AssociatedDecl, TTP->getIndex(), Final);
2041 }
2042
2043 PackIndex = SemaRef.getPackIndex(Arg);
2044 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2045 }
2046
2048 assert(!Template.isNull() && "Null template template argument");
2049 return getSema().Context.getSubstTemplateTemplateParm(
2050 Template, AssociatedDecl, TTP->getIndex(), PackIndex, Final);
2051 }
2052 }
2053
2054 if (SubstTemplateTemplateParmPackStorage *SubstPack
2056 if (!getSema().ArgPackSubstIndex)
2057 return Name;
2058
2059 TemplateArgument Pack = SubstPack->getArgumentPack();
2061 SemaRef.getPackSubstitutedTemplateArgument(Pack).getAsTemplate();
2062 return getSema().Context.getSubstTemplateTemplateParm(
2063 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2064 SemaRef.getPackIndex(Pack), SubstPack->getFinal());
2065 }
2066
2067 return inherited::TransformTemplateName(
2068 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2069 FirstQualifierInScope, AllowInjectedClassName);
2070}
2071
2073TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2074 if (!E->isTypeDependent())
2075 return E;
2076
2077 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2078}
2079
2081TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2082 NonTypeTemplateParmDecl *NTTP) {
2083 // If the corresponding template argument is NULL or non-existent, it's
2084 // because we are performing instantiation from explicitly-specified
2085 // template arguments in a function template, but there were some
2086 // arguments left unspecified.
2087 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2088 NTTP->getPosition())) {
2089 IsIncomplete = true;
2090 return BailOutOnIncomplete ? ExprError() : E;
2091 }
2092
2093 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2094
2095 if (TemplateArgs.isRewrite()) {
2096 // We're rewriting the template parameter as a reference to another
2097 // template parameter.
2098 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2099 assert(Arg.getKind() == TemplateArgument::Expression &&
2100 "unexpected nontype template argument kind in template rewrite");
2101 // FIXME: This can lead to the same subexpression appearing multiple times
2102 // in a complete expression.
2103 return Arg.getAsExpr();
2104 }
2105
2106 auto [AssociatedDecl, Final] =
2107 TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2108 UnsignedOrNone PackIndex = std::nullopt;
2109 if (NTTP->isParameterPack()) {
2110 assert(Arg.getKind() == TemplateArgument::Pack &&
2111 "Missing argument pack");
2112
2113 if (!getSema().ArgPackSubstIndex) {
2114 // We have an argument pack, but we can't select a particular argument
2115 // out of it yet. Therefore, we'll build an expression to hold on to that
2116 // argument pack.
2117 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2118 E->getLocation(),
2119 NTTP->getDeclName());
2120 if (TargetType.isNull())
2121 return ExprError();
2122
2123 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2124 if (TargetType->isRecordType())
2125 ExprType.addConst();
2126 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2127 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2128 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2129 }
2130 PackIndex = SemaRef.getPackIndex(Arg);
2131 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2132 }
2133 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2134 AssociatedDecl, NTTP, E->getLocation(), Arg, PackIndex, Final);
2135}
2136
2137const AnnotateAttr *
2138TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2139 SmallVector<Expr *> Args;
2140 for (Expr *Arg : AA->args()) {
2141 ExprResult Res = getDerived().TransformExpr(Arg);
2142 if (Res.isUsable())
2143 Args.push_back(Res.get());
2144 }
2145 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2146 Args.data(), Args.size(), AA->getRange());
2147}
2148
2149const CXXAssumeAttr *
2150TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2151 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2152 if (!Res.isUsable())
2153 return AA;
2154
2155 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2156 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2157 AA->getRange());
2158 if (!Res.isUsable())
2159 return AA;
2160 }
2161
2162 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2163 AA->getRange());
2164}
2165
2166const LoopHintAttr *
2167TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2168 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2169
2170 if (TransformedExpr == LH->getValue())
2171 return LH;
2172
2173 // Generate error if there is a problem with the value.
2174 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2175 /*AllowZero=*/LH->getSemanticSpelling() ==
2176 LoopHintAttr::Pragma_unroll))
2177 return LH;
2178
2179 LoopHintAttr::OptionType Option = LH->getOption();
2180 LoopHintAttr::LoopHintState State = LH->getState();
2181
2182 // Since C++ does not have partial instantiation, we would expect a
2183 // transformed loop hint expression to not be value dependent. However, at
2184 // the time of writing, the use of a generic lambda inside a template
2185 // triggers a double instantiation, so we must protect against this event.
2186 // This provision may become unneeded in the future.
2187 if (Option == LoopHintAttr::UnrollCount &&
2188 !TransformedExpr->isValueDependent()) {
2189 llvm::APSInt ValueAPS =
2190 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2191 // The values of 0 and 1 block any unrolling of the loop (also see
2192 // handleLoopHintAttr in SemaStmtAttr).
2193 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2194 Option = LoopHintAttr::Unroll;
2195 State = LoopHintAttr::Disable;
2196 }
2197 }
2198
2199 // Create new LoopHintValueAttr with integral expression in place of the
2200 // non-type template parameter.
2201 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2202 TransformedExpr, *LH);
2203}
2204const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2205 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2206 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2207 return nullptr;
2208
2209 return A;
2210}
2211const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2212 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2213 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2214 return nullptr;
2215
2216 return A;
2217}
2218
2219const CodeAlignAttr *
2220TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2221 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2222 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2223}
2224const OpenACCRoutineDeclAttr *
2225TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2226 const OpenACCRoutineDeclAttr *A) {
2227 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2228 "applies to a Function Decl (and a few places for VarDecl)");
2229}
2230
2231ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2232 SourceLocation Loc) {
2233 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2234 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2235}
2236
2238TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2239 if (getSema().ArgPackSubstIndex) {
2240 // We can expand this parameter pack now.
2241 ValueDecl *D = E->getExpansion(*getSema().ArgPackSubstIndex);
2242 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
2243 if (!VD)
2244 return ExprError();
2245 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2246 }
2247
2248 QualType T = TransformType(E->getType());
2249 if (T.isNull())
2250 return ExprError();
2251
2252 // Transform each of the parameter expansions into the corresponding
2253 // parameters in the instantiation of the function decl.
2254 SmallVector<ValueDecl *, 8> Vars;
2255 Vars.reserve(E->getNumExpansions());
2256 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2257 I != End; ++I) {
2258 ValueDecl *D = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), *I));
2259 if (!D)
2260 return ExprError();
2261 Vars.push_back(D);
2262 }
2263
2264 auto *PackExpr =
2266 E->getParameterPackLocation(), Vars);
2267 getSema().MarkFunctionParmPackReferenced(PackExpr);
2268 return PackExpr;
2269}
2270
2272TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2273 ValueDecl *PD) {
2274 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2275 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2276 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2277 assert(Found && "no instantiation for parameter pack");
2278
2279 Decl *TransformedDecl;
2280 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(*Found)) {
2281 // If this is a reference to a function parameter pack which we can
2282 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2283 if (!getSema().ArgPackSubstIndex) {
2284 QualType T = TransformType(E->getType());
2285 if (T.isNull())
2286 return ExprError();
2287 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2288 E->getExprLoc(), *Pack);
2289 getSema().MarkFunctionParmPackReferenced(PackExpr);
2290 return PackExpr;
2291 }
2292
2293 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2294 } else {
2295 TransformedDecl = cast<Decl *>(*Found);
2296 }
2297
2298 // We have either an unexpanded pack or a specific expansion.
2299 return RebuildVarDeclRefExpr(cast<ValueDecl>(TransformedDecl),
2300 E->getExprLoc());
2301}
2302
2304TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2305 NamedDecl *D = E->getDecl();
2306
2307 // Handle references to non-type template parameters and non-type template
2308 // parameter packs.
2309 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2310 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2311 return TransformTemplateParmRefExpr(E, NTTP);
2312
2313 // We have a non-type template parameter that isn't fully substituted;
2314 // FindInstantiatedDecl will find it in the local instantiation scope.
2315 }
2316
2317 // Handle references to function parameter packs.
2318 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2319 if (PD->isParameterPack())
2320 return TransformFunctionParmPackRefExpr(E, PD);
2321
2322 return inherited::TransformDeclRefExpr(E);
2323}
2324
2325ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2326 CXXDefaultArgExpr *E) {
2327 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2328 getDescribedFunctionTemplate() &&
2329 "Default arg expressions are never formed in dependent cases.");
2330 return SemaRef.BuildCXXDefaultArgExpr(
2332 E->getParam());
2333}
2334
2335template<typename Fn>
2336QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2337 FunctionProtoTypeLoc TL,
2338 CXXRecordDecl *ThisContext,
2339 Qualifiers ThisTypeQuals,
2340 Fn TransformExceptionSpec) {
2341 // If this is a lambda or block, the transformation MUST be done in the
2342 // CurrentInstantiationScope since it introduces a mapping of
2343 // the original to the newly created transformed parameters.
2344 //
2345 // In that case, TemplateInstantiator::TransformLambdaExpr will
2346 // have already pushed a scope for this prototype, so don't create
2347 // a second one.
2348 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2349 std::optional<LocalInstantiationScope> Scope;
2350 if (!Current || !Current->isLambdaOrBlock())
2351 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2352
2353 return inherited::TransformFunctionProtoType(
2354 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2355}
2356
2357ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2358 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2359 bool ExpectParameterPack) {
2360 auto NewParm = SemaRef.SubstParmVarDecl(
2361 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2362 ExpectParameterPack, EvaluateConstraints);
2363 if (NewParm && SemaRef.getLangOpts().OpenCL)
2364 SemaRef.deduceOpenCLAddressSpace(NewParm);
2365 return NewParm;
2366}
2367
2368QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2369 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2370 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2371 TemplateArgument Arg, SourceLocation NameLoc) {
2372 QualType Replacement = Arg.getAsType();
2373
2374 // If the template parameter had ObjC lifetime qualifiers,
2375 // then any such qualifiers on the replacement type are ignored.
2376 if (SuppressObjCLifetime) {
2377 Qualifiers RQs;
2378 RQs = Replacement.getQualifiers();
2379 RQs.removeObjCLifetime();
2380 Replacement =
2381 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2382 }
2383
2384 // TODO: only do this uniquing once, at the start of instantiation.
2385 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2386 Replacement, AssociatedDecl, Index, PackIndex, Final);
2387 SubstTemplateTypeParmTypeLoc NewTL =
2388 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2389 NewTL.setNameLoc(NameLoc);
2390 return Result;
2391}
2392
2393QualType
2394TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2395 TemplateTypeParmTypeLoc TL,
2396 bool SuppressObjCLifetime) {
2397 const TemplateTypeParmType *T = TL.getTypePtr();
2398 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2399 // Replace the template type parameter with its corresponding
2400 // template argument.
2401
2402 // If the corresponding template argument is NULL or doesn't exist, it's
2403 // because we are performing instantiation from explicitly-specified
2404 // template arguments in a function template class, but there were some
2405 // arguments left unspecified.
2406 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2407 IsIncomplete = true;
2408 if (BailOutOnIncomplete)
2409 return QualType();
2410
2411 TemplateTypeParmTypeLoc NewTL
2412 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2413 NewTL.setNameLoc(TL.getNameLoc());
2414 return TL.getType();
2415 }
2416
2417 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2418
2419 if (TemplateArgs.isRewrite()) {
2420 // We're rewriting the template parameter as a reference to another
2421 // template parameter.
2422 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2423 assert(Arg.getKind() == TemplateArgument::Type &&
2424 "unexpected nontype template argument kind in template rewrite");
2425 QualType NewT = Arg.getAsType();
2426 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2427 return NewT;
2428 }
2429
2430 auto [AssociatedDecl, Final] =
2431 TemplateArgs.getAssociatedDecl(T->getDepth());
2432 UnsignedOrNone PackIndex = std::nullopt;
2433 if (T->isParameterPack() ||
2434 // In concept parameter mapping for fold expressions, packs that aren't
2435 // expanded in place are treated as having non-pack dependency, so that
2436 // a PackExpansionType won't prevent expanding the packs outside the
2437 // TreeTransform. However, we still need to unpack the arguments during
2438 // any template argument substitution, so we check the associated
2439 // declaration instead.
2440 (T->getDecl() && T->getDecl()->isTemplateParameterPack())) {
2441 assert(Arg.getKind() == TemplateArgument::Pack &&
2442 "Missing argument pack");
2443
2444 if (!getSema().ArgPackSubstIndex) {
2445 // We have the template argument pack, but we're not expanding the
2446 // enclosing pack expansion yet. Just save the template argument
2447 // pack for later substitution.
2448 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2449 AssociatedDecl, T->getIndex(), Final, Arg);
2450 SubstTemplateTypeParmPackTypeLoc NewTL
2451 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2452 NewTL.setNameLoc(TL.getNameLoc());
2453 return Result;
2454 }
2455
2456 // PackIndex starts from last element.
2457 PackIndex = SemaRef.getPackIndex(Arg);
2458 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2459 }
2460
2461 assert(Arg.getKind() == TemplateArgument::Type &&
2462 "Template argument kind mismatch");
2463
2464 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2465 AssociatedDecl, T->getIndex(),
2466 PackIndex, Arg, TL.getNameLoc());
2467 }
2468
2469 // The template type parameter comes from an inner template (e.g.,
2470 // the template parameter list of a member template inside the
2471 // template we are instantiating). Create a new template type
2472 // parameter with the template "level" reduced by one.
2473 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2474 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2475 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2476 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2477 QualType Result = getSema().Context.getTemplateTypeParmType(
2478 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2479 T->isParameterPack(), NewTTPDecl);
2480 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2481 NewTL.setNameLoc(TL.getNameLoc());
2482 return Result;
2483}
2484
2485QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2486 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2487 bool SuppressObjCLifetime) {
2488 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2489
2490 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2491
2492 if (!getSema().ArgPackSubstIndex) {
2493 // We aren't expanding the parameter pack, so just return ourselves.
2494 QualType Result = TL.getType();
2495 if (NewReplaced != T->getAssociatedDecl())
2496 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2497 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2498 SubstTemplateTypeParmPackTypeLoc NewTL =
2499 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2500 NewTL.setNameLoc(TL.getNameLoc());
2501 return Result;
2502 }
2503
2504 TemplateArgument Pack = T->getArgumentPack();
2505 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Pack);
2506 return BuildSubstTemplateTypeParmType(
2507 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2508 SemaRef.getPackIndex(Pack), Arg, TL.getNameLoc());
2509}
2510
2511QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2512 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2513 if (!getSema().ArgPackSubstIndex)
2514 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2515 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2516 TL.getTypePtr()->getArgumentPack());
2517 TLB.pushTrivial(SemaRef.getASTContext(), Result.getAsType(),
2518 TL.getBeginLoc());
2519 return Result.getAsType();
2520}
2521
2522static concepts::Requirement::SubstitutionDiagnostic *
2524 Sema::EntityPrinter Printer) {
2525 SmallString<128> Message;
2526 SourceLocation ErrorLoc;
2527 if (Info.hasSFINAEDiagnostic()) {
2530 Info.takeSFINAEDiagnostic(PDA);
2531 PDA.second.EmitToString(S.getDiagnostics(), Message);
2532 ErrorLoc = PDA.first;
2533 } else {
2534 ErrorLoc = Info.getLocation();
2535 }
2536 SmallString<128> Entity;
2537 llvm::raw_svector_ostream OS(Entity);
2538 Printer(OS);
2539 const ASTContext &C = S.Context;
2541 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2542}
2543
2544concepts::Requirement::SubstitutionDiagnostic *
2546 SmallString<128> Entity;
2547 llvm::raw_svector_ostream OS(Entity);
2548 Printer(OS);
2549 const ASTContext &C = Context;
2551 /*SubstitutedEntity=*/C.backupStr(Entity),
2552 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2553}
2554
2555ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2556 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2559 SmallVectorImpl<ParmVarDecl *> &TransParams,
2561
2562 TemplateDeductionInfo Info(KWLoc);
2563 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE,
2564 SourceRange{KWLoc, RBraceLoc});
2565 Sema::SFINAETrap Trap(SemaRef, Info);
2566
2567 unsigned ErrorIdx;
2568 if (getDerived().TransformFunctionTypeParams(
2569 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2570 &TransParams, PInfos, &ErrorIdx) ||
2571 Trap.hasErrorOccurred()) {
2573 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2574 // Add a 'failed' Requirement to contain the error that caused the failure
2575 // here.
2576 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2577 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2578 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2579 TransParams, RE->getRParenLoc(),
2580 TransReqs, RBraceLoc);
2581 }
2582
2583 return ExprResult{};
2584}
2585
2586concepts::TypeRequirement *
2587TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2588 if (!Req->isDependent() && !AlwaysRebuild())
2589 return Req;
2590 if (Req->isSubstitutionFailure()) {
2591 if (AlwaysRebuild())
2592 return RebuildTypeRequirement(
2594 return Req;
2595 }
2596
2597 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2598 Sema::SFINAETrap Trap(SemaRef, Info);
2599 Sema::InstantiatingTemplate TypeInst(
2600 SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req,
2601 Req->getType()->getTypeLoc().getSourceRange());
2602 if (TypeInst.isInvalid())
2603 return nullptr;
2604 TypeSourceInfo *TransType = TransformType(Req->getType());
2605 if (!TransType || Trap.hasErrorOccurred())
2606 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2607 [&] (llvm::raw_ostream& OS) {
2608 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2609 }));
2610 return RebuildTypeRequirement(TransType);
2611}
2612
2613concepts::ExprRequirement *
2614TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2615 if (!Req->isDependent() && !AlwaysRebuild())
2616 return Req;
2617
2618 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2619 TransExpr;
2620 if (Req->isExprSubstitutionFailure())
2621 TransExpr = Req->getExprSubstitutionDiagnostic();
2622 else {
2623 Expr *E = Req->getExpr();
2624 TemplateDeductionInfo Info(E->getBeginLoc());
2625 Sema::SFINAETrap Trap(SemaRef, Info);
2626 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req,
2627 E->getSourceRange());
2628 if (ExprInst.isInvalid())
2629 return nullptr;
2630 ExprResult TransExprRes = TransformExpr(E);
2631 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2632 TransExprRes.get()->hasPlaceholderType())
2633 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2634 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2635 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2636 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2637 });
2638 else
2639 TransExpr = TransExprRes.get();
2640 }
2641
2642 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2643 const auto &RetReq = Req->getReturnTypeRequirement();
2644 if (RetReq.isEmpty())
2645 TransRetReq.emplace();
2646 else if (RetReq.isSubstitutionFailure())
2647 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2648 else if (RetReq.isTypeConstraint()) {
2649 TemplateParameterList *OrigTPL =
2650 RetReq.getTypeConstraintTemplateParameterList();
2651 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2652 Sema::SFINAETrap Trap(SemaRef, Info);
2653 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req,
2654 OrigTPL->getSourceRange());
2655 if (TPLInst.isInvalid())
2656 return nullptr;
2657 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2658 if (!TPL || Trap.hasErrorOccurred())
2659 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2660 [&] (llvm::raw_ostream& OS) {
2661 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2662 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2663 }));
2664 else {
2665 TPLInst.Clear();
2666 TransRetReq.emplace(TPL);
2667 }
2668 }
2669 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2670 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2671 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2672 std::move(*TransRetReq));
2673 return RebuildExprRequirement(
2675 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2676}
2677
2678concepts::NestedRequirement *
2679TemplateInstantiator::TransformNestedRequirement(
2680 concepts::NestedRequirement *Req) {
2681
2682 ASTContext &C = SemaRef.Context;
2683
2684 Expr *Constraint = Req->getConstraintExpr();
2685 ConstraintSatisfaction Satisfaction;
2686
2687 auto NestedReqWithDiag = [&C, this](Expr *E,
2688 ConstraintSatisfaction Satisfaction) {
2689 Satisfaction.IsSatisfied = false;
2690 SmallString<128> Entity;
2691 llvm::raw_svector_ostream OS(Entity);
2692 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2693 return new (C) concepts::NestedRequirement(
2694 SemaRef.Context, C.backupStr(Entity), std::move(Satisfaction));
2695 };
2696
2697 if (Req->hasInvalidConstraint()) {
2698 if (AlwaysRebuild())
2699 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2701 return Req;
2702 }
2703
2704 if (!getEvaluateConstraints()) {
2705 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2706 if (TransConstraint.isInvalid() || !TransConstraint.get())
2707 return nullptr;
2708 if (TransConstraint.get()->isInstantiationDependent())
2709 return new (SemaRef.Context)
2710 concepts::NestedRequirement(TransConstraint.get());
2711 ConstraintSatisfaction Satisfaction;
2712 return new (SemaRef.Context) concepts::NestedRequirement(
2713 SemaRef.Context, TransConstraint.get(), Satisfaction);
2714 }
2715
2716 bool Success;
2717 Expr *NewConstraint;
2718 {
2719 EnterExpressionEvaluationContext ContextRAII(
2721 Sema::InstantiatingTemplate ConstrInst(
2722 SemaRef, Constraint->getBeginLoc(), Req,
2723 Sema::InstantiatingTemplate::ConstraintsCheck(),
2724 Constraint->getSourceRange());
2725
2726 if (ConstrInst.isInvalid())
2727 return nullptr;
2728
2729 Success = !SemaRef.CheckConstraintSatisfaction(
2730 Req, AssociatedConstraint(Constraint, SemaRef.ArgPackSubstIndex),
2731 TemplateArgs, Constraint->getSourceRange(), Satisfaction,
2732 /*TopLevelConceptId=*/nullptr, &NewConstraint);
2733 }
2734
2735 if (!Success || Satisfaction.HasSubstitutionFailure())
2736 return NestedReqWithDiag(Constraint, Satisfaction);
2737
2738 // FIXME: const correctness
2739 // MLTAL might be dependent.
2740 if (!NewConstraint) {
2741 if (!Satisfaction.IsSatisfied)
2742 return NestedReqWithDiag(Constraint, Satisfaction);
2743
2744 NewConstraint = Constraint;
2745 }
2746 return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);
2747}
2748
2751 SourceLocation Loc,
2752 DeclarationName Entity,
2753 bool AllowDeducedTST) {
2754 assert(!CodeSynthesisContexts.empty() &&
2755 "Cannot perform an instantiation without some context on the "
2756 "instantiation stack");
2757
2758 if (!T->getType()->isInstantiationDependentType() &&
2759 !T->getType()->isVariablyModifiedType())
2760 return T;
2761
2762 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2763 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2764 : Instantiator.TransformType(T);
2765}
2766
2769 SourceLocation Loc,
2770 DeclarationName Entity) {
2771 assert(!CodeSynthesisContexts.empty() &&
2772 "Cannot perform an instantiation without some context on the "
2773 "instantiation stack");
2774
2775 if (TL.getType().isNull())
2776 return nullptr;
2777
2780 // FIXME: Make a copy of the TypeLoc data here, so that we can
2781 // return a new TypeSourceInfo. Inefficient!
2782 TypeLocBuilder TLB;
2783 TLB.pushFullCopy(TL);
2784 return TLB.getTypeSourceInfo(Context, TL.getType());
2785 }
2786
2787 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2788 TypeLocBuilder TLB;
2789 TLB.reserve(TL.getFullDataSize());
2790 QualType Result = Instantiator.TransformType(TLB, TL);
2791 if (Result.isNull())
2792 return nullptr;
2793
2794 return TLB.getTypeSourceInfo(Context, Result);
2795}
2796
2797/// Deprecated form of the above.
2799 const MultiLevelTemplateArgumentList &TemplateArgs,
2800 SourceLocation Loc, DeclarationName Entity,
2801 bool *IsIncompleteSubstitution) {
2802 assert(!CodeSynthesisContexts.empty() &&
2803 "Cannot perform an instantiation without some context on the "
2804 "instantiation stack");
2805
2806 // If T is not a dependent type or a variably-modified type, there
2807 // is nothing to do.
2808 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2809 return T;
2810
2811 TemplateInstantiator Instantiator(
2812 *this, TemplateArgs, Loc, Entity,
2813 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2814 QualType QT = Instantiator.TransformType(T);
2815 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2816 *IsIncompleteSubstitution = true;
2817 return QT;
2818}
2819
2821 if (T->getType()->isInstantiationDependentType() ||
2822 T->getType()->isVariablyModifiedType())
2823 return true;
2824
2825 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2826 if (!TL.getAs<FunctionProtoTypeLoc>())
2827 return false;
2828
2830 for (ParmVarDecl *P : FP.getParams()) {
2831 // This must be synthesized from a typedef.
2832 if (!P) continue;
2833
2834 // If there are any parameters, a new TypeSourceInfo that refers to the
2835 // instantiated parameters must be built.
2836 return true;
2837 }
2838
2839 return false;
2840}
2841
2844 SourceLocation Loc,
2845 DeclarationName Entity,
2846 CXXRecordDecl *ThisContext,
2847 Qualifiers ThisTypeQuals,
2848 bool EvaluateConstraints) {
2849 assert(!CodeSynthesisContexts.empty() &&
2850 "Cannot perform an instantiation without some context on the "
2851 "instantiation stack");
2852
2854 return T;
2855
2856 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2857 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2858
2859 TypeLocBuilder TLB;
2860
2861 TypeLoc TL = T->getTypeLoc();
2862 TLB.reserve(TL.getFullDataSize());
2863
2865
2866 if (FunctionProtoTypeLoc Proto =
2868 // Instantiate the type, other than its exception specification. The
2869 // exception specification is instantiated in InitFunctionInstantiation
2870 // once we've built the FunctionDecl.
2871 // FIXME: Set the exception specification to EST_Uninstantiated here,
2872 // instead of rebuilding the function type again later.
2873 Result = Instantiator.TransformFunctionProtoType(
2874 TLB, Proto, ThisContext, ThisTypeQuals,
2876 bool &Changed) { return false; });
2877 } else {
2878 Result = Instantiator.TransformType(TLB, TL);
2879 }
2880 // When there are errors resolving types, clang may use IntTy as a fallback,
2881 // breaking our assumption that function declarations have function types.
2882 if (Result.isNull() || !Result->isFunctionType())
2883 return nullptr;
2884
2885 return TLB.getTypeSourceInfo(Context, Result);
2886}
2887
2890 SmallVectorImpl<QualType> &ExceptionStorage,
2891 const MultiLevelTemplateArgumentList &Args) {
2892 bool Changed = false;
2893 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2894 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2895 Changed);
2896}
2897
2899 const MultiLevelTemplateArgumentList &Args) {
2902
2903 SmallVector<QualType, 4> ExceptionStorage;
2904 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2905 ESI, ExceptionStorage, Args))
2906 // On error, recover by dropping the exception specification.
2907 ESI.Type = EST_None;
2908
2910}
2911
2912namespace {
2913
2914 struct GetContainedInventedTypeParmVisitor :
2915 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2916 TemplateTypeParmDecl *> {
2917 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2918 TemplateTypeParmDecl *>::Visit;
2919
2921 if (T.isNull())
2922 return nullptr;
2923 return Visit(T.getTypePtr());
2924 }
2925 // The deduced type itself.
2926 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2927 const TemplateTypeParmType *T) {
2928 if (!T->getDecl() || !T->getDecl()->isImplicit())
2929 return nullptr;
2930 return T->getDecl();
2931 }
2932
2933 // Only these types can contain 'auto' types, and subsequently be replaced
2934 // by references to invented parameters.
2935
2936 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2937 return Visit(T->getPointeeType());
2938 }
2939
2940 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2941 return Visit(T->getPointeeType());
2942 }
2943
2944 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2945 return Visit(T->getPointeeTypeAsWritten());
2946 }
2947
2948 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2949 return Visit(T->getPointeeType());
2950 }
2951
2952 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2953 return Visit(T->getElementType());
2954 }
2955
2956 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2957 const DependentSizedExtVectorType *T) {
2958 return Visit(T->getElementType());
2959 }
2960
2961 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2962 return Visit(T->getElementType());
2963 }
2964
2965 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2966 return VisitFunctionType(T);
2967 }
2968
2969 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2970 return Visit(T->getReturnType());
2971 }
2972
2973 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2974 return Visit(T->getInnerType());
2975 }
2976
2977 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2978 return Visit(T->getModifiedType());
2979 }
2980
2981 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2982 return Visit(T->getUnderlyingType());
2983 }
2984
2985 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2986 return Visit(T->getOriginalType());
2987 }
2988
2989 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2990 return Visit(T->getPattern());
2991 }
2992 };
2993
2994} // namespace
2995
2997 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2998 const MultiLevelTemplateArgumentList &TemplateArgs,
2999 bool EvaluateConstraints) {
3000 const ASTTemplateArgumentListInfo *TemplArgInfo =
3002
3003 if (!EvaluateConstraints && !inParameterMappingSubstitution()) {
3005 if (!Index)
3006 Index = SemaRef.ArgPackSubstIndex;
3009 return false;
3010 }
3011
3012 TemplateArgumentListInfo InstArgs;
3013
3014 if (TemplArgInfo) {
3015 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3016 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3017 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3018 InstArgs))
3019 return true;
3020 }
3021 return AttachTypeConstraint(
3023 TC->getNamedConcept(),
3024 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3025 Inst->isParameterPack()
3027 ->getEllipsisLoc()
3028 : SourceLocation());
3029}
3030
3033 const MultiLevelTemplateArgumentList &TemplateArgs,
3034 int indexAdjustment, UnsignedOrNone NumExpansions,
3035 bool ExpectParameterPack, bool EvaluateConstraint) {
3036 TypeSourceInfo *OldTSI = OldParm->getTypeSourceInfo();
3037 TypeSourceInfo *NewTSI = nullptr;
3038
3039 TypeLoc OldTL = OldTSI->getTypeLoc();
3040 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3041
3042 // We have a function parameter pack. Substitute into the pattern of the
3043 // expansion.
3044 NewTSI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3045 OldParm->getLocation(), OldParm->getDeclName());
3046 if (!NewTSI)
3047 return nullptr;
3048
3049 if (NewTSI->getType()->containsUnexpandedParameterPack()) {
3050 // We still have unexpanded parameter packs, which means that
3051 // our function parameter is still a function parameter pack.
3052 // Therefore, make its type a pack expansion type.
3053 NewTSI = CheckPackExpansion(NewTSI, ExpansionTL.getEllipsisLoc(),
3054 NumExpansions);
3055 } else if (ExpectParameterPack) {
3056 // We expected to get a parameter pack but didn't (because the type
3057 // itself is not a pack expansion type), so complain. This can occur when
3058 // the substitution goes through an alias template that "loses" the
3059 // pack expansion.
3060 Diag(OldParm->getLocation(),
3061 diag::err_function_parameter_pack_without_parameter_packs)
3062 << NewTSI->getType();
3063 return nullptr;
3064 }
3065 } else {
3066 NewTSI = SubstType(OldTSI, TemplateArgs, OldParm->getLocation(),
3067 OldParm->getDeclName());
3068 }
3069
3070 if (!NewTSI)
3071 return nullptr;
3072
3073 if (NewTSI->getType()->isVoidType()) {
3074 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3075 return nullptr;
3076 }
3077
3078 // In abbreviated templates, TemplateTypeParmDecls with possible
3079 // TypeConstraints are created when the parameter list is originally parsed.
3080 // The TypeConstraints can therefore reference other functions parameters in
3081 // the abbreviated function template, which is why we must instantiate them
3082 // here, when the instantiated versions of those referenced parameters are in
3083 // scope.
3084 if (TemplateTypeParmDecl *TTP =
3085 GetContainedInventedTypeParmVisitor().Visit(OldTSI->getType())) {
3086 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3087 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3088 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3089 // We will first get here when instantiating the abbreviated function
3090 // template's described function, but we might also get here later.
3091 // Make sure we do not instantiate the TypeConstraint more than once.
3092 if (Inst && !Inst->getTypeConstraint()) {
3093 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3094 return nullptr;
3095 }
3096 }
3097 }
3098
3099 ParmVarDecl *NewParm = CheckParameter(
3100 Context.getTranslationUnitDecl(), OldParm->getInnerLocStart(),
3101 OldParm->getLocation(), OldParm->getIdentifier(), NewTSI->getType(),
3102 NewTSI, OldParm->getStorageClass());
3103 if (!NewParm)
3104 return nullptr;
3105
3106 // Mark the (new) default argument as uninstantiated (if any).
3107 if (OldParm->hasUninstantiatedDefaultArg()) {
3108 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3109 NewParm->setUninstantiatedDefaultArg(Arg);
3110 } else if (OldParm->hasUnparsedDefaultArg()) {
3111 NewParm->setUnparsedDefaultArg();
3112 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3113 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3114 // Default arguments cannot be substituted until the declaration context
3115 // for the associated function or lambda capture class is available.
3116 // This is necessary for cases like the following where construction of
3117 // the lambda capture class for the outer lambda is dependent on the
3118 // parameter types but where the default argument is dependent on the
3119 // outer lambda's declaration context.
3120 // template <typename T>
3121 // auto f() {
3122 // return [](T = []{ return T{}; }()) { return 0; };
3123 // }
3124 NewParm->setUninstantiatedDefaultArg(Arg);
3125 }
3126
3130
3131 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3132 // Add the new parameter to the instantiated parameter pack.
3133 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
3134 } else {
3135 // Introduce an Old -> New mapping
3136 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
3137 }
3138
3139 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3140 // can be anything, is this right ?
3141 NewParm->setDeclContext(CurContext);
3142
3143 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3144 OldParm->getFunctionScopeIndex() + indexAdjustment);
3145
3146 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3147
3148 return NewParm;
3149}
3150
3153 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3154 const MultiLevelTemplateArgumentList &TemplateArgs,
3155 SmallVectorImpl<QualType> &ParamTypes,
3157 ExtParameterInfoBuilder &ParamInfos) {
3158 assert(!CodeSynthesisContexts.empty() &&
3159 "Cannot perform an instantiation without some context on the "
3160 "instantiation stack");
3161
3162 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3163 DeclarationName());
3164 return Instantiator.TransformFunctionTypeParams(
3165 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3166}
3167
3169 SourceLocation Loc,
3170 ParmVarDecl *Param,
3171 const MultiLevelTemplateArgumentList &TemplateArgs,
3172 bool ForCallExpr) {
3173 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3174 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3175
3176 RecursiveInstGuard AlreadyInstantiating(
3178 if (AlreadyInstantiating) {
3179 Param->setInvalidDecl();
3180 return Diag(Param->getBeginLoc(), diag::err_recursive_default_argument)
3181 << FD << PatternExpr->getSourceRange();
3182 }
3183
3186 NonSFINAEContext _(*this);
3187 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3188 if (Inst.isInvalid())
3189 return true;
3190
3192 // C++ [dcl.fct.default]p5:
3193 // The names in the [default argument] expression are bound, and
3194 // the semantic constraints are checked, at the point where the
3195 // default argument expression appears.
3196 ContextRAII SavedContext(*this, FD);
3197 {
3198 std::optional<LocalInstantiationScope> LIS;
3199
3200 if (ForCallExpr) {
3201 // When instantiating a default argument due to use in a call expression,
3202 // an instantiation scope that includes the parameters of the callee is
3203 // required to satisfy references from the default argument. For example:
3204 // template<typename T> void f(T a, int = decltype(a)());
3205 // void g() { f(0); }
3206 LIS.emplace(*this);
3208 /*ForDefinition*/ false);
3209 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3210 return true;
3211 }
3212
3214 Result = SubstInitializer(PatternExpr, TemplateArgs,
3215 /*DirectInit*/ false);
3216 });
3217 }
3218 if (Result.isInvalid())
3219 return true;
3220
3221 if (ForCallExpr) {
3222 // Check the expression as an initializer for the parameter.
3223 InitializedEntity Entity
3226 Param->getLocation(),
3227 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3228 Expr *ResultE = Result.getAs<Expr>();
3229
3230 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3231 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3232 if (Result.isInvalid())
3233 return true;
3234
3235 Result =
3236 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
3237 /*DiscardedValue*/ false);
3238 } else {
3239 // FIXME: Obtain the source location for the '=' token.
3240 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3241 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3242 }
3243 if (Result.isInvalid())
3244 return true;
3245
3246 // Remember the instantiated default argument.
3247 Param->setDefaultArg(Result.getAs<Expr>());
3248
3249 return false;
3250}
3251
3252// See TreeTransform::PreparePackForExpansion for the relevant comment.
3253// This function implements the same concept for base specifiers.
3254static bool
3256 const MultiLevelTemplateArgumentList &TemplateArgs,
3257 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3258 SourceRange BaseSourceRange = Base.getSourceRange();
3259 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3260 Info.Ellipsis = Base.getEllipsisLoc();
3261 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3262 TypeSourceInfo *BaseTypeInfo,
3263 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3264 // This is a pack expansion. See whether we should expand it now, or
3265 // wait until later.
3267 S.collectUnexpandedParameterPacks(BaseTypeInfo->getTypeLoc(), Unexpanded);
3268 if (IsLateExpansionAttempt) {
3269 // Request expansion only when there is an opportunity to expand a pack
3270 // that required a substituion first.
3271 bool SawPackTypes =
3272 llvm::any_of(Unexpanded, [](UnexpandedParameterPack P) {
3273 return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>();
3274 });
3275 if (!SawPackTypes) {
3276 Info.Expand = false;
3277 return false;
3278 }
3279 }
3280
3281 // Determine whether the set of unexpanded parameter packs can and should be
3282 // expanded.
3283 Info.Expand = false;
3284 Info.RetainExpansion = false;
3285 Info.NumExpansions = std::nullopt;
3287 BaseEllipsisLoc, BaseSourceRange, Unexpanded, TemplateArgs,
3288 /*FailOnPackProducingTemplates=*/false, Info.Expand,
3289 Info.RetainExpansion, Info.NumExpansions);
3290 };
3291
3292 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3293 return true;
3294
3295 if (Info.Expand) {
3296 Out = Base.getTypeSourceInfo();
3297 return false;
3298 }
3299
3300 // The resulting base specifier will (still) be a pack expansion.
3301 {
3302 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3303 Out = S.SubstType(Base.getTypeSourceInfo(), TemplateArgs,
3304 BaseSourceRange.getBegin(), DeclarationName());
3305 }
3306 if (!Out->getType()->containsUnexpandedParameterPack())
3307 return false;
3308
3309 // Some packs will learn their length after substitution.
3310 // We may need to request their expansion.
3311 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3312 return true;
3313 if (Info.Expand)
3314 Info.ExpandUnderForgetSubstitions = true;
3315 return false;
3316}
3317
3318bool
3320 CXXRecordDecl *Pattern,
3321 const MultiLevelTemplateArgumentList &TemplateArgs) {
3322 bool Invalid = false;
3323 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3324 for (const auto &Base : Pattern->bases()) {
3325 if (!Base.getType()->isDependentType()) {
3326 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3327 if (RD->isInvalidDecl())
3328 Instantiation->setInvalidDecl();
3329 }
3330 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3331 continue;
3332 }
3333
3334 SourceLocation EllipsisLoc;
3335 TypeSourceInfo *BaseTypeLoc = nullptr;
3336 if (Base.isPackExpansion()) {
3337 UnexpandedInfo Info;
3338 if (PreparePackForExpansion(*this, Base, TemplateArgs, BaseTypeLoc,
3339 Info)) {
3340 Invalid = true;
3341 continue;
3342 }
3343
3344 // If we should expand this pack expansion now, do so.
3346 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3348 ArgsForSubst = &EmptyList;
3349
3350 if (Info.Expand) {
3351 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3352 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3353
3354 TypeSourceInfo *Expanded =
3355 SubstType(BaseTypeLoc, *ArgsForSubst,
3356 Base.getSourceRange().getBegin(), DeclarationName());
3357 if (!Expanded) {
3358 Invalid = true;
3359 continue;
3360 }
3361
3362 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3363 Instantiation, Base.getSourceRange(), Base.isVirtual(),
3364 Base.getAccessSpecifierAsWritten(), Expanded,
3365 SourceLocation()))
3366 InstantiatedBases.push_back(InstantiatedBase);
3367 else
3368 Invalid = true;
3369 }
3370
3371 continue;
3372 }
3373
3374 // The resulting base specifier will (still) be a pack expansion.
3375 EllipsisLoc = Base.getEllipsisLoc();
3376 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3377 BaseTypeLoc =
3378 SubstType(BaseTypeLoc, *ArgsForSubst,
3379 Base.getSourceRange().getBegin(), DeclarationName());
3380 } else {
3381 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3382 TemplateArgs,
3383 Base.getSourceRange().getBegin(),
3384 DeclarationName());
3385 }
3386
3387 if (!BaseTypeLoc) {
3388 Invalid = true;
3389 continue;
3390 }
3391
3392 if (CXXBaseSpecifier *InstantiatedBase
3393 = CheckBaseSpecifier(Instantiation,
3394 Base.getSourceRange(),
3395 Base.isVirtual(),
3396 Base.getAccessSpecifierAsWritten(),
3397 BaseTypeLoc,
3398 EllipsisLoc))
3399 InstantiatedBases.push_back(InstantiatedBase);
3400 else
3401 Invalid = true;
3402 }
3403
3404 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3405 Invalid = true;
3406
3407 return Invalid;
3408}
3409
3410// Defined via #include from SemaTemplateInstantiateDecl.cpp
3411namespace clang {
3412 namespace sema {
3414 const MultiLevelTemplateArgumentList &TemplateArgs);
3416 const Attr *At, ASTContext &C, Sema &S,
3417 const MultiLevelTemplateArgumentList &TemplateArgs);
3418 }
3419}
3420
3421bool Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3422 CXXRecordDecl *Instantiation,
3423 CXXRecordDecl *Pattern,
3424 const MultiLevelTemplateArgumentList &TemplateArgs,
3425 TemplateSpecializationKind TSK, bool Complain) {
3426#ifndef NDEBUG
3427 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3429 assert(!AlreadyInstantiating && "should have been caught by caller");
3430#endif
3431
3432 return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern,
3433 TemplateArgs, TSK, Complain);
3434}
3435
3436bool Sema::InstantiateClassImpl(
3437 SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation,
3438 CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs,
3439 TemplateSpecializationKind TSK, bool Complain) {
3440
3441 CXXRecordDecl *PatternDef
3442 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3443 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3444 Instantiation->getInstantiatedFromMemberClass(),
3445 Pattern, PatternDef, TSK, Complain))
3446 return true;
3447
3448 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3449 llvm::TimeTraceMetadata M;
3450 llvm::raw_string_ostream OS(M.Detail);
3451 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3452 /*Qualified=*/true);
3453 if (llvm::isTimeTraceVerbose()) {
3454 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3455 M.File = SourceMgr.getFilename(Loc);
3456 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3457 }
3458 return M;
3459 });
3460
3461 Pattern = PatternDef;
3462
3463 // Record the point of instantiation.
3464 if (MemberSpecializationInfo *MSInfo
3465 = Instantiation->getMemberSpecializationInfo()) {
3466 MSInfo->setTemplateSpecializationKind(TSK);
3467 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3468 } else if (ClassTemplateSpecializationDecl *Spec
3469 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3470 Spec->setTemplateSpecializationKind(TSK);
3471 Spec->setPointOfInstantiation(PointOfInstantiation);
3472 }
3473
3474 NonSFINAEContext _(*this);
3475 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3476 if (Inst.isInvalid())
3477 return true;
3478 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3479 "instantiating class definition");
3480
3481 // Enter the scope of this instantiation. We don't use
3482 // PushDeclContext because we don't have a scope.
3483 ContextRAII SavedContext(*this, Instantiation);
3484 EnterExpressionEvaluationContext EvalContext(
3485 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3486
3487 // If this is an instantiation of a local class, merge this local
3488 // instantiation scope with the enclosing scope. Otherwise, every
3489 // instantiation of a class has its own local instantiation scope.
3490 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3491 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3492
3493 // Some class state isn't processed immediately but delayed till class
3494 // instantiation completes. We may not be ready to handle any delayed state
3495 // already on the stack as it might correspond to a different class, so save
3496 // it now and put it back later.
3497 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3498
3499 // Pull attributes from the pattern onto the instantiation.
3500 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3501
3502 // Start the definition of this instantiation.
3503 Instantiation->startDefinition();
3504
3505 // The instantiation is visible here, even if it was first declared in an
3506 // unimported module.
3507 Instantiation->setVisibleDespiteOwningModule();
3508
3509 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3510 Instantiation->setTagKind(Pattern->getTagKind());
3511
3512 // Do substitution on the base class specifiers.
3513 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3514 Instantiation->setInvalidDecl();
3515
3516 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3517 Instantiator.setEvaluateConstraints(false);
3518 SmallVector<Decl*, 4> Fields;
3519 // Delay instantiation of late parsed attributes.
3520 LateInstantiatedAttrVec LateAttrs;
3521 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3522
3523 bool MightHaveConstexprVirtualFunctions = false;
3524 for (auto *Member : Pattern->decls()) {
3525 // Don't instantiate members not belonging in this semantic context.
3526 // e.g. for:
3527 // @code
3528 // template <int i> class A {
3529 // class B *g;
3530 // };
3531 // @endcode
3532 // 'class B' has the template as lexical context but semantically it is
3533 // introduced in namespace scope.
3534 if (Member->getDeclContext() != Pattern)
3535 continue;
3536
3537 // BlockDecls can appear in a default-member-initializer. They must be the
3538 // child of a BlockExpr, so we only know how to instantiate them from there.
3539 // Similarly, lambda closure types are recreated when instantiating the
3540 // corresponding LambdaExpr.
3541 if (isa<BlockDecl>(Member) ||
3543 continue;
3544
3545 if (Member->isInvalidDecl()) {
3546 Instantiation->setInvalidDecl();
3547 continue;
3548 }
3549
3550 Decl *NewMember = Instantiator.Visit(Member);
3551 if (NewMember) {
3552 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3553 Fields.push_back(Field);
3554 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3555 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3556 // specialization causes the implicit instantiation of the definitions
3557 // of unscoped member enumerations.
3558 // Record a point of instantiation for this implicit instantiation.
3559 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3560 Enum->isCompleteDefinition()) {
3561 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3562 assert(MSInfo && "no spec info for member enum specialization");
3564 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3565 }
3566 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3567 if (SA->isFailed()) {
3568 // A static_assert failed. Bail out; instantiating this
3569 // class is probably not meaningful.
3570 Instantiation->setInvalidDecl();
3571 break;
3572 }
3573 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3574 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3575 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3576 MightHaveConstexprVirtualFunctions = true;
3577 }
3578
3579 if (NewMember->isInvalidDecl())
3580 Instantiation->setInvalidDecl();
3581 } else {
3582 // FIXME: Eventually, a NULL return will mean that one of the
3583 // instantiations was a semantic disaster, and we'll want to mark the
3584 // declaration invalid.
3585 // For now, we expect to skip some members that we can't yet handle.
3586 }
3587 }
3588
3589 // Finish checking fields.
3590 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3591 SourceLocation(), SourceLocation(), ParsedAttributesView());
3592 CheckCompletedCXXClass(nullptr, Instantiation);
3593
3594 // Default arguments are parsed, if not instantiated. We can go instantiate
3595 // default arg exprs for default constructors if necessary now. Unless we're
3596 // parsing a class, in which case wait until that's finished.
3597 if (ParsingClassDepth == 0)
3598 ActOnFinishCXXNonNestedClass();
3599
3600 // Instantiate late parsed attributes, and attach them to their decls.
3601 // See Sema::InstantiateAttrs
3602 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3603 E = LateAttrs.end(); I != E; ++I) {
3604 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3605 CurrentInstantiationScope = I->Scope;
3606
3607 // Allow 'this' within late-parsed attributes.
3608 auto *ND = cast<NamedDecl>(I->NewDecl);
3609 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3610 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3611 ND->isCXXInstanceMember());
3612
3613 Attr *NewAttr =
3614 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3615 if (NewAttr)
3616 I->NewDecl->addAttr(NewAttr);
3618 Instantiator.getStartingScope());
3619 }
3620 Instantiator.disableLateAttributeInstantiation();
3621 LateAttrs.clear();
3622
3623 ActOnFinishDelayedMemberInitializers(Instantiation);
3624
3625 // FIXME: We should do something similar for explicit instantiations so they
3626 // end up in the right module.
3627 if (TSK == TSK_ImplicitInstantiation) {
3628 Instantiation->setLocation(Pattern->getLocation());
3629 Instantiation->setLocStart(Pattern->getInnerLocStart());
3630 Instantiation->setBraceRange(Pattern->getBraceRange());
3631 }
3632
3633 if (!Instantiation->isInvalidDecl()) {
3634 // Perform any dependent diagnostics from the pattern.
3635 if (Pattern->isDependentContext())
3636 PerformDependentDiagnostics(Pattern, TemplateArgs);
3637
3638 // Instantiate any out-of-line class template partial
3639 // specializations now.
3641 P = Instantiator.delayed_partial_spec_begin(),
3642 PEnd = Instantiator.delayed_partial_spec_end();
3643 P != PEnd; ++P) {
3644 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3645 P->first, P->second)) {
3646 Instantiation->setInvalidDecl();
3647 break;
3648 }
3649 }
3650
3651 // Instantiate any out-of-line variable template partial
3652 // specializations now.
3654 P = Instantiator.delayed_var_partial_spec_begin(),
3655 PEnd = Instantiator.delayed_var_partial_spec_end();
3656 P != PEnd; ++P) {
3657 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3658 P->first, P->second)) {
3659 Instantiation->setInvalidDecl();
3660 break;
3661 }
3662 }
3663 }
3664
3665 // Exit the scope of this instantiation.
3666 SavedContext.pop();
3667
3668 if (!Instantiation->isInvalidDecl()) {
3669 // Always emit the vtable for an explicit instantiation definition
3670 // of a polymorphic class template specialization. Otherwise, eagerly
3671 // instantiate only constexpr virtual functions in preparation for their use
3672 // in constant evaluation.
3674 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3675 else if (MightHaveConstexprVirtualFunctions)
3676 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3677 /*ConstexprOnly*/ true);
3678 }
3679
3680 Consumer.HandleTagDeclDefinition(Instantiation);
3681
3682 return Instantiation->isInvalidDecl();
3683}
3684
3685bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3686 EnumDecl *Instantiation, EnumDecl *Pattern,
3687 const MultiLevelTemplateArgumentList &TemplateArgs,
3689#ifndef NDEBUG
3690 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3692 assert(!AlreadyInstantiating && "should have been caught by caller");
3693#endif
3694
3695 EnumDecl *PatternDef = Pattern->getDefinition();
3696 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3697 Instantiation->getInstantiatedFromMemberEnum(),
3698 Pattern, PatternDef, TSK,/*Complain*/true))
3699 return true;
3700 Pattern = PatternDef;
3701
3702 // Record the point of instantiation.
3703 if (MemberSpecializationInfo *MSInfo
3704 = Instantiation->getMemberSpecializationInfo()) {
3705 MSInfo->setTemplateSpecializationKind(TSK);
3706 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3707 }
3708
3709 NonSFINAEContext _(*this);
3710 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3711 if (Inst.isInvalid())
3712 return true;
3713 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3714 "instantiating enum definition");
3715
3716 // The instantiation is visible here, even if it was first declared in an
3717 // unimported module.
3718 Instantiation->setVisibleDespiteOwningModule();
3719
3720 // Enter the scope of this instantiation. We don't use
3721 // PushDeclContext because we don't have a scope.
3722 ContextRAII SavedContext(*this, Instantiation);
3725
3726 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3727
3728 // Pull attributes from the pattern onto the instantiation.
3729 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3730
3731 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3732 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3733
3734 // Exit the scope of this instantiation.
3735 SavedContext.pop();
3736
3737 return Instantiation->isInvalidDecl();
3738}
3739
3741 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3742 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3743 // If there is no initializer, we don't need to do anything.
3744 if (!Pattern->hasInClassInitializer())
3745 return false;
3746
3747 assert(Instantiation->getInClassInitStyle() ==
3748 Pattern->getInClassInitStyle() &&
3749 "pattern and instantiation disagree about init style");
3750
3751 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3753 if (AlreadyInstantiating)
3754 // Error out if we hit an instantiation cycle for this initializer.
3755 return Diag(PointOfInstantiation,
3756 diag::err_default_member_initializer_cycle)
3757 << Instantiation;
3758
3759 // Error out if we haven't parsed the initializer of the pattern yet because
3760 // we are waiting for the closing brace of the outer class.
3761 Expr *OldInit = Pattern->getInClassInitializer();
3762 if (!OldInit) {
3763 RecordDecl *PatternRD = Pattern->getParent();
3764 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3765 Diag(PointOfInstantiation,
3766 diag::err_default_member_initializer_not_yet_parsed)
3767 << OutermostClass << Pattern;
3768 Diag(Pattern->getEndLoc(),
3769 diag::note_default_member_initializer_not_yet_parsed);
3770 Instantiation->setInvalidDecl();
3771 return true;
3772 }
3773
3774 NonSFINAEContext _(*this);
3775 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3776 if (Inst.isInvalid())
3777 return true;
3778 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3779 "instantiating default member init");
3780
3781 // Enter the scope of this instantiation. We don't use PushDeclContext because
3782 // we don't have a scope.
3783 ContextRAII SavedContext(*this, Instantiation->getParent());
3786 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3787 PointOfInstantiation, Instantiation, CurContext};
3788
3789 LocalInstantiationScope Scope(*this, true);
3790
3791 // Instantiate the initializer.
3793 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3794
3795 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3796 /*CXXDirectInit=*/false);
3797 Expr *Init = NewInit.get();
3798 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3800 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3801
3802 if (auto *L = getASTMutationListener())
3803 L->DefaultMemberInitializerInstantiated(Instantiation);
3804
3805 // Return true if the in-class initializer is still missing.
3806 return !Instantiation->getInClassInitializer();
3807}
3808
3809namespace {
3810 /// A partial specialization whose template arguments have matched
3811 /// a given template-id.
3812 struct PartialSpecMatchResult {
3815 };
3816}
3817
3819 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3820 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3822 return true;
3823
3825 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
3826 CTD->getPartialSpecializations(PartialSpecs);
3827 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
3828 // C++ [temp.spec.partial.member]p2:
3829 // If the primary member template is explicitly specialized for a given
3830 // (implicit) specialization of the enclosing class template, the partial
3831 // specializations of the member template are ignored for this
3832 // specialization of the enclosing class template. If a partial
3833 // specialization of the member template is explicitly specialized for a
3834 // given (implicit) specialization of the enclosing class template, the
3835 // primary member template and its other partial specializations are still
3836 // considered for this specialization of the enclosing class template.
3838 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
3839 continue;
3840
3841 TemplateDeductionInfo Info(Loc);
3842 if (DeduceTemplateArguments(CTPSD,
3843 ClassTemplateSpec->getTemplateArgs().asArray(),
3845 return true;
3846 }
3847
3848 return false;
3849}
3850
3851/// Get the instantiation pattern to use to instantiate the definition of a
3852/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3853/// template or of a partial specialization).
3855 Sema &S, SourceLocation PointOfInstantiation,
3856 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3857 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
3858 std::optional<Sema::NonSFINAEContext> NSC(S);
3859 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3860 if (Inst.isInvalid())
3861 return {/*Invalid=*/true};
3862
3863 llvm::PointerUnion<ClassTemplateDecl *,
3865 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3867 // Find best matching specialization.
3868 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3869
3870 // C++ [temp.class.spec.match]p1:
3871 // When a class template is used in a context that requires an
3872 // instantiation of the class, it is necessary to determine
3873 // whether the instantiation is to be generated using the primary
3874 // template or one of the partial specializations. This is done by
3875 // matching the template arguments of the class template
3876 // specialization with the template argument lists of the partial
3877 // specializations.
3878 typedef PartialSpecMatchResult MatchResult;
3879 SmallVector<MatchResult, 4> Matched, ExtraMatched;
3881 Template->getPartialSpecializations(PartialSpecs);
3882 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3883 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
3884 // C++ [temp.spec.partial.member]p2:
3885 // If the primary member template is explicitly specialized for a given
3886 // (implicit) specialization of the enclosing class template, the
3887 // partial specializations of the member template are ignored for this
3888 // specialization of the enclosing class template. If a partial
3889 // specialization of the member template is explicitly specialized for a
3890 // given (implicit) specialization of the enclosing class template, the
3891 // primary member template and its other partial specializations are
3892 // still considered for this specialization of the enclosing class
3893 // template.
3894 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
3895 !Partial->getMostRecentDecl()->isMemberSpecialization())
3896 continue;
3897
3898 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3900 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3902 // Store the failed-deduction information for use in diagnostics, later.
3903 // TODO: Actually use the failed-deduction info?
3904 FailedCandidates.addCandidate().set(
3906 MakeDeductionFailureInfo(S.Context, Result, Info));
3907 (void)Result;
3908 } else {
3909 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
3910 List.push_back(MatchResult{Partial, Info.takeCanonical()});
3911 }
3912 }
3913 if (Matched.empty() && PrimaryStrictPackMatch)
3914 Matched = std::move(ExtraMatched);
3915
3916 // If we're dealing with a member template where the template parameters
3917 // have been instantiated, this provides the original template parameters
3918 // from which the member template's parameters were instantiated.
3919
3920 if (Matched.size() >= 1) {
3921 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3922 if (Matched.size() == 1) {
3923 // -- If exactly one matching specialization is found, the
3924 // instantiation is generated from that specialization.
3925 // We don't need to do anything for this.
3926 } else {
3927 // -- If more than one matching specialization is found, the
3928 // partial order rules (14.5.4.2) are used to determine
3929 // whether one of the specializations is more specialized
3930 // than the others. If none of the specializations is more
3931 // specialized than all of the other matching
3932 // specializations, then the use of the class template is
3933 // ambiguous and the program is ill-formed.
3935 PEnd = Matched.end();
3936 P != PEnd; ++P) {
3938 P->Partial, Best->Partial, PointOfInstantiation) ==
3939 P->Partial)
3940 Best = P;
3941 }
3942
3943 // Determine if the best partial specialization is more specialized than
3944 // the others.
3945 bool Ambiguous = false;
3946 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3947 PEnd = Matched.end();
3948 P != PEnd; ++P) {
3949 if (P != Best && S.getMoreSpecializedPartialSpecialization(
3950 P->Partial, Best->Partial,
3951 PointOfInstantiation) != Best->Partial) {
3952 Ambiguous = true;
3953 break;
3954 }
3955 }
3956
3957 if (Ambiguous) {
3958 // Partial ordering did not produce a clear winner. Complain.
3959 Inst.Clear();
3960 NSC.reset();
3961 S.Diag(PointOfInstantiation,
3962 diag::err_partial_spec_ordering_ambiguous)
3963 << ClassTemplateSpec;
3964
3965 // Print the matching partial specializations.
3966 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3967 PEnd = Matched.end();
3968 P != PEnd; ++P)
3969 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3971 P->Partial->getTemplateParameters(), *P->Args);
3972
3973 return {/*Invalid=*/true};
3974 }
3975 }
3976
3977 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3978 } else {
3979 // -- If no matches are found, the instantiation is generated
3980 // from the primary template.
3981 }
3982 }
3983
3984 CXXRecordDecl *Pattern = nullptr;
3985 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3986 if (auto *PartialSpec =
3987 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3988 // Instantiate using the best class template partial specialization.
3989 while (PartialSpec->getInstantiatedFromMember()) {
3990 // If we've found an explicit specialization of this class template,
3991 // stop here and use that as the pattern.
3992 if (PartialSpec->isMemberSpecialization())
3993 break;
3994
3995 PartialSpec = PartialSpec->getInstantiatedFromMember();
3996 }
3997 Pattern = PartialSpec;
3998 } else {
3999 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4000 while (Template->getInstantiatedFromMemberTemplate()) {
4001 // If we've found an explicit specialization of this class template,
4002 // stop here and use that as the pattern.
4003 if (Template->isMemberSpecialization())
4004 break;
4005
4006 Template = Template->getInstantiatedFromMemberTemplate();
4007 }
4008 Pattern = Template->getTemplatedDecl();
4009 }
4010
4011 return Pattern;
4012}
4013
4015 SourceLocation PointOfInstantiation,
4016 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4017 TemplateSpecializationKind TSK, bool Complain,
4018 bool PrimaryStrictPackMatch) {
4019 // Perform the actual instantiation on the canonical declaration.
4020 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4021 ClassTemplateSpec->getCanonicalDecl());
4022 if (ClassTemplateSpec->isInvalidDecl())
4023 return true;
4024
4025 Sema::RecursiveInstGuard AlreadyInstantiating(
4026 *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template);
4027 if (AlreadyInstantiating)
4028 return false;
4029
4030 bool HadAvaibilityWarning =
4031 ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, nullptr, nullptr)
4032 .first != AR_Available;
4033
4035 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4036 ClassTemplateSpec, TSK,
4037 PrimaryStrictPackMatch);
4038
4039 if (!Pattern.isUsable())
4040 return Pattern.isInvalid();
4041
4042 bool Err = InstantiateClassImpl(
4043 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4044 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4045
4046 // If we haven't already warn on avaibility, consider the avaibility
4047 // attributes of the partial specialization.
4048 // Note that - because we need to have deduced the partial specialization -
4049 // We can only emit these warnings when the specialization is instantiated.
4050 if (!Err && !HadAvaibilityWarning) {
4051 assert(ClassTemplateSpec->getTemplateSpecializationKind() !=
4053 DiagnoseAvailabilityOfDecl(ClassTemplateSpec, PointOfInstantiation);
4054 }
4055 return Err;
4056}
4057
4058void
4060 CXXRecordDecl *Instantiation,
4061 const MultiLevelTemplateArgumentList &TemplateArgs,
4063 // FIXME: We need to notify the ASTMutationListener that we did all of these
4064 // things, in case we have an explicit instantiation definition in a PCM, a
4065 // module, or preamble, and the declaration is in an imported AST.
4066 assert(
4069 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4070 "Unexpected template specialization kind!");
4071 for (auto *D : Instantiation->decls()) {
4072 bool SuppressNew = false;
4073 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4074 if (FunctionDecl *Pattern =
4075 Function->getInstantiatedFromMemberFunction()) {
4076
4077 if (Function->getTrailingRequiresClause()) {
4078 ConstraintSatisfaction Satisfaction;
4079 if (CheckFunctionConstraints(Function, Satisfaction) ||
4080 !Satisfaction.IsSatisfied) {
4081 continue;
4082 }
4083 }
4084
4085 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4086 continue;
4087
4089 Function->getTemplateSpecializationKind();
4090 if (PrevTSK == TSK_ExplicitSpecialization)
4091 continue;
4092
4094 PointOfInstantiation, TSK, Function, PrevTSK,
4095 Function->getPointOfInstantiation(), SuppressNew) ||
4096 SuppressNew)
4097 continue;
4098
4099 // C++11 [temp.explicit]p8:
4100 // An explicit instantiation definition that names a class template
4101 // specialization explicitly instantiates the class template
4102 // specialization and is only an explicit instantiation definition
4103 // of members whose definition is visible at the point of
4104 // instantiation.
4105 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4106 continue;
4107
4108 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4109
4110 if (Function->isDefined()) {
4111 // Let the ASTConsumer know that this function has been explicitly
4112 // instantiated now, and its linkage might have changed.
4113 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
4114 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4115 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4116 } else if (TSK == TSK_ImplicitInstantiation) {
4118 std::make_pair(Function, PointOfInstantiation));
4119 }
4120 }
4121 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4123 continue;
4124
4125 if (Var->isStaticDataMember()) {
4126 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4127 continue;
4128
4130 assert(MSInfo && "No member specialization information?");
4131 if (MSInfo->getTemplateSpecializationKind()
4133 continue;
4134
4135 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4136 Var,
4138 MSInfo->getPointOfInstantiation(),
4139 SuppressNew) ||
4140 SuppressNew)
4141 continue;
4142
4144 // C++0x [temp.explicit]p8:
4145 // An explicit instantiation definition that names a class template
4146 // specialization explicitly instantiates the class template
4147 // specialization and is only an explicit instantiation definition
4148 // of members whose definition is visible at the point of
4149 // instantiation.
4151 continue;
4152
4153 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4154 InstantiateVariableDefinition(PointOfInstantiation, Var);
4155 } else {
4156 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4157 }
4158 }
4159 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4160 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4161 continue;
4162
4163 // Always skip the injected-class-name, along with any
4164 // redeclarations of nested classes, since both would cause us
4165 // to try to instantiate the members of a class twice.
4166 // Skip closure types; they'll get instantiated when we instantiate
4167 // the corresponding lambda-expression.
4168 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4169 Record->isLambda())
4170 continue;
4171
4172 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4173 assert(MSInfo && "No member specialization information?");
4174
4175 if (MSInfo->getTemplateSpecializationKind()
4177 continue;
4178
4179 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4181 // On Windows, explicit instantiation decl of the outer class doesn't
4182 // affect the inner class. Typically extern template declarations are
4183 // used in combination with dll import/export annotations, but those
4184 // are not propagated from the outer class templates to inner classes.
4185 // Therefore, do not instantiate inner classes on this platform, so
4186 // that users don't end up with undefined symbols during linking.
4187 continue;
4188 }
4189
4190 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4191 Record,
4193 MSInfo->getPointOfInstantiation(),
4194 SuppressNew) ||
4195 SuppressNew)
4196 continue;
4197
4198 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4199 assert(Pattern && "Missing instantiated-from-template information");
4200
4201 if (!Record->getDefinition()) {
4202 if (!Pattern->getDefinition()) {
4203 // C++0x [temp.explicit]p8:
4204 // An explicit instantiation definition that names a class template
4205 // specialization explicitly instantiates the class template
4206 // specialization and is only an explicit instantiation definition
4207 // of members whose definition is visible at the point of
4208 // instantiation.
4210 MSInfo->setTemplateSpecializationKind(TSK);
4211 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4212 }
4213
4214 continue;
4215 }
4216
4217 InstantiateClass(PointOfInstantiation, Record, Pattern,
4218 TemplateArgs,
4219 TSK);
4220 } else {
4222 Record->getTemplateSpecializationKind() ==
4224 Record->setTemplateSpecializationKind(TSK);
4225 MarkVTableUsed(PointOfInstantiation, Record, true);
4226 }
4227 }
4228
4229 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4230 if (Pattern)
4231 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4232 TSK);
4233 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4234 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4235 assert(MSInfo && "No member specialization information?");
4236
4237 if (MSInfo->getTemplateSpecializationKind()
4239 continue;
4240
4242 PointOfInstantiation, TSK, Enum,
4244 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4245 SuppressNew)
4246 continue;
4247
4248 if (Enum->getDefinition())
4249 continue;
4250
4251 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4252 assert(Pattern && "Missing instantiated-from-template information");
4253
4255 if (!Pattern->getDefinition())
4256 continue;
4257
4258 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4259 } else {
4260 MSInfo->setTemplateSpecializationKind(TSK);
4261 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4262 }
4263 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4264 // No need to instantiate in-class initializers during explicit
4265 // instantiation.
4266 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4267 // Handle local classes which could have substituted template params.
4268 CXXRecordDecl *ClassPattern =
4269 Instantiation->isLocalClass()
4270 ? Instantiation->getInstantiatedFromMemberClass()
4271 : Instantiation->getTemplateInstantiationPattern();
4272
4274 ClassPattern->lookup(Field->getDeclName());
4275 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4276 assert(Pattern);
4277 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4278 TemplateArgs);
4279 }
4280 }
4281 }
4282}
4283
4284void
4286 SourceLocation PointOfInstantiation,
4287 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4289 // C++0x [temp.explicit]p7:
4290 // An explicit instantiation that names a class template
4291 // specialization is an explicit instantion of the same kind
4292 // (declaration or definition) of each of its members (not
4293 // including members inherited from base classes) that has not
4294 // been previously explicitly specialized in the translation unit
4295 // containing the explicit instantiation, except as described
4296 // below.
4297 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4298 getTemplateInstantiationArgs(ClassTemplateSpec),
4299 TSK);
4300}
4301
4304 if (!S)
4305 return S;
4306
4307 TemplateInstantiator Instantiator(*this, TemplateArgs,
4309 DeclarationName());
4310 return Instantiator.TransformStmt(S);
4311}
4312
4314 const TemplateArgumentLoc &Input,
4315 const MultiLevelTemplateArgumentList &TemplateArgs,
4317 const DeclarationName &Entity) {
4318 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4319 return Instantiator.TransformTemplateArgument(Input, Output);
4320}
4321
4324 const MultiLevelTemplateArgumentList &TemplateArgs,
4326 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4327 DeclarationName());
4328 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4329}
4330
4333 const MultiLevelTemplateArgumentList &TemplateArgs,
4335 TemplateInstantiator Instantiator(
4336 TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,
4337 TemplateArgs);
4338 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4339}
4340
4343 if (!E)
4344 return E;
4345
4346 TemplateInstantiator Instantiator(*this, TemplateArgs,
4348 DeclarationName());
4349 return Instantiator.TransformExpr(E);
4350}
4351
4354 const MultiLevelTemplateArgumentList &TemplateArgs) {
4355 if (!E)
4356 return E;
4357
4358 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4359 DeclarationName());
4360 return Instantiator.TransformAddressOfOperand(E);
4361}
4362
4365 const MultiLevelTemplateArgumentList &TemplateArgs) {
4366 // FIXME: should call SubstExpr directly if this function is equivalent or
4367 // should it be different?
4368 return SubstExpr(E, TemplateArgs);
4369}
4370
4372 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4373 if (!E)
4374 return E;
4375
4376 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4377 DeclarationName());
4378 Instantiator.setEvaluateConstraints(false);
4379 return Instantiator.TransformExpr(E);
4380}
4381
4383 const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr,
4384 const MultiLevelTemplateArgumentList &MLTAL) {
4385 TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(),
4386 DeclarationName());
4387 const ASTTemplateArgumentListInfo *ArgsAsWritten =
4389 TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(),
4390 ArgsAsWritten->getRAngleLoc());
4391
4392 NonSFINAEContext _(*this);
4394 *this, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),
4396 CSE->getNamedConcept(),
4397 ArgsAsWritten->arguments().front().getSourceRange());
4398
4399 if (Inst.isInvalid())
4400 return ExprError();
4401
4402 if (Instantiator.TransformConceptTemplateArguments(
4403 ArgsAsWritten->getTemplateArgs(),
4404 ArgsAsWritten->getTemplateArgs() +
4405 ArgsAsWritten->getNumTemplateArgs(),
4406 SubstArgs))
4407 return true;
4408
4409 llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector(
4410 SubstArgs.arguments(),
4411 [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); });
4412
4413 MultiLevelTemplateArgumentList MLTALForConstraint =
4415 CSE->getNamedConcept(),
4417 /*Final=*/false,
4418 /*Innermost=*/NewArgList,
4419 /*RelativeToPrimary=*/true,
4420 /*Pattern=*/nullptr,
4421 /*ForConstraintInstantiation=*/true);
4422
4423 // Rebuild a constraint, only substituting non-dependent concept names
4424 // and nothing else.
4425 // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>.
4426 // only SomeConceptName is substituted, in the constraint expression of C.
4427 struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> {
4430
4431 ConstraintExprTransformer(Sema &SemaRef,
4433 : TreeTransform(SemaRef), MLTAL(MLTAL) {}
4434
4435 ExprResult TransformExpr(Expr *E) {
4436 if (!E)
4437 return E;
4438 switch (E->getStmtClass()) {
4439 case Stmt::BinaryOperatorClass:
4440 case Stmt::ConceptSpecializationExprClass:
4441 case Stmt::ParenExprClass:
4442 case Stmt::UnresolvedLookupExprClass:
4443 return Base::TransformExpr(E);
4444 default:
4445 break;
4446 }
4447 return E;
4448 }
4449
4450 // Rebuild both branches of a conjunction / disjunction
4451 // even if there is a substitution failure in one of
4452 // the branch.
4453 ExprResult TransformBinaryOperator(BinaryOperator *E) {
4454 if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd ||
4455 E->getOpcode() == BinaryOperatorKind::BO_LOr))
4456 return E;
4457
4458 ExprResult LHS = TransformExpr(E->getLHS());
4459 ExprResult RHS = TransformExpr(E->getRHS());
4460
4461 if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
4462 return E;
4463
4464 return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
4465 E->getOpcode(), SemaRef.Context.BoolTy,
4468 }
4469
4470 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
4471 TemplateArgumentLoc &Output,
4472 bool Uneval = false) {
4474 return Base::TransformTemplateArgument(Input, Output, Uneval);
4475
4476 Output = Input;
4477 return false;
4478 }
4479
4480 ExprResult TransformUnresolvedLookupExpr(UnresolvedLookupExpr *E,
4481 bool IsAddressOfOperand = false) {
4482 if (E->isConceptReference()) {
4483 ExprResult Res = SemaRef.SubstExpr(E, MLTAL);
4484 return Res;
4485 }
4486 return E;
4487 }
4488 };
4489
4490 ConstraintExprTransformer Transformer(*this, MLTALForConstraint);
4491 ExprResult Res =
4492 Transformer.TransformExpr(const_cast<Expr *>(ConstraintExpr));
4493 return Res;
4494}
4495
4497 const MultiLevelTemplateArgumentList &TemplateArgs,
4498 bool CXXDirectInit) {
4499 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4500 DeclarationName());
4501 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4502}
4503
4504bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4505 const MultiLevelTemplateArgumentList &TemplateArgs,
4506 SmallVectorImpl<Expr *> &Outputs) {
4507 if (Exprs.empty())
4508 return false;
4509
4510 TemplateInstantiator Instantiator(*this, TemplateArgs,
4512 DeclarationName());
4513 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4514 IsCall, Outputs);
4515}
4516
4519 const MultiLevelTemplateArgumentList &TemplateArgs) {
4520 if (!NNS)
4521 return NestedNameSpecifierLoc();
4522
4523 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4524 DeclarationName());
4525 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4526}
4527
4530 const MultiLevelTemplateArgumentList &TemplateArgs) {
4531 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4532 NameInfo.getName());
4533 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4534}
4535
4538 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4539 SourceLocation NameLoc,
4540 const MultiLevelTemplateArgumentList &TemplateArgs) {
4541 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4542 DeclarationName());
4543 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4544 NameLoc);
4545}
4546
4547static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4548 // When storing ParmVarDecls in the local instantiation scope, we always
4549 // want to use the ParmVarDecl from the canonical function declaration,
4550 // since the map is then valid for any redeclaration or definition of that
4551 // function.
4552 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4553 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4554 unsigned i = PV->getFunctionScopeIndex();
4555 // This parameter might be from a freestanding function type within the
4556 // function and isn't necessarily referring to one of FD's parameters.
4557 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4558 return FD->getCanonicalDecl()->getParamDecl(i);
4559 }
4560 }
4561 return D;
4562}
4563
4564llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4567 for (LocalInstantiationScope *Current = this; Current;
4568 Current = Current->Outer) {
4569
4570 // Check if we found something within this scope.
4571 const Decl *CheckD = D;
4572 do {
4573 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4574 if (Found != Current->LocalDecls.end())
4575 return &Found->second;
4576
4577 // If this is a tag declaration, it's possible that we need to look for
4578 // a previous declaration.
4579 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4580 CheckD = Tag->getPreviousDecl();
4581 else
4582 CheckD = nullptr;
4583 } while (CheckD);
4584
4585 // If we aren't combined with our outer scope, we're done.
4586 if (!Current->CombineWithOuterScope)
4587 break;
4588 }
4589
4590 return nullptr;
4591}
4592
4593llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4596 if (Result)
4597 return Result;
4598 // If we're performing a partial substitution during template argument
4599 // deduction, we may not have values for template parameters yet.
4602 return nullptr;
4603
4604 // Local types referenced prior to definition may require instantiation.
4605 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4606 if (RD->isLocalClass())
4607 return nullptr;
4608
4609 // Enumeration types referenced prior to definition may appear as a result of
4610 // error recovery.
4611 if (isa<EnumDecl>(D))
4612 return nullptr;
4613
4614 // Materialized typedefs/type alias for implicit deduction guides may require
4615 // instantiation.
4616 if (isa<TypedefNameDecl>(D) &&
4618 return nullptr;
4619
4620 // If we didn't find the decl, then we either have a sema bug, or we have a
4621 // forward reference to a label declaration. Return null to indicate that
4622 // we have an uninstantiated label.
4623 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4624 return nullptr;
4625}
4626
4629 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4630 if (Stored.isNull()) {
4631#ifndef NDEBUG
4632 // It should not be present in any surrounding scope either.
4633 LocalInstantiationScope *Current = this;
4634 while (Current->CombineWithOuterScope && Current->Outer) {
4635 Current = Current->Outer;
4636 assert(!Current->LocalDecls.contains(D) &&
4637 "Instantiated local in inner and outer scopes");
4638 }
4639#endif
4640 Stored = Inst;
4641 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4642 Pack->push_back(cast<ValueDecl>(Inst));
4643 } else {
4644 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4645 }
4646}
4647
4649 VarDecl *Inst) {
4651 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4652 Pack->push_back(Inst);
4653}
4654
4656#ifndef NDEBUG
4657 // This should be the first time we've been told about this decl.
4658 for (LocalInstantiationScope *Current = this;
4659 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4660 assert(!Current->LocalDecls.contains(D) &&
4661 "Creating local pack after instantiation of local");
4662#endif
4663
4665 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4667 Stored = Pack;
4668 ArgumentPacks.push_back(Pack);
4669}
4670
4672 for (DeclArgumentPack *Pack : ArgumentPacks)
4673 if (llvm::is_contained(*Pack, D))
4674 return true;
4675 return false;
4676}
4677
4679 const TemplateArgument *ExplicitArgs,
4680 unsigned NumExplicitArgs) {
4681 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4682 "Already have a partially-substituted pack");
4683 assert((!PartiallySubstitutedPack
4684 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4685 "Wrong number of arguments in partially-substituted pack");
4686 PartiallySubstitutedPack = Pack;
4687 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4688 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4689}
4690
4692 const TemplateArgument **ExplicitArgs,
4693 unsigned *NumExplicitArgs) const {
4694 if (ExplicitArgs)
4695 *ExplicitArgs = nullptr;
4696 if (NumExplicitArgs)
4697 *NumExplicitArgs = 0;
4698
4699 for (const LocalInstantiationScope *Current = this; Current;
4700 Current = Current->Outer) {
4701 if (Current->PartiallySubstitutedPack) {
4702 if (ExplicitArgs)
4703 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4704 if (NumExplicitArgs)
4705 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4706
4707 return Current->PartiallySubstitutedPack;
4708 }
4709
4710 if (!Current->CombineWithOuterScope)
4711 break;
4712 }
4713
4714 return nullptr;
4715}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines Expressions and AST nodes for C++2a concepts.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static bool PreparePackForExpansion(Sema &S, const CXXBaseSpecifier &Base, const MultiLevelTemplateArgumentList &TemplateArgs, TypeSourceInfo *&Out, UnexpandedInfo &Info)
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static ActionResult< CXXRecordDecl * > getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, Sema::EntityPrinter Printer)
static std::string convertCallArgsToString(Sema &S, llvm::ArrayRef< const Expr * > Args)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:843
The result of parsing/analyzing an expression, statement etc.
Definition Ownership.h:154
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
Expr * getLHS() const
Definition Expr.h:4088
SourceLocation getOperatorLoc() const
Definition Expr.h:4080
Expr * getRHS() const
Definition Expr.h:4090
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:4982
Opcode getOpcode() const
Definition Expr.h:4083
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition ExprCXX.h:1344
const ParmVarDecl * getParam() const
Definition ExprCXX.h:1312
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition DeclCXX.cpp:1828
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1554
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2020
base_class_range bases()
Definition DeclCXX.h:608
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2075
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2050
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2042
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2027
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
Declaration of a class template.
ClassTemplateDecl * getMostRecentDecl()
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isClassScopeExplicitSpecialization() const
Is this an explicit specialization at class scope (within the class that owns the primary template)?
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate members of the class templa...
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
NamedDecl * getFoundDecl() const
Definition ASTConcept.h:197
Represents the specialization of a concept - evaluates to a prvalue of type bool.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
ConceptDecl * getNamedConcept() const
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
bool isFileContext() const
Definition DeclBase.h:2180
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
ValueDecl * getDecl()
Definition Expr.h:1338
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:266
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isFileContextDecl() const
Definition DeclBase.cpp:454
static Decl * castFromDeclContext(const DeclContext *)
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition DeclBase.cpp:320
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
void setLocation(SourceLocation L)
Definition DeclBase.h:440
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition DeclBase.h:949
DeclContext * getDeclContext()
Definition DeclBase.h:448
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:870
The name of a declaration.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:822
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:837
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4010
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4282
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5149
EnumDecl * getDefinition() const
Definition Decl.h:4122
This represents one expression.
Definition Expr.h:112
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
ExprDependence getDependence() const
Definition Expr.h:164
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4725
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3340
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3334
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Represents a function declaration or definition.
Definition Decl.h:2000
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4264
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4313
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2344
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1816
ValueDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition ExprCXX.h:4882
ValueDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition ExprCXX.h:4874
ValueDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition ExprCXX.h:4867
iterator end() const
Definition ExprCXX.h:4876
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition ExprCXX.h:4879
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4870
iterator begin() const
Definition ExprCXX.h:4875
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
QualType desugar() const
Definition TypeBase.h:5850
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5558
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition TypeLoc.h:1678
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4491
QualType getReturnType() const
Definition TypeBase.h:4805
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1968
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:371
LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope=false, bool InstantiatingLambdaOrBlock=false)
Definition Template.h:439
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
SmallVector< ValueDecl *, 4 > DeclArgumentPack
A set of declarations.
Definition Template.h:374
llvm::PointerUnion< Decl *, DeclArgumentPack * > * getInstantiationOfIfExists(const Decl *D)
Similar to findInstantiationOf(), but it wouldn't assert if the instantiation was not found within th...
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all outer scopes, down to the given outermost scope.
Definition Template.h:511
void InstantiatedLocal(const Decl *D, Decl *Inst)
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
bool isLambdaOrBlock() const
Determine whether this scope is for instantiating a lambda or block.
Definition Template.h:577
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Provides information a specialization of a member of a class template, which may be a member function...
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Describes a module or submodule.
Definition Module.h:144
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
bool hasTemplateArgument(unsigned Depth, unsigned Index) const
Determine whether there is a non-NULL template argument at the given depth and index.
Definition Template.h:175
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition Template.h:271
std::pair< Decl *, bool > getAssociatedDecl(unsigned Depth) const
A template-like entity which owns the whole pattern being substituted.
Definition Template.h:164
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition Template.h:123
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition Template.h:129
unsigned getNewDepth(unsigned OldDepth) const
Determine how many of the OldDepth outermost template parameter lists would be removed by substitutin...
Definition Template.h:145
void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg)
Clear out a specific template argument.
Definition Template.h:199
bool isRewrite() const
Determine whether we are rewriting template parameters rather than substituting for them.
Definition Template.h:117
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp:1845
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition Decl.cpp:1672
A C++ nested-name-specifier augmented with source location information.
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getDepth() const
Get the nesting depth of the template parameter.
SourceLocation getEllipsisLoc() const
Definition TypeLoc.h:2600
TypeLoc getPatternLoc() const
Definition TypeLoc.h:2616
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
SourceLocation getExplicitObjectParamThisLoc() const
Definition Decl.h:1886
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1931
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1919
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3047
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1923
bool hasInheritedDefaultArg() const
Definition Decl.h:1935
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1882
Expr * getDefaultArg()
Definition Decl.cpp:3010
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3052
unsigned getFunctionScopeDepth() const
Definition Decl.h:1840
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1939
PredefinedIdentKind getIdentKind() const
Definition Expr.h:2040
SourceLocation getLocation() const
Definition Expr.h:2046
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition TypeBase.h:937
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3556
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void removeObjCLifetime()
Definition TypeBase.h:551
Represents a struct/union/class.
Definition Decl.h:4324
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Represents the body of a requires-expression.
Definition DeclCXX.h:2098
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
SourceLocation getLParenLoc() const
SourceLocation getRParenLoc() const
RequiresExprBodyDecl * getBody() const
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13658
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8470
A RAII object to temporarily push a declaration context.
Definition Sema.h:3494
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6376
DefaultedComparisonKind asComparison() const
Definition Sema.h:6408
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6405
A helper class for building up ExtParameterInfos.
Definition Sema.h:13044
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12476
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:856
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition Sema.h:13613
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13597
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13073
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.
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr, const MultiLevelTemplateArgumentList &MLTAL)
Substitute concept template arguments in the constraint expression of a concept-id.
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
llvm::function_ref< void(SourceLocation, PartialDiagnostic)> InstantiationContextDiagFuncRef
Definition Sema.h:2291
TemplateName SubstTemplateName(SourceLocation TemplateKWLoc, NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, SourceLocation NameLoc, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, UnsignedOrNone NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition Sema.h:13979
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
concepts::Requirement::SubstitutionDiagnostic * createSubstDiagAt(SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using ASTConte...
bool SubstExprs(ArrayRef< Expr * > Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr * > &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTContext & Context
Definition Sema.h:1288
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:924
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose=true)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
void PrintInstantiationStack()
Definition Sema.h:13688
ASTContext & getASTContext() const
Definition Sema.h:927
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.
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 ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1192
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition Sema.h:920
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool SubstTemplateArgumentsInParameterMapping(ArrayRef< TemplateArgumentLoc > Args, SourceLocation BaseLoc, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Out)
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 ...
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
TemplateArgument getPackSubstitutedTemplateArgument(TemplateArgument Arg) const
Definition Sema.h:11792
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:13085
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1421
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:14028
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
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 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...
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition Sema.h:13628
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
bool inConstraintSubstitution() const
Determine whether we are currently performing constraint substitution.
Definition Sema.h:13968
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver)
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
std::pair< AvailabilityResult, const NamedDecl * > ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message, ObjCInterfaceDecl *ClassReceiver)
The diagnostic we should emit for D, and the declaration that originated it, or AR_Available.
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition Sema.h:13652
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 SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
ExprResult SubstConstraintExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTConsumer & Consumer
Definition Sema.h:1289
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6751
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6761
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition Sema.h:13636
bool inParameterMappingSubstitution() const
Definition Sema.h:13973
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8189
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8339
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
DiagnosticsEngine & Diags
Definition Sema.h:1290
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
friend class InitializationSequence
Definition Sema.h:1563
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13608
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:625
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
ExprResult SubstCXXIdExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
Substitute an expression as if it is a address-of-operand, which makes it act like a CXXIdExpression ...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Perform substitution on the base class specifiers of the given class template specialization.
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:651
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8681
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
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 getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
StmtClass getStmtClass() const
Definition Stmt.h:1485
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
void setTagKind(TagKind TK)
Definition Decl.h:3918
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4906
void setBraceRange(SourceRange R)
Definition Decl.h:3792
SourceLocation getNameLoc() const
Definition TypeLoc.h:822
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
A template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
bool isConceptOrConceptTemplateParameter() const
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
@ Type
The template argument is a type.
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition Template.h:686
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition Template.h:689
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool isParameterPack() const
Returns whether this is a parameter pack.
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
QualType TransformTemplateSpecializationType(TypeLocBuilder &TLB, TemplateSpecializationTypeLoc TL, QualType ObjectType, NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName)
Declaration of an alias template.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:266
UnsignedOrNone getArgPackSubstIndex() const
Definition ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition ASTConcept.h:276
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
const DeclarationNameInfo & getConceptNameInfo() const
Definition ASTConcept.h:280
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
void setLocStart(SourceLocation L)
Definition Decl.h:3548
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
void pushTrivial(ASTContext &Context, QualType T, SourceLocation Loc)
Pushes 'T' with all locations pointing to 'Loc'.
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
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1408
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition TypeLoc.h:165
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8263
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8274
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8891
bool isReferenceType() const
Definition TypeBase.h:8553
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2791
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2801
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
bool isRecordType() const
Definition TypeBase.h:8656
QualType getUnderlyingType() const
Definition Decl.h:3617
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5588
Represents a variable declaration or definition.
Definition Decl.h:926
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2377
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2783
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:2918
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2909
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
const ReturnTypeRequirement & getReturnTypeRequirement() const
SourceLocation getNoexceptLoc() const
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
const ASTConstraintSatisfaction & getConstraintSatisfaction() const
A static requirement that can be used in a requires-expression to check properties of types and expre...
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
TypeSourceInfo * getType() const
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeCanonical()
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
The JSON file list parser is used to communicate input to InstallAPI.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus11
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
NamedDecl * getAsNamedDecl(TemplateParameter P)
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:238
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ AS_public
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition ASTLambda.h:89
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
@ AR_Available
Definition DeclBase.h:73
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ Success
Template argument deduction was successful.
Definition Sema.h:371
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5882
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments.
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
SourceLocation getLAngleLoc() const
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getRAngleLoc() const
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.
Holds information about the various types of exception specification.
Definition TypeBase.h:5326
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5328
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13124
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13287
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13260
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13247
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13126
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13218
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13136
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13145
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13164
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13215
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13172
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13179
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13222
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13190
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13228
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13155
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13234
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13231
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13237
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13152
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13160
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13168
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13129
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13182
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13186
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13141
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13212
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13175
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13250
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
A stack object to be created when performing template instantiation.
Definition Sema.h:13310
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13463
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange=SourceRange())
Note that we are instantiating a class template, function template, variable template,...
void Clear()
Note that we have finished instantiating this template.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
SourceLocation Ellipsis
UnsignedOrNone NumExpansions