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