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