clang 19.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"
20#include "clang/AST/Expr.h"
23#include "clang/AST/Type.h"
26#include "clang/Basic/Stack.h"
28#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Sema.h"
35#include "clang/Sema/Template.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/TimeProfiler.h"
41#include <optional>
42
43using namespace clang;
44using namespace sema;
45
46//===----------------------------------------------------------------------===/
47// Template Instantiation Support
48//===----------------------------------------------------------------------===/
49
50namespace {
52struct Response {
53 const Decl *NextDecl = nullptr;
54 bool IsDone = false;
55 bool ClearRelativeToPrimary = true;
56 static Response Done() {
57 Response R;
58 R.IsDone = true;
59 return R;
60 }
61 static Response ChangeDecl(const Decl *ND) {
62 Response R;
63 R.NextDecl = ND;
64 return R;
65 }
66 static Response ChangeDecl(const DeclContext *Ctx) {
67 Response R;
68 R.NextDecl = Decl::castFromDeclContext(Ctx);
69 return R;
70 }
71
72 static Response UseNextDecl(const Decl *CurDecl) {
73 return ChangeDecl(CurDecl->getDeclContext());
74 }
75
76 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
77 Response R = Response::UseNextDecl(CurDecl);
78 R.ClearRelativeToPrimary = false;
79 return R;
80 }
81};
82// Add template arguments from a variable template instantiation.
83Response
84HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
86 bool SkipForSpecialization) {
87 // For a class-scope explicit specialization, there are no template arguments
88 // at this level, but there may be enclosing template arguments.
89 if (VarTemplSpec->isClassScopeExplicitSpecialization())
90 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
91
92 // We're done when we hit an explicit specialization.
94 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
95 return Response::Done();
96
97 // If this variable template specialization was instantiated from a
98 // specialized member that is a variable template, we're done.
99 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
100 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
101 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
103 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
104 if (!SkipForSpecialization)
105 Result.addOuterTemplateArguments(
106 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
107 /*Final=*/false);
108 if (Partial->isMemberSpecialization())
109 return Response::Done();
110 } else {
111 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
112 if (!SkipForSpecialization)
113 Result.addOuterTemplateArguments(
114 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
115 /*Final=*/false);
116 if (Tmpl->isMemberSpecialization())
117 return Response::Done();
118 }
119 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
120}
121
122// If we have a template template parameter with translation unit context,
123// then we're performing substitution into a default template argument of
124// this template template parameter before we've constructed the template
125// that will own this template template parameter. In this case, we
126// use empty template parameter lists for all of the outer templates
127// to avoid performing any substitutions.
128Response
129HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
131 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
132 Result.addOuterTemplateArguments(std::nullopt);
133 return Response::Done();
134}
135
136Response HandlePartialClassTemplateSpec(
137 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
138 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
139 if (!SkipForSpecialization)
140 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
141 return Response::Done();
142}
143
144// Add template arguments from a class template instantiation.
145Response
146HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
148 bool SkipForSpecialization) {
149 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
150 // We're done when we hit an explicit specialization.
151 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
152 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
153 return Response::Done();
154
155 if (!SkipForSpecialization)
156 Result.addOuterTemplateArguments(
157 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
158 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
159 /*Final=*/false);
160
161 // If this class template specialization was instantiated from a
162 // specialized member that is a class template, we're done.
163 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
164 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
165 return Response::Done();
166
167 // If this was instantiated from a partial template specialization, we need
168 // to get the next level of declaration context from the partial
169 // specialization, as the ClassTemplateSpecializationDecl's
170 // DeclContext/LexicalDeclContext will be for the primary template.
171 if (auto *InstFromPartialTempl = ClassTemplSpec->getSpecializedTemplateOrPartial()
173 return Response::ChangeDecl(InstFromPartialTempl->getLexicalDeclContext());
174 }
175 return Response::UseNextDecl(ClassTemplSpec);
176}
177
178Response HandleFunction(const FunctionDecl *Function,
180 const FunctionDecl *Pattern, bool RelativeToPrimary,
181 bool ForConstraintInstantiation) {
182 // Add template arguments from a function template specialization.
183 if (!RelativeToPrimary &&
184 Function->getTemplateSpecializationKindForInstantiation() ==
186 return Response::Done();
187
188 if (!RelativeToPrimary &&
189 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
190 // This is an implicit instantiation of an explicit specialization. We
191 // don't get any template arguments from this function but might get
192 // some from an enclosing template.
193 return Response::UseNextDecl(Function);
194 } else if (const TemplateArgumentList *TemplateArgs =
195 Function->getTemplateSpecializationArgs()) {
196 // Add the template arguments for this specialization.
197 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
198 TemplateArgs->asArray(),
199 /*Final=*/false);
200
201 // If this function was instantiated from a specialized member that is
202 // a function template, we're done.
203 assert(Function->getPrimaryTemplate() && "No function template?");
204 if (Function->getPrimaryTemplate()->isMemberSpecialization())
205 return Response::Done();
206
207 // If this function is a generic lambda specialization, we are done.
208 if (!ForConstraintInstantiation &&
210 return Response::Done();
211
212 } else if (Function->getDescribedFunctionTemplate()) {
213 assert(
214 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
215 "Outer template not instantiated?");
216 }
217 // If this is a friend or local declaration and it declares an entity at
218 // namespace scope, take arguments from its lexical parent
219 // instead of its semantic parent, unless of course the pattern we're
220 // instantiating actually comes from the file's context!
221 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
222 Function->getNonTransparentDeclContext()->isFileContext() &&
223 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
224 return Response::ChangeDecl(Function->getLexicalDeclContext());
225 }
226
227 if (ForConstraintInstantiation && Function->getFriendObjectKind())
228 return Response::ChangeDecl(Function->getLexicalDeclContext());
229 return Response::UseNextDecl(Function);
230}
231
232Response HandleFunctionTemplateDecl(const FunctionTemplateDecl *FTD,
234 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
235 Result.addOuterTemplateArguments(
236 const_cast<FunctionTemplateDecl *>(FTD),
237 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(),
238 /*Final=*/false);
239
241
242 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
243 if (NNS->isInstantiationDependent()) {
244 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
245 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
246 // Prefer template arguments from the injected-class-type if possible.
247 // For example,
248 // ```cpp
249 // template <class... Pack> struct S {
250 // template <class T> void foo();
251 // };
252 // template <class... Pack> template <class T>
253 // ^^^^^^^^^^^^^ InjectedTemplateArgs
254 // They're of kind TemplateArgument::Pack, not of
255 // TemplateArgument::Type.
256 // void S<Pack...>::foo() {}
257 // ^^^^^^^
258 // TSTy->template_arguments() (which are of PackExpansionType)
259 // ```
260 // This meets the contract in
261 // TreeTransform::TryExpandParameterPacks that the template arguments
262 // for unexpanded parameters should be of a Pack kind.
263 if (TSTy->isCurrentInstantiation()) {
264 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
265 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
266 Arguments = CTD->getInjectedTemplateArgs();
267 else if (auto *Specialization =
268 dyn_cast<ClassTemplateSpecializationDecl>(RD))
269 Arguments =
270 Specialization->getTemplateInstantiationArgs().asArray();
271 }
272 Result.addOuterTemplateArguments(
273 const_cast<FunctionTemplateDecl *>(FTD), Arguments,
274 /*Final=*/false);
275 }
276 }
277
278 NNS = NNS->getPrefix();
279 }
280 }
281
282 return Response::ChangeDecl(FTD->getLexicalDeclContext());
283}
284
285Response HandleRecordDecl(const CXXRecordDecl *Rec,
287 ASTContext &Context,
288 bool ForConstraintInstantiation) {
289 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
290 assert(
291 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
292 "Outer template not instantiated?");
293 if (ClassTemplate->isMemberSpecialization())
294 return Response::Done();
295 if (ForConstraintInstantiation)
296 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
297 ClassTemplate->getInjectedTemplateArgs(),
298 /*Final=*/false);
299 }
300
301 if (const MemberSpecializationInfo *MSInfo =
303 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
304 return Response::Done();
305
306 bool IsFriend = Rec->getFriendObjectKind() ||
309 if (ForConstraintInstantiation && IsFriend &&
311 return Response::ChangeDecl(Rec->getLexicalDeclContext());
312 }
313
314 // This is to make sure we pick up the VarTemplateSpecializationDecl that this
315 // lambda is defined inside of.
316 if (Rec->isLambda())
317 if (const Decl *LCD = Rec->getLambdaContextDecl())
318 return Response::ChangeDecl(LCD);
319
320 return Response::UseNextDecl(Rec);
321}
322
323Response HandleImplicitConceptSpecializationDecl(
326 Result.addOuterTemplateArguments(
327 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
329 /*Final=*/false);
330 return Response::UseNextDecl(CSD);
331}
332
333Response HandleGenericDeclContext(const Decl *CurDecl) {
334 return Response::UseNextDecl(CurDecl);
335}
336} // namespace TemplateInstArgsHelpers
337} // namespace
338
339/// Retrieve the template argument list(s) that should be used to
340/// instantiate the definition of the given declaration.
341///
342/// \param ND the declaration for which we are computing template instantiation
343/// arguments.
344///
345/// \param DC In the event we don't HAVE a declaration yet, we instead provide
346/// the decl context where it will be created. In this case, the `Innermost`
347/// should likely be provided. If ND is non-null, this is ignored.
348///
349/// \param Innermost if non-NULL, specifies a template argument list for the
350/// template declaration passed as ND.
351///
352/// \param RelativeToPrimary true if we should get the template
353/// arguments relative to the primary template, even when we're
354/// dealing with a specialization. This is only relevant for function
355/// template specializations.
356///
357/// \param Pattern If non-NULL, indicates the pattern from which we will be
358/// instantiating the definition of the given declaration, \p ND. This is
359/// used to determine the proper set of template instantiation arguments for
360/// friend function template specializations.
361///
362/// \param ForConstraintInstantiation when collecting arguments,
363/// ForConstraintInstantiation indicates we should continue looking when
364/// encountering a lambda generic call operator, and continue looking for
365/// arguments on an enclosing class template.
366
368 const NamedDecl *ND, const DeclContext *DC, bool Final,
369 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
370 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
371 bool SkipForSpecialization) {
372 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
373 // Accumulate the set of template argument lists in this structure.
375
376 using namespace TemplateInstArgsHelpers;
377 const Decl *CurDecl = ND;
378
379 if (!CurDecl)
380 CurDecl = Decl::castFromDeclContext(DC);
381
382 if (Innermost) {
383 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
384 Final);
385 // Populate placeholder template arguments for TemplateTemplateParmDecls.
386 // This is essential for the case e.g.
387 //
388 // template <class> concept Concept = false;
389 // template <template <Concept C> class T> void foo(T<int>)
390 //
391 // where parameter C has a depth of 1 but the substituting argument `int`
392 // has a depth of 0.
393 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
394 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
395 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
396 }
397
398 while (!CurDecl->isFileContextDecl()) {
399 Response R;
400 if (const auto *VarTemplSpec =
401 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
402 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
403 } else if (const auto *PartialClassTemplSpec =
404 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
405 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
406 SkipForSpecialization);
407 } else if (const auto *ClassTemplSpec =
408 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
409 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
410 SkipForSpecialization);
411 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
412 R = HandleFunction(Function, Result, Pattern, RelativeToPrimary,
413 ForConstraintInstantiation);
414 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
415 R = HandleRecordDecl(Rec, Result, Context, ForConstraintInstantiation);
416 } else if (const auto *CSD =
417 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
418 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
419 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
420 R = HandleFunctionTemplateDecl(FTD, Result);
421 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
422 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
423 } else if (!isa<DeclContext>(CurDecl)) {
424 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
425 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
426 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
427 }
428 } else {
429 R = HandleGenericDeclContext(CurDecl);
430 }
431
432 if (R.IsDone)
433 return Result;
434 if (R.ClearRelativeToPrimary)
435 RelativeToPrimary = false;
436 assert(R.NextDecl);
437 CurDecl = R.NextDecl;
438 }
439
440 return Result;
441}
442
444 switch (Kind) {
452 case ConstraintsCheck:
454 return true;
455
472 return false;
473
474 // This function should never be called when Kind's value is Memoization.
475 case Memoization:
476 break;
477 }
478
479 llvm_unreachable("Invalid SynthesisKind!");
480}
481
484 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
485 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
486 sema::TemplateDeductionInfo *DeductionInfo)
487 : SemaRef(SemaRef) {
488 // Don't allow further instantiation if a fatal error and an uncompilable
489 // error have occurred. Any diagnostics we might have raised will not be
490 // visible, and we do not need to construct a correct AST.
491 if (SemaRef.Diags.hasFatalErrorOccurred() &&
493 Invalid = true;
494 return;
495 }
496 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
497 if (!Invalid) {
499 Inst.Kind = Kind;
500 Inst.PointOfInstantiation = PointOfInstantiation;
501 Inst.Entity = Entity;
502 Inst.Template = Template;
503 Inst.TemplateArgs = TemplateArgs.data();
504 Inst.NumTemplateArgs = TemplateArgs.size();
505 Inst.DeductionInfo = DeductionInfo;
506 Inst.InstantiationRange = InstantiationRange;
507 SemaRef.pushCodeSynthesisContext(Inst);
508
509 AlreadyInstantiating = !Inst.Entity ? false :
511 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
512 .second;
513 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
514 }
515}
516
518 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
519 SourceRange InstantiationRange)
520 : InstantiatingTemplate(SemaRef,
521 CodeSynthesisContext::TemplateInstantiation,
522 PointOfInstantiation, InstantiationRange, Entity) {}
523
525 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
526 ExceptionSpecification, SourceRange InstantiationRange)
528 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
529 PointOfInstantiation, InstantiationRange, Entity) {}
530
532 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
533 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
534 SourceRange InstantiationRange)
536 SemaRef,
537 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
538 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
539 Template, TemplateArgs) {}
540
542 Sema &SemaRef, SourceLocation PointOfInstantiation,
544 ArrayRef<TemplateArgument> TemplateArgs,
546 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
547 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
548 InstantiationRange, FunctionTemplate, nullptr,
549 TemplateArgs, &DeductionInfo) {
550 assert(
553}
554
556 Sema &SemaRef, SourceLocation PointOfInstantiation,
557 TemplateDecl *Template,
558 ArrayRef<TemplateArgument> TemplateArgs,
559 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
561 SemaRef,
562 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
563 PointOfInstantiation, InstantiationRange, Template, nullptr,
564 TemplateArgs, &DeductionInfo) {}
565
567 Sema &SemaRef, SourceLocation PointOfInstantiation,
569 ArrayRef<TemplateArgument> TemplateArgs,
570 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
572 SemaRef,
573 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
574 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
575 TemplateArgs, &DeductionInfo) {}
576
578 Sema &SemaRef, SourceLocation PointOfInstantiation,
580 ArrayRef<TemplateArgument> TemplateArgs,
581 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
583 SemaRef,
584 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
585 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
586 TemplateArgs, &DeductionInfo) {}
587
589 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
590 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
592 SemaRef,
593 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
594 PointOfInstantiation, InstantiationRange, Param, nullptr,
595 TemplateArgs) {}
596
598 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
600 SourceRange InstantiationRange)
602 SemaRef,
603 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
604 PointOfInstantiation, InstantiationRange, Param, Template,
605 TemplateArgs) {}
606
608 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
610 SourceRange InstantiationRange)
612 SemaRef,
613 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
614 PointOfInstantiation, InstantiationRange, Param, Template,
615 TemplateArgs) {}
616
618 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
619 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
620 SourceRange InstantiationRange)
622 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
623 PointOfInstantiation, InstantiationRange, Param, Template,
624 TemplateArgs) {}
625
627 Sema &SemaRef, SourceLocation PointOfInstantiation,
629 SourceRange InstantiationRange)
631 SemaRef, CodeSynthesisContext::RequirementInstantiation,
632 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
633 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
634}
635
637 Sema &SemaRef, SourceLocation PointOfInstantiation,
639 SourceRange InstantiationRange)
641 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
642 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
643 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
644
646 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
647 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
649 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
650 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
651 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
652}
653
655 Sema &SemaRef, SourceLocation PointOfInstantiation,
656 ConstraintsCheck, NamedDecl *Template,
657 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
660 PointOfInstantiation, InstantiationRange, Template, nullptr,
661 TemplateArgs) {}
662
664 Sema &SemaRef, SourceLocation PointOfInstantiation,
666 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
669 PointOfInstantiation, InstantiationRange, Template, nullptr,
670 {}, &DeductionInfo) {}
671
673 Sema &SemaRef, SourceLocation PointOfInstantiation,
675 SourceRange InstantiationRange)
678 PointOfInstantiation, InstantiationRange, Template) {}
679
681 Sema &SemaRef, SourceLocation PointOfInstantiation,
683 SourceRange InstantiationRange)
686 PointOfInstantiation, InstantiationRange, Template) {}
687
689 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
690 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
692 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
693 PointOfInstantiation, InstantiationRange, Entity) {}
694
695
699
700 CodeSynthesisContexts.push_back(Ctx);
701
702 if (!Ctx.isInstantiationRecord())
704
705 // Check to see if we're low on stack space. We can't do anything about this
706 // from here, but we can at least warn the user.
709}
710
712 auto &Active = CodeSynthesisContexts.back();
713 if (!Active.isInstantiationRecord()) {
714 assert(NonInstantiationEntries > 0);
716 }
717
718 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
719
720 // Name lookup no longer looks in this template's defining module.
721 assert(CodeSynthesisContexts.size() >=
723 "forgot to remove a lookup module for a template instantiation");
724 if (CodeSynthesisContexts.size() ==
727 LookupModulesCache.erase(M);
729 }
730
731 // If we've left the code synthesis context for the current context stack,
732 // stop remembering that we've emitted that stack.
733 if (CodeSynthesisContexts.size() ==
736
737 CodeSynthesisContexts.pop_back();
738}
739
741 if (!Invalid) {
742 if (!AlreadyInstantiating) {
743 auto &Active = SemaRef.CodeSynthesisContexts.back();
744 if (Active.Entity)
745 SemaRef.InstantiatingSpecializations.erase(
746 {Active.Entity->getCanonicalDecl(), Active.Kind});
747 }
748
749 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
750 SemaRef.CodeSynthesisContexts.back());
751
752 SemaRef.popCodeSynthesisContext();
753 Invalid = true;
754 }
755}
756
757static std::string convertCallArgsToString(Sema &S,
759 std::string Result;
760 llvm::raw_string_ostream OS(Result);
761 llvm::ListSeparator Comma;
762 for (const Expr *Arg : Args) {
763 OS << Comma;
764 Arg->IgnoreParens()->printPretty(OS, nullptr,
766 }
767 return Result;
768}
769
770bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
771 SourceLocation PointOfInstantiation,
772 SourceRange InstantiationRange) {
773 assert(SemaRef.NonInstantiationEntries <=
774 SemaRef.CodeSynthesisContexts.size());
775 if ((SemaRef.CodeSynthesisContexts.size() -
777 <= SemaRef.getLangOpts().InstantiationDepth)
778 return false;
779
780 SemaRef.Diag(PointOfInstantiation,
781 diag::err_template_recursion_depth_exceeded)
782 << SemaRef.getLangOpts().InstantiationDepth
783 << InstantiationRange;
784 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
785 << SemaRef.getLangOpts().InstantiationDepth;
786 return true;
787}
788
789/// Prints the current instantiation stack through a series of
790/// notes.
792 // Determine which template instantiations to skip, if any.
793 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
794 unsigned Limit = Diags.getTemplateBacktraceLimit();
795 if (Limit && Limit < CodeSynthesisContexts.size()) {
796 SkipStart = Limit / 2 + Limit % 2;
797 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
798 }
799
800 // FIXME: In all of these cases, we need to show the template arguments
801 unsigned InstantiationIdx = 0;
803 Active = CodeSynthesisContexts.rbegin(),
804 ActiveEnd = CodeSynthesisContexts.rend();
805 Active != ActiveEnd;
806 ++Active, ++InstantiationIdx) {
807 // Skip this instantiation?
808 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
809 if (InstantiationIdx == SkipStart) {
810 // Note that we're skipping instantiations.
811 Diags.Report(Active->PointOfInstantiation,
812 diag::note_instantiation_contexts_suppressed)
813 << unsigned(CodeSynthesisContexts.size() - Limit);
814 }
815 continue;
816 }
817
818 switch (Active->Kind) {
820 Decl *D = Active->Entity;
821 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
822 unsigned DiagID = diag::note_template_member_class_here;
823 if (isa<ClassTemplateSpecializationDecl>(Record))
824 DiagID = diag::note_template_class_instantiation_here;
825 Diags.Report(Active->PointOfInstantiation, DiagID)
826 << Record << Active->InstantiationRange;
827 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
828 unsigned DiagID;
829 if (Function->getPrimaryTemplate())
830 DiagID = diag::note_function_template_spec_here;
831 else
832 DiagID = diag::note_template_member_function_here;
833 Diags.Report(Active->PointOfInstantiation, DiagID)
834 << Function
835 << Active->InstantiationRange;
836 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
837 Diags.Report(Active->PointOfInstantiation,
838 VD->isStaticDataMember()?
839 diag::note_template_static_data_member_def_here
840 : diag::note_template_variable_def_here)
841 << VD
842 << Active->InstantiationRange;
843 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
844 Diags.Report(Active->PointOfInstantiation,
845 diag::note_template_enum_def_here)
846 << ED
847 << Active->InstantiationRange;
848 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
849 Diags.Report(Active->PointOfInstantiation,
850 diag::note_template_nsdmi_here)
851 << FD << Active->InstantiationRange;
852 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
853 Diags.Report(Active->PointOfInstantiation,
854 diag::note_template_class_instantiation_here)
855 << CTD << Active->InstantiationRange;
856 } else {
857 Diags.Report(Active->PointOfInstantiation,
858 diag::note_template_type_alias_instantiation_here)
859 << cast<TypeAliasTemplateDecl>(D)
860 << Active->InstantiationRange;
861 }
862 break;
863 }
864
866 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
867 SmallString<128> TemplateArgsStr;
868 llvm::raw_svector_ostream OS(TemplateArgsStr);
869 Template->printName(OS, getPrintingPolicy());
870 printTemplateArgumentList(OS, Active->template_arguments(),
872 Diags.Report(Active->PointOfInstantiation,
873 diag::note_default_arg_instantiation_here)
874 << OS.str()
875 << Active->InstantiationRange;
876 break;
877 }
878
880 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
881 Diags.Report(Active->PointOfInstantiation,
882 diag::note_explicit_template_arg_substitution_here)
883 << FnTmpl
885 Active->TemplateArgs,
886 Active->NumTemplateArgs)
887 << Active->InstantiationRange;
888 break;
889 }
890
892 if (FunctionTemplateDecl *FnTmpl =
893 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
894 Diags.Report(Active->PointOfInstantiation,
895 diag::note_function_template_deduction_instantiation_here)
896 << FnTmpl
897 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
898 Active->TemplateArgs,
899 Active->NumTemplateArgs)
900 << Active->InstantiationRange;
901 } else {
902 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
903 isa<VarTemplateSpecializationDecl>(Active->Entity);
904 bool IsTemplate = false;
905 TemplateParameterList *Params;
906 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
907 IsTemplate = true;
908 Params = D->getTemplateParameters();
909 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
910 Active->Entity)) {
911 Params = D->getTemplateParameters();
912 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
913 Active->Entity)) {
914 Params = D->getTemplateParameters();
915 } else {
916 llvm_unreachable("unexpected template kind");
917 }
918
919 Diags.Report(Active->PointOfInstantiation,
920 diag::note_deduced_template_arg_substitution_here)
921 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
922 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
923 Active->NumTemplateArgs)
924 << Active->InstantiationRange;
925 }
926 break;
927 }
928
930 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
931 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
932
933 SmallString<128> TemplateArgsStr;
934 llvm::raw_svector_ostream OS(TemplateArgsStr);
936 printTemplateArgumentList(OS, Active->template_arguments(),
938 Diags.Report(Active->PointOfInstantiation,
939 diag::note_default_function_arg_instantiation_here)
940 << OS.str()
941 << Active->InstantiationRange;
942 break;
943 }
944
946 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
947 std::string Name;
948 if (!Parm->getName().empty())
949 Name = std::string(" '") + Parm->getName().str() + "'";
950
951 TemplateParameterList *TemplateParams = nullptr;
952 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
953 TemplateParams = Template->getTemplateParameters();
954 else
955 TemplateParams =
956 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
957 ->getTemplateParameters();
958 Diags.Report(Active->PointOfInstantiation,
959 diag::note_prior_template_arg_substitution)
960 << isa<TemplateTemplateParmDecl>(Parm)
961 << Name
962 << getTemplateArgumentBindingsText(TemplateParams,
963 Active->TemplateArgs,
964 Active->NumTemplateArgs)
965 << Active->InstantiationRange;
966 break;
967 }
968
970 TemplateParameterList *TemplateParams = nullptr;
971 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
972 TemplateParams = Template->getTemplateParameters();
973 else
974 TemplateParams =
975 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
976 ->getTemplateParameters();
977
978 Diags.Report(Active->PointOfInstantiation,
979 diag::note_template_default_arg_checking)
980 << getTemplateArgumentBindingsText(TemplateParams,
981 Active->TemplateArgs,
982 Active->NumTemplateArgs)
983 << Active->InstantiationRange;
984 break;
985 }
986
988 Diags.Report(Active->PointOfInstantiation,
989 diag::note_evaluating_exception_spec_here)
990 << cast<FunctionDecl>(Active->Entity);
991 break;
992
994 Diags.Report(Active->PointOfInstantiation,
995 diag::note_template_exception_spec_instantiation_here)
996 << cast<FunctionDecl>(Active->Entity)
997 << Active->InstantiationRange;
998 break;
999
1001 Diags.Report(Active->PointOfInstantiation,
1002 diag::note_template_requirement_instantiation_here)
1003 << Active->InstantiationRange;
1004 break;
1006 Diags.Report(Active->PointOfInstantiation,
1007 diag::note_template_requirement_params_instantiation_here)
1008 << Active->InstantiationRange;
1009 break;
1010
1012 Diags.Report(Active->PointOfInstantiation,
1013 diag::note_nested_requirement_here)
1014 << Active->InstantiationRange;
1015 break;
1016
1018 Diags.Report(Active->PointOfInstantiation,
1019 diag::note_in_declaration_of_implicit_special_member)
1020 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
1021 break;
1022
1024 Diags.Report(Active->Entity->getLocation(),
1025 diag::note_in_declaration_of_implicit_equality_comparison);
1026 break;
1027
1029 // FIXME: For synthesized functions that are not defaulted,
1030 // produce a note.
1031 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1034 if (DFK.isSpecialMember()) {
1035 auto *MD = cast<CXXMethodDecl>(FD);
1036 Diags.Report(Active->PointOfInstantiation,
1037 diag::note_member_synthesized_at)
1038 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
1039 << Context.getTagDeclType(MD->getParent());
1040 } else if (DFK.isComparison()) {
1041 QualType RecordType = FD->getParamDecl(0)
1042 ->getType()
1043 .getNonReferenceType()
1044 .getUnqualifiedType();
1045 Diags.Report(Active->PointOfInstantiation,
1046 diag::note_comparison_synthesized_at)
1047 << (int)DFK.asComparison() << RecordType;
1048 }
1049 break;
1050 }
1051
1053 Diags.Report(Active->Entity->getLocation(),
1054 diag::note_rewriting_operator_as_spaceship);
1055 break;
1056
1058 Diags.Report(Active->PointOfInstantiation,
1059 diag::note_in_binding_decl_init)
1060 << cast<BindingDecl>(Active->Entity);
1061 break;
1062
1064 Diags.Report(Active->PointOfInstantiation,
1065 diag::note_due_to_dllexported_class)
1066 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1067 break;
1068
1070 Diags.Report(Active->PointOfInstantiation,
1071 diag::note_building_builtin_dump_struct_call)
1073 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1074 break;
1075
1077 break;
1078
1080 Diags.Report(Active->PointOfInstantiation,
1081 diag::note_lambda_substitution_here);
1082 break;
1084 unsigned DiagID = 0;
1085 if (!Active->Entity) {
1086 Diags.Report(Active->PointOfInstantiation,
1087 diag::note_nested_requirement_here)
1088 << Active->InstantiationRange;
1089 break;
1090 }
1091 if (isa<ConceptDecl>(Active->Entity))
1092 DiagID = diag::note_concept_specialization_here;
1093 else if (isa<TemplateDecl>(Active->Entity))
1094 DiagID = diag::note_checking_constraints_for_template_id_here;
1095 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1096 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1097 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1098 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1099 else {
1100 assert(isa<FunctionDecl>(Active->Entity));
1101 DiagID = diag::note_checking_constraints_for_function_here;
1102 }
1103 SmallString<128> TemplateArgsStr;
1104 llvm::raw_svector_ostream OS(TemplateArgsStr);
1105 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1106 if (!isa<FunctionDecl>(Active->Entity)) {
1107 printTemplateArgumentList(OS, Active->template_arguments(),
1109 }
1110 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1111 << Active->InstantiationRange;
1112 break;
1113 }
1115 Diags.Report(Active->PointOfInstantiation,
1116 diag::note_constraint_substitution_here)
1117 << Active->InstantiationRange;
1118 break;
1120 Diags.Report(Active->PointOfInstantiation,
1121 diag::note_constraint_normalization_here)
1122 << cast<NamedDecl>(Active->Entity)->getName()
1123 << Active->InstantiationRange;
1124 break;
1126 Diags.Report(Active->PointOfInstantiation,
1127 diag::note_parameter_mapping_substitution_here)
1128 << Active->InstantiationRange;
1129 break;
1131 Diags.Report(Active->PointOfInstantiation,
1132 diag::note_building_deduction_guide_here);
1133 break;
1134 }
1135 }
1136}
1137
1138std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1140 return std::optional<TemplateDeductionInfo *>(nullptr);
1141
1143 Active = CodeSynthesisContexts.rbegin(),
1144 ActiveEnd = CodeSynthesisContexts.rend();
1145 Active != ActiveEnd;
1146 ++Active)
1147 {
1148 switch (Active->Kind) {
1150 // An instantiation of an alias template may or may not be a SFINAE
1151 // context, depending on what else is on the stack.
1152 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1153 break;
1154 [[fallthrough]];
1161 // This is a template instantiation, so there is no SFINAE.
1162 return std::nullopt;
1164 // [temp.deduct]p9
1165 // A lambda-expression appearing in a function type or a template
1166 // parameter is not considered part of the immediate context for the
1167 // purposes of template argument deduction.
1168 // CWG2672: A lambda-expression body is never in the immediate context.
1169 return std::nullopt;
1170
1175 // A default template argument instantiation and substitution into
1176 // template parameters with arguments for prior parameters may or may
1177 // not be a SFINAE context; look further up the stack.
1178 break;
1179
1182 // We're either substituting explicitly-specified template arguments,
1183 // deduced template arguments. SFINAE applies unless we are in a lambda
1184 // body, see [temp.deduct]p9.
1188 // SFINAE always applies in a constraint expression or a requirement
1189 // in a requires expression.
1190 assert(Active->DeductionInfo && "Missing deduction info pointer");
1191 return Active->DeductionInfo;
1192
1200 // This happens in a context unrelated to template instantiation, so
1201 // there is no SFINAE.
1202 return std::nullopt;
1203
1205 // FIXME: This should not be treated as a SFINAE context, because
1206 // we will cache an incorrect exception specification. However, clang
1207 // bootstrap relies this! See PR31692.
1208 break;
1209
1211 break;
1212 }
1213
1214 // The inner context was transparent for SFINAE. If it occurred within a
1215 // non-instantiation SFINAE context, then SFINAE applies.
1216 if (Active->SavedInNonInstantiationSFINAEContext)
1217 return std::optional<TemplateDeductionInfo *>(nullptr);
1218 }
1219
1220 return std::nullopt;
1221}
1222
1223//===----------------------------------------------------------------------===/
1224// Template Instantiation for Types
1225//===----------------------------------------------------------------------===/
1226namespace {
1227 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1228 const MultiLevelTemplateArgumentList &TemplateArgs;
1229 SourceLocation Loc;
1230 DeclarationName Entity;
1231 // Whether to evaluate the C++20 constraints or simply substitute into them.
1232 bool EvaluateConstraints = true;
1233
1234 public:
1235 typedef TreeTransform<TemplateInstantiator> inherited;
1236
1237 TemplateInstantiator(Sema &SemaRef,
1238 const MultiLevelTemplateArgumentList &TemplateArgs,
1239 SourceLocation Loc, DeclarationName Entity)
1240 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1241 Entity(Entity) {}
1242
1243 void setEvaluateConstraints(bool B) {
1244 EvaluateConstraints = B;
1245 }
1246 bool getEvaluateConstraints() {
1247 return EvaluateConstraints;
1248 }
1249
1250 /// Determine whether the given type \p T has already been
1251 /// transformed.
1252 ///
1253 /// For the purposes of template instantiation, a type has already been
1254 /// transformed if it is NULL or if it is not dependent.
1255 bool AlreadyTransformed(QualType T);
1256
1257 /// Returns the location of the entity being instantiated, if known.
1258 SourceLocation getBaseLocation() { return Loc; }
1259
1260 /// Returns the name of the entity being instantiated, if any.
1261 DeclarationName getBaseEntity() { return Entity; }
1262
1263 /// Sets the "base" location and entity when that
1264 /// information is known based on another transformation.
1265 void setBase(SourceLocation Loc, DeclarationName Entity) {
1266 this->Loc = Loc;
1267 this->Entity = Entity;
1268 }
1269
1270 unsigned TransformTemplateDepth(unsigned Depth) {
1271 return TemplateArgs.getNewDepth(Depth);
1272 }
1273
1274 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1275 int Index = getSema().ArgumentPackSubstitutionIndex;
1276 if (Index == -1)
1277 return std::nullopt;
1278 return Pack.pack_size() - 1 - Index;
1279 }
1280
1281 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1282 SourceRange PatternRange,
1284 bool &ShouldExpand, bool &RetainExpansion,
1285 std::optional<unsigned> &NumExpansions) {
1286 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1287 PatternRange, Unexpanded,
1288 TemplateArgs,
1289 ShouldExpand,
1290 RetainExpansion,
1291 NumExpansions);
1292 }
1293
1294 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1296 }
1297
1298 TemplateArgument ForgetPartiallySubstitutedPack() {
1299 TemplateArgument Result;
1300 if (NamedDecl *PartialPack
1302 MultiLevelTemplateArgumentList &TemplateArgs
1303 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1304 unsigned Depth, Index;
1305 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1306 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1307 Result = TemplateArgs(Depth, Index);
1308 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1309 }
1310 }
1311
1312 return Result;
1313 }
1314
1315 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1316 if (Arg.isNull())
1317 return;
1318
1319 if (NamedDecl *PartialPack
1321 MultiLevelTemplateArgumentList &TemplateArgs
1322 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1323 unsigned Depth, Index;
1324 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1325 TemplateArgs.setArgument(Depth, Index, Arg);
1326 }
1327 }
1328
1329 /// Transform the given declaration by instantiating a reference to
1330 /// this declaration.
1331 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1332
1333 void transformAttrs(Decl *Old, Decl *New) {
1334 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1335 }
1336
1337 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1338 if (Old->isParameterPack()) {
1340 for (auto *New : NewDecls)
1342 Old, cast<VarDecl>(New));
1343 return;
1344 }
1345
1346 assert(NewDecls.size() == 1 &&
1347 "should only have multiple expansions for a pack");
1348 Decl *New = NewDecls.front();
1349
1350 // If we've instantiated the call operator of a lambda or the call
1351 // operator template of a generic lambda, update the "instantiation of"
1352 // information.
1353 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1354 if (NewMD && isLambdaCallOperator(NewMD)) {
1355 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1356 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1357 NewTD->setInstantiatedFromMemberTemplate(
1358 OldMD->getDescribedFunctionTemplate());
1359 else
1360 NewMD->setInstantiationOfMemberFunction(OldMD,
1362 }
1363
1365
1366 // We recreated a local declaration, but not by instantiating it. There
1367 // may be pending dependent diagnostics to produce.
1368 if (auto *DC = dyn_cast<DeclContext>(Old);
1369 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1370 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1371 }
1372
1373 /// Transform the definition of the given declaration by
1374 /// instantiating it.
1375 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1376
1377 /// Transform the first qualifier within a scope by instantiating the
1378 /// declaration.
1379 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1380
1381 bool TransformExceptionSpec(SourceLocation Loc,
1383 SmallVectorImpl<QualType> &Exceptions,
1384 bool &Changed);
1385
1386 /// Rebuild the exception declaration and register the declaration
1387 /// as an instantiated local.
1388 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1390 SourceLocation StartLoc,
1391 SourceLocation NameLoc,
1392 IdentifierInfo *Name);
1393
1394 /// Rebuild the Objective-C exception declaration and register the
1395 /// declaration as an instantiated local.
1396 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1397 TypeSourceInfo *TSInfo, QualType T);
1398
1399 /// Check for tag mismatches when instantiating an
1400 /// elaborated type.
1401 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1402 ElaboratedTypeKeyword Keyword,
1403 NestedNameSpecifierLoc QualifierLoc,
1404 QualType T);
1405
1407 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1408 SourceLocation NameLoc,
1409 QualType ObjectType = QualType(),
1410 NamedDecl *FirstQualifierInScope = nullptr,
1411 bool AllowInjectedClassName = false);
1412
1413 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1414 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1415 const Stmt *InstS,
1416 const NoInlineAttr *A);
1417 const AlwaysInlineAttr *
1418 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1419 const AlwaysInlineAttr *A);
1420 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1421 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1422 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1423 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1424
1425 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1427 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1429 ExprResult TransformSubstNonTypeTemplateParmExpr(
1431
1432 /// Rebuild a DeclRefExpr for a VarDecl reference.
1433 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1434
1435 /// Transform a reference to a function or init-capture parameter pack.
1436 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1437
1438 /// Transform a FunctionParmPackExpr which was built when we couldn't
1439 /// expand a function parameter pack reference which refers to an expanded
1440 /// pack.
1441 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1442
1443 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1445 // Call the base version; it will forward to our overridden version below.
1446 return inherited::TransformFunctionProtoType(TLB, TL);
1447 }
1448
1449 template<typename Fn>
1450 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1452 CXXRecordDecl *ThisContext,
1453 Qualifiers ThisTypeQuals,
1454 Fn TransformExceptionSpec);
1455
1456 ParmVarDecl *
1457 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1458 std::optional<unsigned> NumExpansions,
1459 bool ExpectParameterPack);
1460
1461 using inherited::TransformTemplateTypeParmType;
1462 /// Transforms a template type parameter type by performing
1463 /// substitution of the corresponding template type argument.
1464 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1466 bool SuppressObjCLifetime);
1467
1468 QualType BuildSubstTemplateTypeParmType(
1469 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1470 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1471 TemplateArgument Arg, SourceLocation NameLoc);
1472
1473 /// Transforms an already-substituted template type parameter pack
1474 /// into either itself (if we aren't substituting into its pack expansion)
1475 /// or the appropriate substituted argument.
1476 using inherited::TransformSubstTemplateTypeParmPackType;
1477 QualType
1478 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1480 bool SuppressObjCLifetime);
1481
1482 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1483 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1485
1486 ExprResult Result = inherited::TransformLambdaExpr(E);
1487 if (Result.isInvalid())
1488 return Result;
1489
1490 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1491 for (ParmVarDecl *PVD : MD->parameters()) {
1492 assert(PVD && "null in a parameter list");
1493 if (!PVD->hasDefaultArg())
1494 continue;
1495 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1496 // FIXME: Obtain the source location for the '=' token.
1497 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1498 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1499 // If substitution fails, the default argument is set to a
1500 // RecoveryExpr that wraps the uninstantiated default argument so
1501 // that downstream diagnostics are omitted.
1502 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1503 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1504 { UninstExpr }, UninstExpr->getType());
1505 if (ErrorResult.isUsable())
1506 PVD->setDefaultArg(ErrorResult.get());
1507 }
1508 }
1509
1510 return Result;
1511 }
1512
1513 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1514 // Currently, we instantiate the body when instantiating the lambda
1515 // expression. However, `EvaluateConstraints` is disabled during the
1516 // instantiation of the lambda expression, causing the instantiation
1517 // failure of the return type requirement in the body. If p0588r1 is fully
1518 // implemented, the body will be lazily instantiated, and this problem
1519 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1520 // `true` to temporarily fix this issue.
1521 // FIXME: This temporary fix can be removed after fully implementing
1522 // p0588r1.
1523 bool Prev = EvaluateConstraints;
1524 EvaluateConstraints = true;
1525 StmtResult Stmt = inherited::TransformLambdaBody(E, Body);
1526 EvaluateConstraints = Prev;
1527 return Stmt;
1528 }
1529
1530 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1531 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1532 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1533 if (TransReq.isInvalid())
1534 return TransReq;
1535 assert(TransReq.get() != E &&
1536 "Do not change value of isSatisfied for the existing expression. "
1537 "Create a new expression instead.");
1538 if (E->getBody()->isDependentContext()) {
1539 Sema::SFINAETrap Trap(SemaRef);
1540 // We recreate the RequiresExpr body, but not by instantiating it.
1541 // Produce pending diagnostics for dependent access check.
1542 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1543 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1544 if (Trap.hasErrorOccurred())
1545 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1546 }
1547 return TransReq;
1548 }
1549
1550 bool TransformRequiresExprRequirements(
1553 bool SatisfactionDetermined = false;
1554 for (concepts::Requirement *Req : Reqs) {
1555 concepts::Requirement *TransReq = nullptr;
1556 if (!SatisfactionDetermined) {
1557 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1558 TransReq = TransformTypeRequirement(TypeReq);
1559 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1560 TransReq = TransformExprRequirement(ExprReq);
1561 else
1562 TransReq = TransformNestedRequirement(
1563 cast<concepts::NestedRequirement>(Req));
1564 if (!TransReq)
1565 return true;
1566 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1567 // [expr.prim.req]p6
1568 // [...] The substitution and semantic constraint checking
1569 // proceeds in lexical order and stops when a condition that
1570 // determines the result of the requires-expression is
1571 // encountered. [..]
1572 SatisfactionDetermined = true;
1573 } else
1574 TransReq = Req;
1575 Transformed.push_back(TransReq);
1576 }
1577 return false;
1578 }
1579
1580 TemplateParameterList *TransformTemplateParameterList(
1581 TemplateParameterList *OrigTPL) {
1582 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1583
1584 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1585 TemplateDeclInstantiator DeclInstantiator(getSema(),
1586 /* DeclContext *Owner */ Owner, TemplateArgs);
1587 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1588 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1589 }
1590
1592 TransformTypeRequirement(concepts::TypeRequirement *Req);
1594 TransformExprRequirement(concepts::ExprRequirement *Req);
1596 TransformNestedRequirement(concepts::NestedRequirement *Req);
1597 ExprResult TransformRequiresTypeParams(
1598 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1601 SmallVectorImpl<ParmVarDecl *> &TransParams,
1603
1604 private:
1606 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1607 const NonTypeTemplateParmDecl *parm,
1609 std::optional<unsigned> PackIndex);
1610 };
1611}
1612
1613bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1614 if (T.isNull())
1615 return true;
1616
1618 return false;
1619
1620 getSema().MarkDeclarationsReferencedInType(Loc, T);
1621 return true;
1622}
1623
1624static TemplateArgument
1626 assert(S.ArgumentPackSubstitutionIndex >= 0);
1627 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1629 if (Arg.isPackExpansion())
1630 Arg = Arg.getPackExpansionPattern();
1631 return Arg;
1632}
1633
1634Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1635 if (!D)
1636 return nullptr;
1637
1638 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1639 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1640 // If the corresponding template argument is NULL or non-existent, it's
1641 // because we are performing instantiation from explicitly-specified
1642 // template arguments in a function template, but there were some
1643 // arguments left unspecified.
1644 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1645 TTP->getPosition()))
1646 return D;
1647
1648 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1649
1650 if (TTP->isParameterPack()) {
1651 assert(Arg.getKind() == TemplateArgument::Pack &&
1652 "Missing argument pack");
1653 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1654 }
1655
1657 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1658 "Wrong kind of template template argument");
1659 return Template.getAsTemplateDecl();
1660 }
1661
1662 // Fall through to find the instantiated declaration for this template
1663 // template parameter.
1664 }
1665
1666 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1667}
1668
1669Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1670 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1671 if (!Inst)
1672 return nullptr;
1673
1674 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1675 return Inst;
1676}
1677
1678bool TemplateInstantiator::TransformExceptionSpec(
1680 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1681 if (ESI.Type == EST_Uninstantiated) {
1682 ESI.instantiate();
1683 Changed = true;
1684 }
1685 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1686}
1687
1688NamedDecl *
1689TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1690 SourceLocation Loc) {
1691 // If the first part of the nested-name-specifier was a template type
1692 // parameter, instantiate that type parameter down to a tag type.
1693 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1694 const TemplateTypeParmType *TTP
1695 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1696
1697 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1698 // FIXME: This needs testing w/ member access expressions.
1699 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1700
1701 if (TTP->isParameterPack()) {
1702 assert(Arg.getKind() == TemplateArgument::Pack &&
1703 "Missing argument pack");
1704
1705 if (getSema().ArgumentPackSubstitutionIndex == -1)
1706 return nullptr;
1707
1708 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1709 }
1710
1711 QualType T = Arg.getAsType();
1712 if (T.isNull())
1713 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1714
1715 if (const TagType *Tag = T->getAs<TagType>())
1716 return Tag->getDecl();
1717
1718 // The resulting type is not a tag; complain.
1719 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1720 return nullptr;
1721 }
1722 }
1723
1724 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1725}
1726
1727VarDecl *
1728TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1730 SourceLocation StartLoc,
1731 SourceLocation NameLoc,
1732 IdentifierInfo *Name) {
1733 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1734 StartLoc, NameLoc, Name);
1735 if (Var)
1736 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1737 return Var;
1738}
1739
1740VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1741 TypeSourceInfo *TSInfo,
1742 QualType T) {
1743 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1744 if (Var)
1745 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1746 return Var;
1747}
1748
1750TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1751 ElaboratedTypeKeyword Keyword,
1752 NestedNameSpecifierLoc QualifierLoc,
1753 QualType T) {
1754 if (const TagType *TT = T->getAs<TagType>()) {
1755 TagDecl* TD = TT->getDecl();
1756
1757 SourceLocation TagLocation = KeywordLoc;
1758
1760
1761 // TODO: should we even warn on struct/class mismatches for this? Seems
1762 // like it's likely to produce a lot of spurious errors.
1763 if (Id && Keyword != ElaboratedTypeKeyword::None &&
1766 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1767 TagLocation, Id)) {
1768 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1769 << Id
1771 TD->getKindName());
1772 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1773 }
1774 }
1775 }
1776
1777 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1778}
1779
1780TemplateName TemplateInstantiator::TransformTemplateName(
1781 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1782 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1783 bool AllowInjectedClassName) {
1785 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1786 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1787 // If the corresponding template argument is NULL or non-existent, it's
1788 // because we are performing instantiation from explicitly-specified
1789 // template arguments in a function template, but there were some
1790 // arguments left unspecified.
1791 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1792 TTP->getPosition()))
1793 return Name;
1794
1795 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1796
1797 if (TemplateArgs.isRewrite()) {
1798 // We're rewriting the template parameter as a reference to another
1799 // template parameter.
1800 if (Arg.getKind() == TemplateArgument::Pack) {
1801 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1802 "unexpected pack arguments in template rewrite");
1803 Arg = Arg.pack_begin()->getPackExpansionPattern();
1804 }
1805 assert(Arg.getKind() == TemplateArgument::Template &&
1806 "unexpected nontype template argument kind in template rewrite");
1807 return Arg.getAsTemplate();
1808 }
1809
1810 auto [AssociatedDecl, Final] =
1811 TemplateArgs.getAssociatedDecl(TTP->getDepth());
1812 std::optional<unsigned> PackIndex;
1813 if (TTP->isParameterPack()) {
1814 assert(Arg.getKind() == TemplateArgument::Pack &&
1815 "Missing argument pack");
1816
1817 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1818 // We have the template argument pack to substitute, but we're not
1819 // actually expanding the enclosing pack expansion yet. So, just
1820 // keep the entire argument pack.
1821 return getSema().Context.getSubstTemplateTemplateParmPack(
1822 Arg, AssociatedDecl, TTP->getIndex(), Final);
1823 }
1824
1825 PackIndex = getPackIndex(Arg);
1826 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1827 }
1828
1830 assert(!Template.isNull() && "Null template template argument");
1831 assert(!Template.getAsQualifiedTemplateName() &&
1832 "template decl to substitute is qualified?");
1833
1834 if (Final)
1835 return Template;
1836 return getSema().Context.getSubstTemplateTemplateParm(
1837 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
1838 }
1839 }
1840
1842 = Name.getAsSubstTemplateTemplateParmPack()) {
1843 if (getSema().ArgumentPackSubstitutionIndex == -1)
1844 return Name;
1845
1846 TemplateArgument Pack = SubstPack->getArgumentPack();
1847 TemplateName Template =
1849 if (SubstPack->getFinal())
1850 return Template;
1851 return getSema().Context.getSubstTemplateTemplateParm(
1852 Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(),
1853 SubstPack->getIndex(), getPackIndex(Pack));
1854 }
1855
1856 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1857 FirstQualifierInScope,
1858 AllowInjectedClassName);
1859}
1860
1862TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1863 if (!E->isTypeDependent())
1864 return E;
1865
1866 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1867}
1868
1870TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1872 // If the corresponding template argument is NULL or non-existent, it's
1873 // because we are performing instantiation from explicitly-specified
1874 // template arguments in a function template, but there were some
1875 // arguments left unspecified.
1876 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1877 NTTP->getPosition()))
1878 return E;
1879
1880 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1881
1882 if (TemplateArgs.isRewrite()) {
1883 // We're rewriting the template parameter as a reference to another
1884 // template parameter.
1885 if (Arg.getKind() == TemplateArgument::Pack) {
1886 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1887 "unexpected pack arguments in template rewrite");
1888 Arg = Arg.pack_begin()->getPackExpansionPattern();
1889 }
1890 assert(Arg.getKind() == TemplateArgument::Expression &&
1891 "unexpected nontype template argument kind in template rewrite");
1892 // FIXME: This can lead to the same subexpression appearing multiple times
1893 // in a complete expression.
1894 return Arg.getAsExpr();
1895 }
1896
1897 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
1898 std::optional<unsigned> PackIndex;
1899 if (NTTP->isParameterPack()) {
1900 assert(Arg.getKind() == TemplateArgument::Pack &&
1901 "Missing argument pack");
1902
1903 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1904 // We have an argument pack, but we can't select a particular argument
1905 // out of it yet. Therefore, we'll build an expression to hold on to that
1906 // argument pack.
1907 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1908 E->getLocation(),
1909 NTTP->getDeclName());
1910 if (TargetType.isNull())
1911 return ExprError();
1912
1913 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
1914 if (TargetType->isRecordType())
1915 ExprType.addConst();
1916 // FIXME: Pass in Final.
1917 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1918 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
1919 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
1920 }
1921 PackIndex = getPackIndex(Arg);
1922 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1923 }
1924 // FIXME: Don't put subst node on Final replacement.
1925 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
1926 Arg, PackIndex);
1927}
1928
1929const LoopHintAttr *
1930TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1931 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1932
1933 if (TransformedExpr == LH->getValue())
1934 return LH;
1935
1936 // Generate error if there is a problem with the value.
1937 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1938 return LH;
1939
1940 // Create new LoopHintValueAttr with integral expression in place of the
1941 // non-type template parameter.
1942 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1943 LH->getState(), TransformedExpr, *LH);
1944}
1945const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
1946 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
1947 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
1948 return nullptr;
1949
1950 return A;
1951}
1952const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
1953 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
1954 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
1955 return nullptr;
1956
1957 return A;
1958}
1959
1960const CodeAlignAttr *
1961TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
1962 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
1963 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
1964}
1965
1966ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1967 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
1969 std::optional<unsigned> PackIndex) {
1970 ExprResult result;
1971
1972 // Determine the substituted parameter type. We can usually infer this from
1973 // the template argument, but not always.
1974 auto SubstParamType = [&] {
1975 QualType T;
1976 if (parm->isExpandedParameterPack())
1978 else
1979 T = parm->getType();
1980 if (parm->isParameterPack() && isa<PackExpansionType>(T))
1981 T = cast<PackExpansionType>(T)->getPattern();
1982 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
1983 };
1984
1985 bool refParam = false;
1986
1987 // The template argument itself might be an expression, in which case we just
1988 // return that expression. This happens when substituting into an alias
1989 // template.
1990 if (arg.getKind() == TemplateArgument::Expression) {
1991 Expr *argExpr = arg.getAsExpr();
1992 result = argExpr;
1993 if (argExpr->isLValue()) {
1994 if (argExpr->getType()->isRecordType()) {
1995 // Check whether the parameter was actually a reference.
1996 QualType paramType = SubstParamType();
1997 if (paramType.isNull())
1998 return ExprError();
1999 refParam = paramType->isReferenceType();
2000 } else {
2001 refParam = true;
2002 }
2003 }
2004 } else if (arg.getKind() == TemplateArgument::Declaration ||
2005 arg.getKind() == TemplateArgument::NullPtr) {
2006 if (arg.getKind() == TemplateArgument::Declaration) {
2007 ValueDecl *VD = arg.getAsDecl();
2008
2009 // Find the instantiation of the template argument. This is
2010 // required for nested templates.
2011 VD = cast_or_null<ValueDecl>(
2012 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2013 if (!VD)
2014 return ExprError();
2015 }
2016
2017 QualType paramType = arg.getNonTypeTemplateArgumentType();
2018 assert(!paramType.isNull() && "type substitution failed for param type");
2019 assert(!paramType->isDependentType() && "param type still dependent");
2020 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2021 refParam = paramType->isReferenceType();
2022 } else {
2023 QualType paramType = arg.getNonTypeTemplateArgumentType();
2024 result = SemaRef.BuildExpressionFromNonTypeTemplateArgument(arg, loc);
2025 refParam = paramType->isReferenceType();
2026 assert(result.isInvalid() ||
2027 SemaRef.Context.hasSameType(result.get()->getType(),
2028 paramType.getNonReferenceType()));
2029 }
2030
2031 if (result.isInvalid())
2032 return ExprError();
2033
2034 Expr *resultExpr = result.get();
2035 // FIXME: Don't put subst node on final replacement.
2036 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
2037 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2038 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2039}
2040
2042TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2044 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2045 // We aren't expanding the parameter pack, so just return ourselves.
2046 return E;
2047 }
2048
2051 // FIXME: Don't put subst node on final replacement.
2052 return transformNonTypeTemplateParmRef(
2054 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2055}
2056
2058TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2060 ExprResult SubstReplacement = E->getReplacement();
2061 if (!isa<ConstantExpr>(SubstReplacement.get()))
2062 SubstReplacement = TransformExpr(E->getReplacement());
2063 if (SubstReplacement.isInvalid())
2064 return true;
2065 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2066 if (SubstType.isNull())
2067 return true;
2068 // The type may have been previously dependent and not now, which means we
2069 // might have to implicit cast the argument to the new type, for example:
2070 // template<auto T, decltype(T) U>
2071 // concept C = sizeof(U) == 4;
2072 // void foo() requires C<2, 'a'> { }
2073 // When normalizing foo(), we first form the normalized constraints of C:
2074 // AtomicExpr(sizeof(U) == 4,
2075 // U=SubstNonTypeTemplateParmExpr(Param=U,
2076 // Expr=DeclRef(U),
2077 // Type=decltype(T)))
2078 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2079 // produce:
2080 // AtomicExpr(sizeof(U) == 4,
2081 // U=SubstNonTypeTemplateParmExpr(Param=U,
2082 // Expr=ImpCast(
2083 // decltype(2),
2084 // SubstNTTPE(Param=U, Expr='a',
2085 // Type=char)),
2086 // Type=decltype(2)))
2087 // The call to CheckTemplateArgument here produces the ImpCast.
2088 TemplateArgument SugaredConverted, CanonicalConverted;
2089 if (SemaRef
2091 SubstReplacement.get(), SugaredConverted,
2092 CanonicalConverted, Sema::CTAK_Specified)
2093 .isInvalid())
2094 return true;
2095 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2096 E->getParameter(), E->getExprLoc(),
2097 SugaredConverted, E->getPackIndex());
2098}
2099
2100ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2101 SourceLocation Loc) {
2102 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2103 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2104}
2105
2107TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2108 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2109 // We can expand this parameter pack now.
2111 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2112 if (!VD)
2113 return ExprError();
2114 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2115 }
2116
2117 QualType T = TransformType(E->getType());
2118 if (T.isNull())
2119 return ExprError();
2120
2121 // Transform each of the parameter expansions into the corresponding
2122 // parameters in the instantiation of the function decl.
2124 Vars.reserve(E->getNumExpansions());
2125 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2126 I != End; ++I) {
2127 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2128 if (!D)
2129 return ExprError();
2130 Vars.push_back(D);
2131 }
2132
2133 auto *PackExpr =
2135 E->getParameterPackLocation(), Vars);
2136 getSema().MarkFunctionParmPackReferenced(PackExpr);
2137 return PackExpr;
2138}
2139
2141TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2142 VarDecl *PD) {
2143 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2144 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2145 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2146 assert(Found && "no instantiation for parameter pack");
2147
2148 Decl *TransformedDecl;
2149 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2150 // If this is a reference to a function parameter pack which we can
2151 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2152 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2153 QualType T = TransformType(E->getType());
2154 if (T.isNull())
2155 return ExprError();
2156 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2157 E->getExprLoc(), *Pack);
2158 getSema().MarkFunctionParmPackReferenced(PackExpr);
2159 return PackExpr;
2160 }
2161
2162 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2163 } else {
2164 TransformedDecl = Found->get<Decl*>();
2165 }
2166
2167 // We have either an unexpanded pack or a specific expansion.
2168 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2169}
2170
2172TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2173 NamedDecl *D = E->getDecl();
2174
2175 // Handle references to non-type template parameters and non-type template
2176 // parameter packs.
2177 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2178 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2179 return TransformTemplateParmRefExpr(E, NTTP);
2180
2181 // We have a non-type template parameter that isn't fully substituted;
2182 // FindInstantiatedDecl will find it in the local instantiation scope.
2183 }
2184
2185 // Handle references to function parameter packs.
2186 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2187 if (PD->isParameterPack())
2188 return TransformFunctionParmPackRefExpr(E, PD);
2189
2190 return inherited::TransformDeclRefExpr(E);
2191}
2192
2193ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2194 CXXDefaultArgExpr *E) {
2195 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2196 getDescribedFunctionTemplate() &&
2197 "Default arg expressions are never formed in dependent cases.");
2198 return SemaRef.BuildCXXDefaultArgExpr(
2199 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2200 E->getParam());
2201}
2202
2203template<typename Fn>
2204QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2206 CXXRecordDecl *ThisContext,
2207 Qualifiers ThisTypeQuals,
2208 Fn TransformExceptionSpec) {
2209 // We need a local instantiation scope for this function prototype.
2210 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2211 return inherited::TransformFunctionProtoType(
2212 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2213}
2214
2215ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2216 ParmVarDecl *OldParm, int indexAdjustment,
2217 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2218 auto NewParm = SemaRef.SubstParmVarDecl(
2219 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2220 ExpectParameterPack, EvaluateConstraints);
2221 if (NewParm && SemaRef.getLangOpts().OpenCL)
2222 SemaRef.deduceOpenCLAddressSpace(NewParm);
2223 return NewParm;
2224}
2225
2226QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2227 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2228 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2229 TemplateArgument Arg, SourceLocation NameLoc) {
2230 QualType Replacement = Arg.getAsType();
2231
2232 // If the template parameter had ObjC lifetime qualifiers,
2233 // then any such qualifiers on the replacement type are ignored.
2234 if (SuppressObjCLifetime) {
2235 Qualifiers RQs;
2236 RQs = Replacement.getQualifiers();
2237 RQs.removeObjCLifetime();
2238 Replacement =
2239 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2240 }
2241
2242 if (Final) {
2243 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2244 return Replacement;
2245 }
2246 // TODO: only do this uniquing once, at the start of instantiation.
2247 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2248 Replacement, AssociatedDecl, Index, PackIndex);
2251 NewTL.setNameLoc(NameLoc);
2252 return Result;
2253}
2254
2256TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2258 bool SuppressObjCLifetime) {
2259 const TemplateTypeParmType *T = TL.getTypePtr();
2260 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2261 // Replace the template type parameter with its corresponding
2262 // template argument.
2263
2264 // If the corresponding template argument is NULL or doesn't exist, it's
2265 // because we are performing instantiation from explicitly-specified
2266 // template arguments in a function template class, but there were some
2267 // arguments left unspecified.
2268 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2271 NewTL.setNameLoc(TL.getNameLoc());
2272 return TL.getType();
2273 }
2274
2275 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2276
2277 if (TemplateArgs.isRewrite()) {
2278 // We're rewriting the template parameter as a reference to another
2279 // template parameter.
2280 if (Arg.getKind() == TemplateArgument::Pack) {
2281 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2282 "unexpected pack arguments in template rewrite");
2283 Arg = Arg.pack_begin()->getPackExpansionPattern();
2284 }
2285 assert(Arg.getKind() == TemplateArgument::Type &&
2286 "unexpected nontype template argument kind in template rewrite");
2287 QualType NewT = Arg.getAsType();
2288 assert(isa<TemplateTypeParmType>(NewT) &&
2289 "type parm not rewritten to type parm");
2290 auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT);
2291 NewTL.setNameLoc(TL.getNameLoc());
2292 return NewT;
2293 }
2294
2295 auto [AssociatedDecl, Final] =
2296 TemplateArgs.getAssociatedDecl(T->getDepth());
2297 std::optional<unsigned> PackIndex;
2298 if (T->isParameterPack()) {
2299 assert(Arg.getKind() == TemplateArgument::Pack &&
2300 "Missing argument pack");
2301
2302 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2303 // We have the template argument pack, but we're not expanding the
2304 // enclosing pack expansion yet. Just save the template argument
2305 // pack for later substitution.
2306 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2307 AssociatedDecl, T->getIndex(), Final, Arg);
2310 NewTL.setNameLoc(TL.getNameLoc());
2311 return Result;
2312 }
2313
2314 // PackIndex starts from last element.
2315 PackIndex = getPackIndex(Arg);
2316 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2317 }
2318
2319 assert(Arg.getKind() == TemplateArgument::Type &&
2320 "Template argument kind mismatch");
2321
2322 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2323 AssociatedDecl, T->getIndex(),
2324 PackIndex, Arg, TL.getNameLoc());
2325 }
2326
2327 // The template type parameter comes from an inner template (e.g.,
2328 // the template parameter list of a member template inside the
2329 // template we are instantiating). Create a new template type
2330 // parameter with the template "level" reduced by one.
2331 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2332 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2333 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2334 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2335 QualType Result = getSema().Context.getTemplateTypeParmType(
2336 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2337 T->isParameterPack(), NewTTPDecl);
2339 NewTL.setNameLoc(TL.getNameLoc());
2340 return Result;
2341}
2342
2343QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2345 bool SuppressObjCLifetime) {
2347
2348 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2349
2350 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2351 // We aren't expanding the parameter pack, so just return ourselves.
2352 QualType Result = TL.getType();
2353 if (NewReplaced != T->getAssociatedDecl())
2354 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2355 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2358 NewTL.setNameLoc(TL.getNameLoc());
2359 return Result;
2360 }
2361
2364 return BuildSubstTemplateTypeParmType(
2365 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2366 getPackIndex(Pack), Arg, TL.getNameLoc());
2367}
2368
2371 concepts::EntityPrinter Printer) {
2372 SmallString<128> Message;
2373 SourceLocation ErrorLoc;
2374 if (Info.hasSFINAEDiagnostic()) {
2377 Info.takeSFINAEDiagnostic(PDA);
2378 PDA.second.EmitToString(S.getDiagnostics(), Message);
2379 ErrorLoc = PDA.first;
2380 } else {
2381 ErrorLoc = Info.getLocation();
2382 }
2383 char *MessageBuf = new (S.Context) char[Message.size()];
2384 std::copy(Message.begin(), Message.end(), MessageBuf);
2385 SmallString<128> Entity;
2386 llvm::raw_svector_ostream OS(Entity);
2387 Printer(OS);
2388 char *EntityBuf = new (S.Context) char[Entity.size()];
2389 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2391 StringRef(EntityBuf, Entity.size()), ErrorLoc,
2392 StringRef(MessageBuf, Message.size())};
2393}
2394
2397 EntityPrinter Printer) {
2398 SmallString<128> Entity;
2399 llvm::raw_svector_ostream OS(Entity);
2400 Printer(OS);
2401 char *EntityBuf = new (S.Context) char[Entity.size()];
2402 llvm::copy(Entity, EntityBuf);
2404 /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()),
2405 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2406}
2407
2408ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2409 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2412 SmallVectorImpl<ParmVarDecl *> &TransParams,
2414
2415 TemplateDeductionInfo Info(KWLoc);
2416 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2417 RE, Info,
2418 SourceRange{KWLoc, RBraceLoc});
2419 Sema::SFINAETrap Trap(SemaRef);
2420
2421 unsigned ErrorIdx;
2422 if (getDerived().TransformFunctionTypeParams(
2423 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2424 &TransParams, PInfos, &ErrorIdx) ||
2425 Trap.hasErrorOccurred()) {
2427 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2428 // Add a 'failed' Requirement to contain the error that caused the failure
2429 // here.
2430 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2431 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2432 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2433 TransParams, RE->getRParenLoc(),
2434 TransReqs, RBraceLoc);
2435 }
2436
2437 return ExprResult{};
2438}
2439
2441TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2442 if (!Req->isDependent() && !AlwaysRebuild())
2443 return Req;
2444 if (Req->isSubstitutionFailure()) {
2445 if (AlwaysRebuild())
2446 return RebuildTypeRequirement(
2448 return Req;
2449 }
2450
2451 Sema::SFINAETrap Trap(SemaRef);
2453 Sema::InstantiatingTemplate TypeInst(SemaRef,
2454 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2455 Req->getType()->getTypeLoc().getSourceRange());
2456 if (TypeInst.isInvalid())
2457 return nullptr;
2458 TypeSourceInfo *TransType = TransformType(Req->getType());
2459 if (!TransType || Trap.hasErrorOccurred())
2460 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2461 [&] (llvm::raw_ostream& OS) {
2462 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2463 }));
2464 return RebuildTypeRequirement(TransType);
2465}
2466
2468TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2469 if (!Req->isDependent() && !AlwaysRebuild())
2470 return Req;
2471
2472 Sema::SFINAETrap Trap(SemaRef);
2473
2474 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2475 TransExpr;
2476 if (Req->isExprSubstitutionFailure())
2477 TransExpr = Req->getExprSubstitutionDiagnostic();
2478 else {
2479 Expr *E = Req->getExpr();
2481 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2482 E->getSourceRange());
2483 if (ExprInst.isInvalid())
2484 return nullptr;
2485 ExprResult TransExprRes = TransformExpr(E);
2486 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2487 TransExprRes.get()->hasPlaceholderType())
2488 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2489 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2490 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2491 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2492 });
2493 else
2494 TransExpr = TransExprRes.get();
2495 }
2496
2497 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2498 const auto &RetReq = Req->getReturnTypeRequirement();
2499 if (RetReq.isEmpty())
2500 TransRetReq.emplace();
2501 else if (RetReq.isSubstitutionFailure())
2502 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2503 else if (RetReq.isTypeConstraint()) {
2504 TemplateParameterList *OrigTPL =
2505 RetReq.getTypeConstraintTemplateParameterList();
2506 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2507 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2508 Req, Info, OrigTPL->getSourceRange());
2509 if (TPLInst.isInvalid())
2510 return nullptr;
2511 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2512 if (!TPL)
2513 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2514 [&] (llvm::raw_ostream& OS) {
2515 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2516 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2517 }));
2518 else {
2519 TPLInst.Clear();
2520 TransRetReq.emplace(TPL);
2521 }
2522 }
2523 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2524 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2525 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2526 std::move(*TransRetReq));
2527 return RebuildExprRequirement(
2529 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2530}
2531
2533TemplateInstantiator::TransformNestedRequirement(
2535 if (!Req->isDependent() && !AlwaysRebuild())
2536 return Req;
2537 if (Req->hasInvalidConstraint()) {
2538 if (AlwaysRebuild())
2539 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2541 return Req;
2542 }
2543 Sema::InstantiatingTemplate ReqInst(SemaRef,
2544 Req->getConstraintExpr()->getBeginLoc(), Req,
2547 if (!getEvaluateConstraints()) {
2548 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2549 if (TransConstraint.isInvalid() || !TransConstraint.get())
2550 return nullptr;
2551 if (TransConstraint.get()->isInstantiationDependent())
2552 return new (SemaRef.Context)
2553 concepts::NestedRequirement(TransConstraint.get());
2554 ConstraintSatisfaction Satisfaction;
2555 return new (SemaRef.Context) concepts::NestedRequirement(
2556 SemaRef.Context, TransConstraint.get(), Satisfaction);
2557 }
2558
2559 ExprResult TransConstraint;
2560 ConstraintSatisfaction Satisfaction;
2562 {
2565 Sema::SFINAETrap Trap(SemaRef);
2566 Sema::InstantiatingTemplate ConstrInst(SemaRef,
2567 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2569 if (ConstrInst.isInvalid())
2570 return nullptr;
2572 if (!SemaRef.CheckConstraintSatisfaction(
2573 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2574 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2575 !Result.empty())
2576 TransConstraint = Result[0];
2577 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2578 "by CheckConstraintSatisfaction.");
2579 }
2580 if (TransConstraint.isUsable() &&
2581 TransConstraint.get()->isInstantiationDependent())
2582 return new (SemaRef.Context)
2583 concepts::NestedRequirement(TransConstraint.get());
2584 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2585 Satisfaction.HasSubstitutionFailure()) {
2586 SmallString<128> Entity;
2587 llvm::raw_svector_ostream OS(Entity);
2588 Req->getConstraintExpr()->printPretty(OS, nullptr,
2589 SemaRef.getPrintingPolicy());
2590 char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
2591 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2592 return new (SemaRef.Context) concepts::NestedRequirement(
2593 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
2594 }
2595 return new (SemaRef.Context) concepts::NestedRequirement(
2596 SemaRef.Context, TransConstraint.get(), Satisfaction);
2597}
2598
2599
2600/// Perform substitution on the type T with a given set of template
2601/// arguments.
2602///
2603/// This routine substitutes the given template arguments into the
2604/// type T and produces the instantiated type.
2605///
2606/// \param T the type into which the template arguments will be
2607/// substituted. If this type is not dependent, it will be returned
2608/// immediately.
2609///
2610/// \param Args the template arguments that will be
2611/// substituted for the top-level template parameters within T.
2612///
2613/// \param Loc the location in the source code where this substitution
2614/// is being performed. It will typically be the location of the
2615/// declarator (if we're instantiating the type of some declaration)
2616/// or the location of the type in the source code (if, e.g., we're
2617/// instantiating the type of a cast expression).
2618///
2619/// \param Entity the name of the entity associated with a declaration
2620/// being instantiated (if any). May be empty to indicate that there
2621/// is no such entity (if, e.g., this is a type that occurs as part of
2622/// a cast expression) or that the entity has no name (e.g., an
2623/// unnamed function parameter).
2624///
2625/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2626/// acceptable as the top level type of the result.
2627///
2628/// \returns If the instantiation succeeds, the instantiated
2629/// type. Otherwise, produces diagnostics and returns a NULL type.
2632 SourceLocation Loc,
2633 DeclarationName Entity,
2634 bool AllowDeducedTST) {
2635 assert(!CodeSynthesisContexts.empty() &&
2636 "Cannot perform an instantiation without some context on the "
2637 "instantiation stack");
2638
2641 return T;
2642
2643 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2644 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2645 : Instantiator.TransformType(T);
2646}
2647
2650 SourceLocation Loc,
2651 DeclarationName Entity) {
2652 assert(!CodeSynthesisContexts.empty() &&
2653 "Cannot perform an instantiation without some context on the "
2654 "instantiation stack");
2655
2656 if (TL.getType().isNull())
2657 return nullptr;
2658
2661 // FIXME: Make a copy of the TypeLoc data here, so that we can
2662 // return a new TypeSourceInfo. Inefficient!
2663 TypeLocBuilder TLB;
2664 TLB.pushFullCopy(TL);
2665 return TLB.getTypeSourceInfo(Context, TL.getType());
2666 }
2667
2668 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2669 TypeLocBuilder TLB;
2670 TLB.reserve(TL.getFullDataSize());
2671 QualType Result = Instantiator.TransformType(TLB, TL);
2672 if (Result.isNull())
2673 return nullptr;
2674
2675 return TLB.getTypeSourceInfo(Context, Result);
2676}
2677
2678/// Deprecated form of the above.
2680 const MultiLevelTemplateArgumentList &TemplateArgs,
2681 SourceLocation Loc, DeclarationName Entity) {
2682 assert(!CodeSynthesisContexts.empty() &&
2683 "Cannot perform an instantiation without some context on the "
2684 "instantiation stack");
2685
2686 // If T is not a dependent type or a variably-modified type, there
2687 // is nothing to do.
2689 return T;
2690
2691 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2692 return Instantiator.TransformType(T);
2693}
2694
2698 return true;
2699
2700 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2701 if (!TL.getAs<FunctionProtoTypeLoc>())
2702 return false;
2703
2705 for (ParmVarDecl *P : FP.getParams()) {
2706 // This must be synthesized from a typedef.
2707 if (!P) continue;
2708
2709 // If there are any parameters, a new TypeSourceInfo that refers to the
2710 // instantiated parameters must be built.
2711 return true;
2712 }
2713
2714 return false;
2715}
2716
2717/// A form of SubstType intended specifically for instantiating the
2718/// type of a FunctionDecl. Its purpose is solely to force the
2719/// instantiation of default-argument expressions and to avoid
2720/// instantiating an exception-specification.
2723 SourceLocation Loc,
2724 DeclarationName Entity,
2725 CXXRecordDecl *ThisContext,
2726 Qualifiers ThisTypeQuals,
2727 bool EvaluateConstraints) {
2728 assert(!CodeSynthesisContexts.empty() &&
2729 "Cannot perform an instantiation without some context on the "
2730 "instantiation stack");
2731
2733 return T;
2734
2735 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2736 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2737
2738 TypeLocBuilder TLB;
2739
2740 TypeLoc TL = T->getTypeLoc();
2741 TLB.reserve(TL.getFullDataSize());
2742
2744
2745 if (FunctionProtoTypeLoc Proto =
2747 // Instantiate the type, other than its exception specification. The
2748 // exception specification is instantiated in InitFunctionInstantiation
2749 // once we've built the FunctionDecl.
2750 // FIXME: Set the exception specification to EST_Uninstantiated here,
2751 // instead of rebuilding the function type again later.
2752 Result = Instantiator.TransformFunctionProtoType(
2753 TLB, Proto, ThisContext, ThisTypeQuals,
2755 bool &Changed) { return false; });
2756 } else {
2757 Result = Instantiator.TransformType(TLB, TL);
2758 }
2759 // When there are errors resolving types, clang may use IntTy as a fallback,
2760 // breaking our assumption that function declarations have function types.
2761 if (Result.isNull() || !Result->isFunctionType())
2762 return nullptr;
2763
2764 return TLB.getTypeSourceInfo(Context, Result);
2765}
2766
2769 SmallVectorImpl<QualType> &ExceptionStorage,
2770 const MultiLevelTemplateArgumentList &Args) {
2771 bool Changed = false;
2772 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2773 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2774 Changed);
2775}
2776
2778 const MultiLevelTemplateArgumentList &Args) {
2781
2782 SmallVector<QualType, 4> ExceptionStorage;
2784 ESI, ExceptionStorage, Args))
2785 // On error, recover by dropping the exception specification.
2786 ESI.Type = EST_None;
2787
2788 UpdateExceptionSpec(New, ESI);
2789}
2790
2791namespace {
2792
2793 struct GetContainedInventedTypeParmVisitor :
2794 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2795 TemplateTypeParmDecl *> {
2796 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2797 TemplateTypeParmDecl *>::Visit;
2798
2799 TemplateTypeParmDecl *Visit(QualType T) {
2800 if (T.isNull())
2801 return nullptr;
2802 return Visit(T.getTypePtr());
2803 }
2804 // The deduced type itself.
2805 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2806 const TemplateTypeParmType *T) {
2807 if (!T->getDecl() || !T->getDecl()->isImplicit())
2808 return nullptr;
2809 return T->getDecl();
2810 }
2811
2812 // Only these types can contain 'auto' types, and subsequently be replaced
2813 // by references to invented parameters.
2814
2815 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2816 return Visit(T->getNamedType());
2817 }
2818
2819 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2820 return Visit(T->getPointeeType());
2821 }
2822
2823 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2824 return Visit(T->getPointeeType());
2825 }
2826
2827 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2828 return Visit(T->getPointeeTypeAsWritten());
2829 }
2830
2831 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2832 return Visit(T->getPointeeType());
2833 }
2834
2835 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2836 return Visit(T->getElementType());
2837 }
2838
2839 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2840 const DependentSizedExtVectorType *T) {
2841 return Visit(T->getElementType());
2842 }
2843
2844 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2845 return Visit(T->getElementType());
2846 }
2847
2848 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2849 return VisitFunctionType(T);
2850 }
2851
2852 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2853 return Visit(T->getReturnType());
2854 }
2855
2856 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2857 return Visit(T->getInnerType());
2858 }
2859
2860 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2861 return Visit(T->getModifiedType());
2862 }
2863
2864 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2865 return Visit(T->getUnderlyingType());
2866 }
2867
2868 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2869 return Visit(T->getOriginalType());
2870 }
2871
2872 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2873 return Visit(T->getPattern());
2874 }
2875 };
2876
2877} // namespace
2878
2880 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2881 const MultiLevelTemplateArgumentList &TemplateArgs,
2882 bool EvaluateConstraints) {
2883 const ASTTemplateArgumentListInfo *TemplArgInfo =
2885
2886 if (!EvaluateConstraints) {
2889 return false;
2890 }
2891
2892 TemplateArgumentListInfo InstArgs;
2893
2894 if (TemplArgInfo) {
2895 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2896 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2897 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
2898 InstArgs))
2899 return true;
2900 }
2901 return AttachTypeConstraint(
2903 TC->getNamedConcept(), &InstArgs, Inst,
2904 Inst->isParameterPack()
2905 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2906 ->getEllipsisLoc()
2907 : SourceLocation());
2908}
2909
2911 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
2912 int indexAdjustment, std::optional<unsigned> NumExpansions,
2913 bool ExpectParameterPack, bool EvaluateConstraint) {
2914 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2915 TypeSourceInfo *NewDI = nullptr;
2916
2917 TypeLoc OldTL = OldDI->getTypeLoc();
2918 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2919
2920 // We have a function parameter pack. Substitute into the pattern of the
2921 // expansion.
2922 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2923 OldParm->getLocation(), OldParm->getDeclName());
2924 if (!NewDI)
2925 return nullptr;
2926
2927 if (NewDI->getType()->containsUnexpandedParameterPack()) {
2928 // We still have unexpanded parameter packs, which means that
2929 // our function parameter is still a function parameter pack.
2930 // Therefore, make its type a pack expansion type.
2931 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2932 NumExpansions);
2933 } else if (ExpectParameterPack) {
2934 // We expected to get a parameter pack but didn't (because the type
2935 // itself is not a pack expansion type), so complain. This can occur when
2936 // the substitution goes through an alias template that "loses" the
2937 // pack expansion.
2938 Diag(OldParm->getLocation(),
2939 diag::err_function_parameter_pack_without_parameter_packs)
2940 << NewDI->getType();
2941 return nullptr;
2942 }
2943 } else {
2944 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2945 OldParm->getDeclName());
2946 }
2947
2948 if (!NewDI)
2949 return nullptr;
2950
2951 if (NewDI->getType()->isVoidType()) {
2952 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2953 return nullptr;
2954 }
2955
2956 // In abbreviated templates, TemplateTypeParmDecls with possible
2957 // TypeConstraints are created when the parameter list is originally parsed.
2958 // The TypeConstraints can therefore reference other functions parameters in
2959 // the abbreviated function template, which is why we must instantiate them
2960 // here, when the instantiated versions of those referenced parameters are in
2961 // scope.
2962 if (TemplateTypeParmDecl *TTP =
2963 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
2964 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
2965 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
2966 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
2967 // We will first get here when instantiating the abbreviated function
2968 // template's described function, but we might also get here later.
2969 // Make sure we do not instantiate the TypeConstraint more than once.
2970 if (Inst && !Inst->getTypeConstraint()) {
2971 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
2972 return nullptr;
2973 }
2974 }
2975 }
2976
2978 OldParm->getInnerLocStart(),
2979 OldParm->getLocation(),
2980 OldParm->getIdentifier(),
2981 NewDI->getType(), NewDI,
2982 OldParm->getStorageClass());
2983 if (!NewParm)
2984 return nullptr;
2985
2986 // Mark the (new) default argument as uninstantiated (if any).
2987 if (OldParm->hasUninstantiatedDefaultArg()) {
2988 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2989 NewParm->setUninstantiatedDefaultArg(Arg);
2990 } else if (OldParm->hasUnparsedDefaultArg()) {
2991 NewParm->setUnparsedDefaultArg();
2992 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2993 } else if (Expr *Arg = OldParm->getDefaultArg()) {
2994 // Default arguments cannot be substituted until the declaration context
2995 // for the associated function or lambda capture class is available.
2996 // This is necessary for cases like the following where construction of
2997 // the lambda capture class for the outer lambda is dependent on the
2998 // parameter types but where the default argument is dependent on the
2999 // outer lambda's declaration context.
3000 // template <typename T>
3001 // auto f() {
3002 // return [](T = []{ return T{}; }()) { return 0; };
3003 // }
3004 NewParm->setUninstantiatedDefaultArg(Arg);
3005 }
3006
3010
3011 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3012 // Add the new parameter to the instantiated parameter pack.
3014 } else {
3015 // Introduce an Old -> New mapping
3017 }
3018
3019 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3020 // can be anything, is this right ?
3021 NewParm->setDeclContext(CurContext);
3022
3023 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3024 OldParm->getFunctionScopeIndex() + indexAdjustment);
3025
3026 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3027
3028 return NewParm;
3029}
3030
3031/// Substitute the given template arguments into the given set of
3032/// parameters, producing the set of parameter types that would be generated
3033/// from such a substitution.
3036 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3037 const MultiLevelTemplateArgumentList &TemplateArgs,
3038 SmallVectorImpl<QualType> &ParamTypes,
3040 ExtParameterInfoBuilder &ParamInfos) {
3041 assert(!CodeSynthesisContexts.empty() &&
3042 "Cannot perform an instantiation without some context on the "
3043 "instantiation stack");
3044
3045 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3046 DeclarationName());
3047 return Instantiator.TransformFunctionTypeParams(
3048 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3049}
3050
3051/// Substitute the given template arguments into the default argument.
3053 SourceLocation Loc,
3054 ParmVarDecl *Param,
3055 const MultiLevelTemplateArgumentList &TemplateArgs,
3056 bool ForCallExpr) {
3057 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3058 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3059
3062
3063 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3064 if (Inst.isInvalid())
3065 return true;
3066 if (Inst.isAlreadyInstantiating()) {
3067 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3068 Param->setInvalidDecl();
3069 return true;
3070 }
3071
3073 {
3074 // C++ [dcl.fct.default]p5:
3075 // The names in the [default argument] expression are bound, and
3076 // the semantic constraints are checked, at the point where the
3077 // default argument expression appears.
3078 ContextRAII SavedContext(*this, FD);
3079 std::unique_ptr<LocalInstantiationScope> LIS;
3080 MultiLevelTemplateArgumentList NewTemplateArgs = TemplateArgs;
3081
3082 if (ForCallExpr) {
3083 // When instantiating a default argument due to use in a call expression,
3084 // an instantiation scope that includes the parameters of the callee is
3085 // required to satisfy references from the default argument. For example:
3086 // template<typename T> void f(T a, int = decltype(a)());
3087 // void g() { f(0); }
3088 LIS = std::make_unique<LocalInstantiationScope>(*this);
3090 /*ForDefinition*/ false);
3091 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3092 return true;
3093 const FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
3094 if (PrimaryTemplate && PrimaryTemplate->isOutOfLine()) {
3095 TemplateArgumentList *CurrentTemplateArgumentList =
3097 TemplateArgs.getInnermost());
3098 NewTemplateArgs = getTemplateInstantiationArgs(
3099 FD, FD->getDeclContext(), /*Final=*/false,
3100 CurrentTemplateArgumentList->asArray(), /*RelativeToPrimary=*/true);
3101 }
3102 }
3103
3105 Result = SubstInitializer(PatternExpr, NewTemplateArgs,
3106 /*DirectInit*/ false);
3107 });
3108 }
3109 if (Result.isInvalid())
3110 return true;
3111
3112 if (ForCallExpr) {
3113 // Check the expression as an initializer for the parameter.
3114 InitializedEntity Entity
3117 Param->getLocation(),
3118 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3119 Expr *ResultE = Result.getAs<Expr>();
3120
3121 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3122 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3123 if (Result.isInvalid())
3124 return true;
3125
3126 Result =
3128 /*DiscardedValue*/ false);
3129 } else {
3130 // FIXME: Obtain the source location for the '=' token.
3131 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3132 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3133 }
3134 if (Result.isInvalid())
3135 return true;
3136
3137 // Remember the instantiated default argument.
3138 Param->setDefaultArg(Result.getAs<Expr>());
3139
3140 return false;
3141}
3142
3143/// Perform substitution on the base class specifiers of the
3144/// given class template specialization.
3145///
3146/// Produces a diagnostic and returns true on error, returns false and
3147/// attaches the instantiated base classes to the class template
3148/// specialization if successful.
3149bool
3151 CXXRecordDecl *Pattern,
3152 const MultiLevelTemplateArgumentList &TemplateArgs) {
3153 bool Invalid = false;
3154 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3155 for (const auto &Base : Pattern->bases()) {
3156 if (!Base.getType()->isDependentType()) {
3157 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3158 if (RD->isInvalidDecl())
3159 Instantiation->setInvalidDecl();
3160 }
3161 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3162 continue;
3163 }
3164
3165 SourceLocation EllipsisLoc;
3166 TypeSourceInfo *BaseTypeLoc;
3167 if (Base.isPackExpansion()) {
3168 // This is a pack expansion. See whether we should expand it now, or
3169 // wait until later.
3171 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3172 Unexpanded);
3173 bool ShouldExpand = false;
3174 bool RetainExpansion = false;
3175 std::optional<unsigned> NumExpansions;
3176 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3177 Base.getSourceRange(),
3178 Unexpanded,
3179 TemplateArgs, ShouldExpand,
3180 RetainExpansion,
3181 NumExpansions)) {
3182 Invalid = true;
3183 continue;
3184 }
3185
3186 // If we should expand this pack expansion now, do so.
3187 if (ShouldExpand) {
3188 for (unsigned I = 0; I != *NumExpansions; ++I) {
3189 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3190
3191 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3192 TemplateArgs,
3193 Base.getSourceRange().getBegin(),
3194 DeclarationName());
3195 if (!BaseTypeLoc) {
3196 Invalid = true;
3197 continue;
3198 }
3199
3200 if (CXXBaseSpecifier *InstantiatedBase
3201 = CheckBaseSpecifier(Instantiation,
3202 Base.getSourceRange(),
3203 Base.isVirtual(),
3204 Base.getAccessSpecifierAsWritten(),
3205 BaseTypeLoc,
3206 SourceLocation()))
3207 InstantiatedBases.push_back(InstantiatedBase);
3208 else
3209 Invalid = true;
3210 }
3211
3212 continue;
3213 }
3214
3215 // The resulting base specifier will (still) be a pack expansion.
3216 EllipsisLoc = Base.getEllipsisLoc();
3217 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3218 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3219 TemplateArgs,
3220 Base.getSourceRange().getBegin(),
3221 DeclarationName());
3222 } else {
3223 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3224 TemplateArgs,
3225 Base.getSourceRange().getBegin(),
3226 DeclarationName());
3227 }
3228
3229 if (!BaseTypeLoc) {
3230 Invalid = true;
3231 continue;
3232 }
3233
3234 if (CXXBaseSpecifier *InstantiatedBase
3235 = CheckBaseSpecifier(Instantiation,
3236 Base.getSourceRange(),
3237 Base.isVirtual(),
3238 Base.getAccessSpecifierAsWritten(),
3239 BaseTypeLoc,
3240 EllipsisLoc))
3241 InstantiatedBases.push_back(InstantiatedBase);
3242 else
3243 Invalid = true;
3244 }
3245
3246 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3247 Invalid = true;
3248
3249 return Invalid;
3250}
3251
3252// Defined via #include from SemaTemplateInstantiateDecl.cpp
3253namespace clang {
3254 namespace sema {
3256 const MultiLevelTemplateArgumentList &TemplateArgs);
3258 const Attr *At, ASTContext &C, Sema &S,
3259 const MultiLevelTemplateArgumentList &TemplateArgs);
3260 }
3261}
3262
3263/// Instantiate the definition of a class from a given pattern.
3264///
3265/// \param PointOfInstantiation The point of instantiation within the
3266/// source code.
3267///
3268/// \param Instantiation is the declaration whose definition is being
3269/// instantiated. This will be either a class template specialization
3270/// or a member class of a class template specialization.
3271///
3272/// \param Pattern is the pattern from which the instantiation
3273/// occurs. This will be either the declaration of a class template or
3274/// the declaration of a member class of a class template.
3275///
3276/// \param TemplateArgs The template arguments to be substituted into
3277/// the pattern.
3278///
3279/// \param TSK the kind of implicit or explicit instantiation to perform.
3280///
3281/// \param Complain whether to complain if the class cannot be instantiated due
3282/// to the lack of a definition.
3283///
3284/// \returns true if an error occurred, false otherwise.
3285bool
3287 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3288 const MultiLevelTemplateArgumentList &TemplateArgs,
3290 bool Complain) {
3291 CXXRecordDecl *PatternDef
3292 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3293 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3294 Instantiation->getInstantiatedFromMemberClass(),
3295 Pattern, PatternDef, TSK, Complain))
3296 return true;
3297
3298 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3299 std::string Name;
3300 llvm::raw_string_ostream OS(Name);
3301 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3302 /*Qualified=*/true);
3303 return Name;
3304 });
3305
3306 Pattern = PatternDef;
3307
3308 // Record the point of instantiation.
3309 if (MemberSpecializationInfo *MSInfo
3310 = Instantiation->getMemberSpecializationInfo()) {
3311 MSInfo->setTemplateSpecializationKind(TSK);
3312 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3313 } else if (ClassTemplateSpecializationDecl *Spec
3314 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3315 Spec->setTemplateSpecializationKind(TSK);
3316 Spec->setPointOfInstantiation(PointOfInstantiation);
3317 }
3318
3319 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3320 if (Inst.isInvalid())
3321 return true;
3322 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3323 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3324 "instantiating class definition");
3325
3326 // Enter the scope of this instantiation. We don't use
3327 // PushDeclContext because we don't have a scope.
3328 ContextRAII SavedContext(*this, Instantiation);
3331
3332 // If this is an instantiation of a local class, merge this local
3333 // instantiation scope with the enclosing scope. Otherwise, every
3334 // instantiation of a class has its own local instantiation scope.
3335 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3336 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3337
3338 // Some class state isn't processed immediately but delayed till class
3339 // instantiation completes. We may not be ready to handle any delayed state
3340 // already on the stack as it might correspond to a different class, so save
3341 // it now and put it back later.
3342 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3343
3344 // Pull attributes from the pattern onto the instantiation.
3345 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3346
3347 // Start the definition of this instantiation.
3348 Instantiation->startDefinition();
3349
3350 // The instantiation is visible here, even if it was first declared in an
3351 // unimported module.
3352 Instantiation->setVisibleDespiteOwningModule();
3353
3354 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3355 Instantiation->setTagKind(Pattern->getTagKind());
3356
3357 // Do substitution on the base class specifiers.
3358 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3359 Instantiation->setInvalidDecl();
3360
3361 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3362 Instantiator.setEvaluateConstraints(false);
3363 SmallVector<Decl*, 4> Fields;
3364 // Delay instantiation of late parsed attributes.
3365 LateInstantiatedAttrVec LateAttrs;
3366 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3367
3368 bool MightHaveConstexprVirtualFunctions = false;
3369 for (auto *Member : Pattern->decls()) {
3370 // Don't instantiate members not belonging in this semantic context.
3371 // e.g. for:
3372 // @code
3373 // template <int i> class A {
3374 // class B *g;
3375 // };
3376 // @endcode
3377 // 'class B' has the template as lexical context but semantically it is
3378 // introduced in namespace scope.
3379 if (Member->getDeclContext() != Pattern)
3380 continue;
3381
3382 // BlockDecls can appear in a default-member-initializer. They must be the
3383 // child of a BlockExpr, so we only know how to instantiate them from there.
3384 // Similarly, lambda closure types are recreated when instantiating the
3385 // corresponding LambdaExpr.
3386 if (isa<BlockDecl>(Member) ||
3387 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3388 continue;
3389
3390 if (Member->isInvalidDecl()) {
3391 Instantiation->setInvalidDecl();
3392 continue;
3393 }
3394
3395 Decl *NewMember = Instantiator.Visit(Member);
3396 if (NewMember) {
3397 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3398 Fields.push_back(Field);
3399 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3400 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3401 // specialization causes the implicit instantiation of the definitions
3402 // of unscoped member enumerations.
3403 // Record a point of instantiation for this implicit instantiation.
3404 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3405 Enum->isCompleteDefinition()) {
3406 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3407 assert(MSInfo && "no spec info for member enum specialization");
3409 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3410 }
3411 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3412 if (SA->isFailed()) {
3413 // A static_assert failed. Bail out; instantiating this
3414 // class is probably not meaningful.
3415 Instantiation->setInvalidDecl();
3416 break;
3417 }
3418 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3419 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3420 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3421 MightHaveConstexprVirtualFunctions = true;
3422 }
3423
3424 if (NewMember->isInvalidDecl())
3425 Instantiation->setInvalidDecl();
3426 } else {
3427 // FIXME: Eventually, a NULL return will mean that one of the
3428 // instantiations was a semantic disaster, and we'll want to mark the
3429 // declaration invalid.
3430 // For now, we expect to skip some members that we can't yet handle.
3431 }
3432 }
3433
3434 // Finish checking fields.
3435 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3437 CheckCompletedCXXClass(nullptr, Instantiation);
3438
3439 // Default arguments are parsed, if not instantiated. We can go instantiate
3440 // default arg exprs for default constructors if necessary now. Unless we're
3441 // parsing a class, in which case wait until that's finished.
3442 if (ParsingClassDepth == 0)
3444
3445 // Instantiate late parsed attributes, and attach them to their decls.
3446 // See Sema::InstantiateAttrs
3447 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3448 E = LateAttrs.end(); I != E; ++I) {
3449 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3450 CurrentInstantiationScope = I->Scope;
3451
3452 // Allow 'this' within late-parsed attributes.
3453 auto *ND = cast<NamedDecl>(I->NewDecl);
3454 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3455 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3456 ND->isCXXInstanceMember());
3457
3458 Attr *NewAttr =
3459 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3460 if (NewAttr)
3461 I->NewDecl->addAttr(NewAttr);
3463 Instantiator.getStartingScope());
3464 }
3465 Instantiator.disableLateAttributeInstantiation();
3466 LateAttrs.clear();
3467
3469
3470 // FIXME: We should do something similar for explicit instantiations so they
3471 // end up in the right module.
3472 if (TSK == TSK_ImplicitInstantiation) {
3473 Instantiation->setLocation(Pattern->getLocation());
3474 Instantiation->setLocStart(Pattern->getInnerLocStart());
3475 Instantiation->setBraceRange(Pattern->getBraceRange());
3476 }
3477
3478 if (!Instantiation->isInvalidDecl()) {
3479 // Perform any dependent diagnostics from the pattern.
3480 if (Pattern->isDependentContext())
3481 PerformDependentDiagnostics(Pattern, TemplateArgs);
3482
3483 // Instantiate any out-of-line class template partial
3484 // specializations now.
3486 P = Instantiator.delayed_partial_spec_begin(),
3487 PEnd = Instantiator.delayed_partial_spec_end();
3488 P != PEnd; ++P) {
3490 P->first, P->second)) {
3491 Instantiation->setInvalidDecl();
3492 break;
3493 }
3494 }
3495
3496 // Instantiate any out-of-line variable template partial
3497 // specializations now.
3499 P = Instantiator.delayed_var_partial_spec_begin(),
3500 PEnd = Instantiator.delayed_var_partial_spec_end();
3501 P != PEnd; ++P) {
3503 P->first, P->second)) {
3504 Instantiation->setInvalidDecl();
3505 break;
3506 }
3507 }
3508 }
3509
3510 // Exit the scope of this instantiation.
3511 SavedContext.pop();
3512
3513 if (!Instantiation->isInvalidDecl()) {
3514 // Always emit the vtable for an explicit instantiation definition
3515 // of a polymorphic class template specialization. Otherwise, eagerly
3516 // instantiate only constexpr virtual functions in preparation for their use
3517 // in constant evaluation.
3519 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3520 else if (MightHaveConstexprVirtualFunctions)
3521 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3522 /*ConstexprOnly*/ true);
3523 }
3524
3525 Consumer.HandleTagDeclDefinition(Instantiation);
3526
3527 return Instantiation->isInvalidDecl();
3528}
3529
3530/// Instantiate the definition of an enum from a given pattern.
3531///
3532/// \param PointOfInstantiation The point of instantiation within the
3533/// source code.
3534/// \param Instantiation is the declaration whose definition is being
3535/// instantiated. This will be a member enumeration of a class
3536/// temploid specialization, or a local enumeration within a
3537/// function temploid specialization.
3538/// \param Pattern The templated declaration from which the instantiation
3539/// occurs.
3540/// \param TemplateArgs The template arguments to be substituted into
3541/// the pattern.
3542/// \param TSK The kind of implicit or explicit instantiation to perform.
3543///
3544/// \return \c true if an error occurred, \c false otherwise.
3545bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3546 EnumDecl *Instantiation, EnumDecl *Pattern,
3547 const MultiLevelTemplateArgumentList &TemplateArgs,
3549 EnumDecl *PatternDef = Pattern->getDefinition();
3550 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3551 Instantiation->getInstantiatedFromMemberEnum(),
3552 Pattern, PatternDef, TSK,/*Complain*/true))
3553 return true;
3554 Pattern = PatternDef;
3555
3556 // Record the point of instantiation.
3557 if (MemberSpecializationInfo *MSInfo
3558 = Instantiation->getMemberSpecializationInfo()) {
3559 MSInfo->setTemplateSpecializationKind(TSK);
3560 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3561 }
3562
3563 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3564 if (Inst.isInvalid())
3565 return true;
3566 if (Inst.isAlreadyInstantiating())
3567 return false;
3568 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3569 "instantiating enum definition");
3570
3571 // The instantiation is visible here, even if it was first declared in an
3572 // unimported module.
3573 Instantiation->setVisibleDespiteOwningModule();
3574
3575 // Enter the scope of this instantiation. We don't use
3576 // PushDeclContext because we don't have a scope.
3577 ContextRAII SavedContext(*this, Instantiation);
3580
3581 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3582
3583 // Pull attributes from the pattern onto the instantiation.
3584 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3585
3586 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3587 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3588
3589 // Exit the scope of this instantiation.
3590 SavedContext.pop();
3591
3592 return Instantiation->isInvalidDecl();
3593}
3594
3595
3596/// Instantiate the definition of a field from the given pattern.
3597///
3598/// \param PointOfInstantiation The point of instantiation within the
3599/// source code.
3600/// \param Instantiation is the declaration whose definition is being
3601/// instantiated. This will be a class of a class temploid
3602/// specialization, or a local enumeration within a function temploid
3603/// specialization.
3604/// \param Pattern The templated declaration from which the instantiation
3605/// occurs.
3606/// \param TemplateArgs The template arguments to be substituted into
3607/// the pattern.
3608///
3609/// \return \c true if an error occurred, \c false otherwise.
3611 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3612 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3613 // If there is no initializer, we don't need to do anything.
3614 if (!Pattern->hasInClassInitializer())
3615 return false;
3616
3617 assert(Instantiation->getInClassInitStyle() ==
3618 Pattern->getInClassInitStyle() &&
3619 "pattern and instantiation disagree about init style");
3620
3621 // Error out if we haven't parsed the initializer of the pattern yet because
3622 // we are waiting for the closing brace of the outer class.
3623 Expr *OldInit = Pattern->getInClassInitializer();
3624 if (!OldInit) {
3625 RecordDecl *PatternRD = Pattern->getParent();
3626 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3627 Diag(PointOfInstantiation,
3628 diag::err_default_member_initializer_not_yet_parsed)
3629 << OutermostClass << Pattern;
3630 Diag(Pattern->getEndLoc(),
3631 diag::note_default_member_initializer_not_yet_parsed);
3632 Instantiation->setInvalidDecl();
3633 return true;
3634 }
3635
3636 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3637 if (Inst.isInvalid())
3638 return true;
3639 if (Inst.isAlreadyInstantiating()) {
3640 // Error out if we hit an instantiation cycle for this initializer.
3641 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3642 << Instantiation;
3643 return true;
3644 }
3645 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3646 "instantiating default member init");
3647
3648 // Enter the scope of this instantiation. We don't use PushDeclContext because
3649 // we don't have a scope.
3650 ContextRAII SavedContext(*this, Instantiation->getParent());
3653 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3654 PointOfInstantiation, Instantiation, CurContext};
3655
3656 LocalInstantiationScope Scope(*this, true);
3657
3658 // Instantiate the initializer.
3660 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3661
3662 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3663 /*CXXDirectInit=*/false);
3664 Expr *Init = NewInit.get();
3665 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3667 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3668
3669 if (auto *L = getASTMutationListener())
3670 L->DefaultMemberInitializerInstantiated(Instantiation);
3671
3672 // Return true if the in-class initializer is still missing.
3673 return !Instantiation->getInClassInitializer();
3674}
3675
3676namespace {
3677 /// A partial specialization whose template arguments have matched
3678 /// a given template-id.
3679 struct PartialSpecMatchResult {
3682 };
3683}
3684
3686 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3687 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3689 return true;
3690
3692 ClassTemplateSpec->getSpecializedTemplate()
3693 ->getPartialSpecializations(PartialSpecs);
3694 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3695 TemplateDeductionInfo Info(Loc);
3696 if (DeduceTemplateArguments(PartialSpecs[I],
3697 ClassTemplateSpec->getTemplateArgs().asArray(),
3699 return true;
3700 }
3701
3702 return false;
3703}
3704
3705/// Get the instantiation pattern to use to instantiate the definition of a
3706/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3707/// template or of a partial specialization).
3710 Sema &S, SourceLocation PointOfInstantiation,
3711 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3713 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3714 if (Inst.isInvalid())
3715 return {/*Invalid=*/true};
3716 if (Inst.isAlreadyInstantiating())
3717 return {/*Invalid=*/false};
3718
3719 llvm::PointerUnion<ClassTemplateDecl *,
3721 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3722 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3723 // Find best matching specialization.
3724 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3725
3726 // C++ [temp.class.spec.match]p1:
3727 // When a class template is used in a context that requires an
3728 // instantiation of the class, it is necessary to determine
3729 // whether the instantiation is to be generated using the primary
3730 // template or one of the partial specializations. This is done by
3731 // matching the template arguments of the class template
3732 // specialization with the template argument lists of the partial
3733 // specializations.
3734 typedef PartialSpecMatchResult MatchResult;
3737 Template->getPartialSpecializations(PartialSpecs);
3738 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3739 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3740 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3741 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3743 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3745 // Store the failed-deduction information for use in diagnostics, later.
3746 // TODO: Actually use the failed-deduction info?
3747 FailedCandidates.addCandidate().set(
3748 DeclAccessPair::make(Template, AS_public), Partial,
3750 (void)Result;
3751 } else {
3752 Matched.push_back(PartialSpecMatchResult());
3753 Matched.back().Partial = Partial;
3754 Matched.back().Args = Info.takeCanonical();
3755 }
3756 }
3757
3758 // If we're dealing with a member template where the template parameters
3759 // have been instantiated, this provides the original template parameters
3760 // from which the member template's parameters were instantiated.
3761
3762 if (Matched.size() >= 1) {
3763 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3764 if (Matched.size() == 1) {
3765 // -- If exactly one matching specialization is found, the
3766 // instantiation is generated from that specialization.
3767 // We don't need to do anything for this.
3768 } else {
3769 // -- If more than one matching specialization is found, the
3770 // partial order rules (14.5.4.2) are used to determine
3771 // whether one of the specializations is more specialized
3772 // than the others. If none of the specializations is more
3773 // specialized than all of the other matching
3774 // specializations, then the use of the class template is
3775 // ambiguous and the program is ill-formed.
3777 PEnd = Matched.end();
3778 P != PEnd; ++P) {
3780 P->Partial, Best->Partial, PointOfInstantiation) ==
3781 P->Partial)
3782 Best = P;
3783 }
3784
3785 // Determine if the best partial specialization is more specialized than
3786 // the others.
3787 bool Ambiguous = false;
3788 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3789 PEnd = Matched.end();
3790 P != PEnd; ++P) {
3792 P->Partial, Best->Partial,
3793 PointOfInstantiation) != Best->Partial) {
3794 Ambiguous = true;
3795 break;
3796 }
3797 }
3798
3799 if (Ambiguous) {
3800 // Partial ordering did not produce a clear winner. Complain.
3801 Inst.Clear();
3802 ClassTemplateSpec->setInvalidDecl();
3803 S.Diag(PointOfInstantiation,
3804 diag::err_partial_spec_ordering_ambiguous)
3805 << ClassTemplateSpec;
3806
3807 // Print the matching partial specializations.
3808 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3809 PEnd = Matched.end();
3810 P != PEnd; ++P)
3811 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3813 P->Partial->getTemplateParameters(), *P->Args);
3814
3815 return {/*Invalid=*/true};
3816 }
3817 }
3818
3819 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3820 } else {
3821 // -- If no matches are found, the instantiation is generated
3822 // from the primary template.
3823 }
3824 }
3825
3826 CXXRecordDecl *Pattern = nullptr;
3827 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3828 if (auto *PartialSpec =
3829 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3830 // Instantiate using the best class template partial specialization.
3831 while (PartialSpec->getInstantiatedFromMember()) {
3832 // If we've found an explicit specialization of this class template,
3833 // stop here and use that as the pattern.
3834 if (PartialSpec->isMemberSpecialization())
3835 break;
3836
3837 PartialSpec = PartialSpec->getInstantiatedFromMember();
3838 }
3839 Pattern = PartialSpec;
3840 } else {
3841 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3842 while (Template->getInstantiatedFromMemberTemplate()) {
3843 // If we've found an explicit specialization of this class template,
3844 // stop here and use that as the pattern.
3845 if (Template->isMemberSpecialization())
3846 break;
3847
3848 Template = Template->getInstantiatedFromMemberTemplate();
3849 }
3850 Pattern = Template->getTemplatedDecl();
3851 }
3852
3853 return Pattern;
3854}
3855
3857 SourceLocation PointOfInstantiation,
3858 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3859 TemplateSpecializationKind TSK, bool Complain) {
3860 // Perform the actual instantiation on the canonical declaration.
3861 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3862 ClassTemplateSpec->getCanonicalDecl());
3863 if (ClassTemplateSpec->isInvalidDecl())
3864 return true;
3865
3867 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3868 ClassTemplateSpec, TSK);
3869 if (!Pattern.isUsable())
3870 return Pattern.isInvalid();
3871
3872 return InstantiateClass(
3873 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3874 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3875}
3876
3877/// Instantiates the definitions of all of the member
3878/// of the given class, which is an instantiation of a class template
3879/// or a member class of a template.
3880void
3882 CXXRecordDecl *Instantiation,
3883 const MultiLevelTemplateArgumentList &TemplateArgs,
3885 // FIXME: We need to notify the ASTMutationListener that we did all of these
3886 // things, in case we have an explicit instantiation definition in a PCM, a
3887 // module, or preamble, and the declaration is in an imported AST.
3888 assert(
3891 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3892 "Unexpected template specialization kind!");
3893 for (auto *D : Instantiation->decls()) {
3894 bool SuppressNew = false;
3895 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3896 if (FunctionDecl *Pattern =
3897 Function->getInstantiatedFromMemberFunction()) {
3898
3899 if (Function->isIneligibleOrNotSelected())
3900 continue;
3901
3902 if (Function->getTrailingRequiresClause()) {
3903 ConstraintSatisfaction Satisfaction;
3904 if (CheckFunctionConstraints(Function, Satisfaction) ||
3905 !Satisfaction.IsSatisfied) {
3906 continue;
3907 }
3908 }
3909
3910 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3911 continue;
3912
3913 MemberSpecializationInfo *MSInfo =
3914 Function->getMemberSpecializationInfo();
3915 assert(MSInfo && "No member specialization information?");
3916 if (MSInfo->getTemplateSpecializationKind()
3918 continue;
3919
3920 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3921 Function,
3923 MSInfo->getPointOfInstantiation(),
3924 SuppressNew) ||
3925 SuppressNew)
3926 continue;
3927
3928 // C++11 [temp.explicit]p8:
3929 // An explicit instantiation definition that names a class template
3930 // specialization explicitly instantiates the class template
3931 // specialization and is only an explicit instantiation definition
3932 // of members whose definition is visible at the point of
3933 // instantiation.
3934 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
3935 continue;
3936
3937 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3938
3939 if (Function->isDefined()) {
3940 // Let the ASTConsumer know that this function has been explicitly
3941 // instantiated now, and its linkage might have changed.
3943 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3944 InstantiateFunctionDefinition(PointOfInstantiation, Function);
3945 } else if (TSK == TSK_ImplicitInstantiation) {
3947 std::make_pair(Function, PointOfInstantiation));
3948 }
3949 }
3950 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
3951 if (isa<VarTemplateSpecializationDecl>(Var))
3952 continue;
3953
3954 if (Var->isStaticDataMember()) {
3955 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3956 continue;
3957
3959 assert(MSInfo && "No member specialization information?");
3960 if (MSInfo->getTemplateSpecializationKind()
3962 continue;
3963
3964 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3965 Var,
3967 MSInfo->getPointOfInstantiation(),
3968 SuppressNew) ||
3969 SuppressNew)
3970 continue;
3971
3973 // C++0x [temp.explicit]p8:
3974 // An explicit instantiation definition that names a class template
3975 // specialization explicitly instantiates the class template
3976 // specialization and is only an explicit instantiation definition
3977 // of members whose definition is visible at the point of
3978 // instantiation.
3980 continue;
3981
3982 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3983 InstantiateVariableDefinition(PointOfInstantiation, Var);
3984 } else {
3985 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3986 }
3987 }
3988 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3989 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3990 continue;
3991
3992 // Always skip the injected-class-name, along with any
3993 // redeclarations of nested classes, since both would cause us
3994 // to try to instantiate the members of a class twice.
3995 // Skip closure types; they'll get instantiated when we instantiate
3996 // the corresponding lambda-expression.
3997 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
3998 Record->isLambda())
3999 continue;
4000
4001 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4002 assert(MSInfo && "No member specialization information?");
4003
4004 if (MSInfo->getTemplateSpecializationKind()
4006 continue;
4007
4008 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4010 // On Windows, explicit instantiation decl of the outer class doesn't
4011 // affect the inner class. Typically extern template declarations are
4012 // used in combination with dll import/export annotations, but those
4013 // are not propagated from the outer class templates to inner classes.
4014 // Therefore, do not instantiate inner classes on this platform, so
4015 // that users don't end up with undefined symbols during linking.
4016 continue;
4017 }
4018
4019 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4020 Record,
4022 MSInfo->getPointOfInstantiation(),
4023 SuppressNew) ||
4024 SuppressNew)
4025 continue;
4026
4027 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4028 assert(Pattern && "Missing instantiated-from-template information");
4029
4030 if (!Record->getDefinition()) {
4031 if (!Pattern->getDefinition()) {
4032 // C++0x [temp.explicit]p8:
4033 // An explicit instantiation definition that names a class template
4034 // specialization explicitly instantiates the class template
4035 // specialization and is only an explicit instantiation definition
4036 // of members whose definition is visible at the point of
4037 // instantiation.
4039 MSInfo->setTemplateSpecializationKind(TSK);
4040 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4041 }
4042
4043 continue;
4044 }
4045
4046 InstantiateClass(PointOfInstantiation, Record, Pattern,
4047 TemplateArgs,
4048 TSK);
4049 } else {
4051 Record->getTemplateSpecializationKind() ==
4053 Record->setTemplateSpecializationKind(TSK);
4054 MarkVTableUsed(PointOfInstantiation, Record, true);
4055 }
4056 }
4057
4058 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4059 if (Pattern)
4060 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4061 TSK);
4062 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4063 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4064 assert(MSInfo && "No member specialization information?");
4065
4066 if (MSInfo->getTemplateSpecializationKind()
4068 continue;
4069
4071 PointOfInstantiation, TSK, Enum,
4073 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4074 SuppressNew)
4075 continue;
4076
4077 if (Enum->getDefinition())
4078 continue;
4079
4080 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4081 assert(Pattern && "Missing instantiated-from-template information");
4082
4084 if (!Pattern->getDefinition())
4085 continue;
4086
4087 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4088 } else {
4089 MSInfo->setTemplateSpecializationKind(TSK);
4090 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4091 }
4092 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4093 // No need to instantiate in-class initializers during explicit
4094 // instantiation.
4095 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4096 CXXRecordDecl *ClassPattern =
4097 Instantiation->getTemplateInstantiationPattern();
4099 ClassPattern->lookup(Field->getDeclName());
4100 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4101 assert(Pattern);
4102 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4103 TemplateArgs);
4104 }
4105 }
4106 }
4107}
4108
4109/// Instantiate the definitions of all of the members of the
4110/// given class template specialization, which was named as part of an
4111/// explicit instantiation.
4112void
4114 SourceLocation PointOfInstantiation,
4115 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4117 // C++0x [temp.explicit]p7:
4118 // An explicit instantiation that names a class template
4119 // specialization is an explicit instantion of the same kind
4120 // (declaration or definition) of each of its members (not
4121 // including members inherited from base classes) that has not
4122 // been previously explicitly specialized in the translation unit
4123 // containing the explicit instantiation, except as described
4124 // below.
4125 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4126 getTemplateInstantiationArgs(ClassTemplateSpec),
4127 TSK);
4128}
4129
4132 if (!S)
4133 return S;
4134
4135 TemplateInstantiator Instantiator(*this, TemplateArgs,
4137 DeclarationName());
4138 return Instantiator.TransformStmt(S);
4139}
4140
4143 const MultiLevelTemplateArgumentList &TemplateArgs,
4145 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4146 DeclarationName());
4147 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4148}
4149
4152 if (!E)
4153 return E;
4154
4155 TemplateInstantiator Instantiator(*this, TemplateArgs,
4157 DeclarationName());
4158 return Instantiator.TransformExpr(E);
4159}
4160
4163 const MultiLevelTemplateArgumentList &TemplateArgs) {
4164 // FIXME: should call SubstExpr directly if this function is equivalent or
4165 // should it be different?
4166 return SubstExpr(E, TemplateArgs);
4167}
4168
4170 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4171 if (!E)
4172 return E;
4173
4174 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4175 DeclarationName());
4176 Instantiator.setEvaluateConstraints(false);
4177 return Instantiator.TransformExpr(E);
4178}
4179
4181 const MultiLevelTemplateArgumentList &TemplateArgs,
4182 bool CXXDirectInit) {
4183 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4184 DeclarationName());
4185 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4186}
4187
4188bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4189 const MultiLevelTemplateArgumentList &TemplateArgs,
4190 SmallVectorImpl<Expr *> &Outputs) {
4191 if (Exprs.empty())
4192 return false;
4193
4194 TemplateInstantiator Instantiator(*this, TemplateArgs,
4196 DeclarationName());
4197 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4198 IsCall, Outputs);
4199}
4200
4203 const MultiLevelTemplateArgumentList &TemplateArgs) {
4204 if (!NNS)
4205 return NestedNameSpecifierLoc();
4206
4207 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4208 DeclarationName());
4209 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4210}
4211
4212/// Do template substitution on declaration name info.
4215 const MultiLevelTemplateArgumentList &TemplateArgs) {
4216 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4217 NameInfo.getName());
4218 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4219}
4220
4223 TemplateName Name, SourceLocation Loc,
4224 const MultiLevelTemplateArgumentList &TemplateArgs) {
4225 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4226 DeclarationName());
4227 CXXScopeSpec SS;
4228 SS.Adopt(QualifierLoc);
4229 return Instantiator.TransformTemplateName(SS, Name, Loc);
4230}
4231
4232static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4233 // When storing ParmVarDecls in the local instantiation scope, we always
4234 // want to use the ParmVarDecl from the canonical function declaration,
4235 // since the map is then valid for any redeclaration or definition of that
4236 // function.
4237 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4238 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4239 unsigned i = PV->getFunctionScopeIndex();
4240 // This parameter might be from a freestanding function type within the
4241 // function and isn't necessarily referring to one of FD's parameters.
4242 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4243 return FD->getCanonicalDecl()->getParamDecl(i);
4244 }
4245 }
4246 return D;
4247}
4248
4249
4250llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4253 for (LocalInstantiationScope *Current = this; Current;
4254 Current = Current->Outer) {
4255
4256 // Check if we found something within this scope.
4257 const Decl *CheckD = D;
4258 do {
4259 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4260 if (Found != Current->LocalDecls.end())
4261 return &Found->second;
4262
4263 // If this is a tag declaration, it's possible that we need to look for
4264 // a previous declaration.
4265 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4266 CheckD = Tag->getPreviousDecl();
4267 else
4268 CheckD = nullptr;
4269 } while (CheckD);
4270
4271 // If we aren't combined with our outer scope, we're done.
4272 if (!Current->CombineWithOuterScope)
4273 break;
4274 }
4275
4276 // If we're performing a partial substitution during template argument
4277 // deduction, we may not have values for template parameters yet.
4278 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4279 isa<TemplateTemplateParmDecl>(D))
4280 return nullptr;
4281
4282 // Local types referenced prior to definition may require instantiation.
4283 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4284 if (RD->isLocalClass())
4285 return nullptr;
4286
4287 // Enumeration types referenced prior to definition may appear as a result of
4288 // error recovery.
4289 if (isa<EnumDecl>(D))
4290 return nullptr;
4291
4292 // Materialized typedefs/type alias for implicit deduction guides may require
4293 // instantiation.
4294 if (isa<TypedefNameDecl>(D) &&
4295 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4296 return nullptr;
4297
4298 // If we didn't find the decl, then we either have a sema bug, or we have a
4299 // forward reference to a label declaration. Return null to indicate that
4300 // we have an uninstantiated label.
4301 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4302 return nullptr;
4303}
4304
4307 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4308 if (Stored.isNull()) {
4309#ifndef NDEBUG
4310 // It should not be present in any surrounding scope either.
4311 LocalInstantiationScope *Current = this;
4312 while (Current->CombineWithOuterScope && Current->Outer) {
4313 Current = Current->Outer;
4314 assert(!Current->LocalDecls.contains(D) &&
4315 "Instantiated local in inner and outer scopes");
4316 }
4317#endif
4318 Stored = Inst;
4319 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4320 Pack->push_back(cast<VarDecl>(Inst));
4321 } else {
4322 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
4323 }
4324}
4325
4327 VarDecl *Inst) {
4329 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4330 Pack->push_back(Inst);
4331}
4332
4334#ifndef NDEBUG
4335 // This should be the first time we've been told about this decl.
4336 for (LocalInstantiationScope *Current = this;
4337 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4338 assert(!Current->LocalDecls.contains(D) &&
4339 "Creating local pack after instantiation of local");
4340#endif
4341
4343 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4345 Stored = Pack;
4346 ArgumentPacks.push_back(Pack);
4347}
4348
4350 for (DeclArgumentPack *Pack : ArgumentPacks)
4351 if (llvm::is_contained(*Pack, D))
4352 return true;
4353 return false;
4354}
4355
4357 const TemplateArgument *ExplicitArgs,
4358 unsigned NumExplicitArgs) {
4359 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4360 "Already have a partially-substituted pack");
4361 assert((!PartiallySubstitutedPack
4362 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4363 "Wrong number of arguments in partially-substituted pack");
4364 PartiallySubstitutedPack = Pack;
4365 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4366 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4367}
4368
4370 const TemplateArgument **ExplicitArgs,
4371 unsigned *NumExplicitArgs) const {
4372 if (ExplicitArgs)
4373 *ExplicitArgs = nullptr;
4374 if (NumExplicitArgs)
4375 *NumExplicitArgs = 0;
4376
4377 for (const LocalInstantiationScope *Current = this; Current;
4378 Current = Current->Outer) {
4379 if (Current->PartiallySubstitutedPack) {
4380 if (ExplicitArgs)
4381 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4382 if (NumExplicitArgs)
4383 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4384
4385 return Current->PartiallySubstitutedPack;
4386 }
4387
4388 if (!Current->CombineWithOuterScope)
4389 break;
4390 }
4391
4392 return nullptr;
4393}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the C++ template declaration subclasses.
Defines Expressions and AST nodes for C++2a concepts.
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &, QualType)
Definition: InterpFrame.cpp:96
Defines the clang::LangOptions interface.
MatchFinder::MatchResult MatchResult
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, concepts::EntityPrinter Printer)
static ActionResult< CXXRecordDecl * > getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...
static std::string convertCallArgsToString(Sema &S, llvm::ArrayRef< const Expr * > Args)
static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg)
Defines utilities for dealing with stack allocation and stack space.
C Language Family Type Representation.
__device__ int
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:72
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1068
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2565
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1575
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2141
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:692
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:752
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:2926
QualType getOriginalType() const
Definition: Type.h:2939
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3146
QualType getElementType() const
Definition: Type.h:3158
Attr - This represents one attribute.
Definition: Attr.h:42
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:5146
QualType getModifiedType() const
Definition: Type.h:5168
Pointer to a block type.
Definition: Type.h:2977
QualType getPointeeType() const
Definition: Type.h:2989
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1254
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition: ExprCXX.h:1328
const ParmVarDecl * getParam() const
Definition: ExprCXX.h:1296
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
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:1682
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1547
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:1873
base_class_range bases()
Definition: DeclCXX.h:618
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1021
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1927
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1902
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1894
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1880
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1913
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
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...
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isFileContext() const
Definition: DeclBase.h:2136
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1260
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1779
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1941
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2321
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1247
ValueDecl * getDecl()
Definition: Expr.h:1315
SourceLocation getLocation() const
Definition: Expr.h:1323
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:598
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isFileContextDecl() const
Definition: DeclBase.cpp:408
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1003
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1143
bool isInvalidDecl() const
Definition: DeclBase.h:593
SourceLocation getLocation() const
Definition: DeclBase.h:444
void setLocation(SourceLocation L)
Definition: DeclBase.h:445
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:939
DeclContext * getDeclContext()
Definition: DeclBase.h:453
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:582
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
The name of a declaration.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:828
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:813
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2047
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1899
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3441
QualType getElementType() const
Definition: Type.h:3456
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:850
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:631
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:5913
QualType getNamedType() const
Retrieve the type named by the qualified-id.
Definition: Type.h:5951
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3832
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4091
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For an enumeration member that was instantiated from a member enumeration of a templated class,...
Definition: Decl.cpp:4869
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4895
EnumDecl * getDefinition() const
Definition: Decl.h:3935
This represents one expression.
Definition: Expr.h:110
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:431
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:186
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:271
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:215
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:266
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:503
Represents a member of a struct/union/class.
Definition: Decl.h:3025
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4527
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3186
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3180
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3238
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
Represents a function declaration or definition.
Definition: Decl.h:1959
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2651
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:4068
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4117
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2407
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2288
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4599
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4626
iterator end() const
Definition: ExprCXX.h:4635
VarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:4641
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4633
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:4638
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4629
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl * > Params)
Definition: ExprCXX.cpp:1748
iterator begin() const
Definition: ExprCXX.h:4634
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4198
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4442
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1465
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:3824
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3798
QualType getReturnType() const
Definition: Type.h:4115
One of these records is kept for each identifier that is lexed.
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
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 the sequence of initializations required to initialize a given object or reference with a s...
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:1938
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
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.
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all outer scopes, down to the given outermost scope.
Definition: Template.h:498
void InstantiatedLocal(const Decl *D, Decl *Inst)
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:4784
QualType getUnderlyingType() const
Definition: Type.h:4800
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3088
QualType getPointeeType() const
Definition: Type.h:3104
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:616
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:647
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:638
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:656
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:661
Describes a module or submodule.
Definition: Module.h:105
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:265
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:197
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:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
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:1826
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1675
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>::".
bool isInstantiationDependent() const
Whether this nested name specifier involves a template parameter.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Represents a pack expansion of types.
Definition: Type.h:6111
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:6132
Sugar for parentheses used when specifying types.
Definition: Type.h:2871
QualType getInnerType() const
Definition: Type.h:2880
Represents a parameter to a function.
Definition: Decl.h:1749
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1809
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2970
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1845
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1890
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1878
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2995
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1782
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1882
bool hasInheritedDefaultArg() const
Definition: Decl.h:1894
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition: Decl.h:1841
Expr * getDefaultArg()
Definition: Decl.cpp:2958
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3000
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1799
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1898
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2897
QualType getPointeeType() const
Definition: Type.h:2907
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1962
PredefinedIdentKind getIdentKind() const
Definition: Expr.h:1997
SourceLocation getLocation() const
Definition: Expr.h:2003
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:737
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3401
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:948
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:804
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6901
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6941
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7101
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6994
The collection of all-type qualifiers we support.
Definition: Type.h:147
void removeObjCLifetime()
Definition: Type.h:358
Represents a struct/union/class.
Definition: Decl.h:4133
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5091
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:861
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3008
QualType getPointeeTypeAsWritten() const
Definition: Type.h:3024
Represents the body of a requires-expression.
Definition: DeclCXX.h:2023
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:510
SourceLocation getLParenLoc() const
Definition: ExprConcepts.h:578
SourceLocation getRParenLoc() const
Definition: ExprConcepts.h:579
RequiresExprBodyDecl * getBody() const
Definition: ExprConcepts.h:554
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:9765
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6913
A RAII object to temporarily push a declaration context.
Definition: Sema.h:1101
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:3573
DefaultedComparisonKind asComparison() const
Definition: Sema.h:3596
CXXSpecialMember asSpecialMember() const
Definition: Sema.h:3595
A helper class for building up ExtParameterInfos.
Definition: Sema.h:10310
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:10126
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:425
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:9694
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:10184
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, std::optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, std::optional< unsigned > NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
void ActOnFinishCXXNonNestedClass()
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:9710
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1924
void ActOnFinishDelayedMemberInitializers(Decl *Record)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
<