xref: /llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (revision abc8812df02599fc413d9ed77b992f8236ed2af9)
1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations.
9 //
10 //===----------------------------------------------------------------------===/
11 
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/DependentDiagnostic.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/PrettyDeclStackTrace.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/EnterExpressionEvaluationContext.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/ScopeInfo.h"
29 #include "clang/Sema/SemaAMDGPU.h"
30 #include "clang/Sema/SemaCUDA.h"
31 #include "clang/Sema/SemaHLSL.h"
32 #include "clang/Sema/SemaObjC.h"
33 #include "clang/Sema/SemaOpenMP.h"
34 #include "clang/Sema/SemaSwift.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateInstCallback.h"
37 #include "llvm/Support/TimeProfiler.h"
38 #include <optional>
39 
40 using namespace clang;
41 
42 static bool isDeclWithinFunction(const Decl *D) {
43   const DeclContext *DC = D->getDeclContext();
44   if (DC->isFunctionOrMethod())
45     return true;
46 
47   if (DC->isRecord())
48     return cast<CXXRecordDecl>(DC)->isLocalClass();
49 
50   return false;
51 }
52 
53 template<typename DeclT>
54 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
55                            const MultiLevelTemplateArgumentList &TemplateArgs) {
56   if (!OldDecl->getQualifierLoc())
57     return false;
58 
59   assert((NewDecl->getFriendObjectKind() ||
60           !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
61          "non-friend with qualified name defined in dependent context");
62   Sema::ContextRAII SavedContext(
63       SemaRef,
64       const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
65                                     ? NewDecl->getLexicalDeclContext()
66                                     : OldDecl->getLexicalDeclContext()));
67 
68   NestedNameSpecifierLoc NewQualifierLoc
69       = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
70                                             TemplateArgs);
71 
72   if (!NewQualifierLoc)
73     return true;
74 
75   NewDecl->setQualifierInfo(NewQualifierLoc);
76   return false;
77 }
78 
79 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
80                                               DeclaratorDecl *NewDecl) {
81   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
82 }
83 
84 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
85                                               TagDecl *NewDecl) {
86   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
87 }
88 
89 // Include attribute instantiation code.
90 #include "clang/Sema/AttrTemplateInstantiate.inc"
91 
92 static void instantiateDependentAlignedAttr(
93     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
94     const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
95   if (Aligned->isAlignmentExpr()) {
96     // The alignment expression is a constant expression.
97     EnterExpressionEvaluationContext Unevaluated(
98         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
99     ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
100     if (!Result.isInvalid())
101       S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
102   } else {
103     if (TypeSourceInfo *Result =
104             S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
105                         Aligned->getLocation(), DeclarationName())) {
106       if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
107                                       Aligned->getLocation(),
108                                       Result->getTypeLoc().getSourceRange()))
109         S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
110     }
111   }
112 }
113 
114 static void instantiateDependentAlignedAttr(
115     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
116     const AlignedAttr *Aligned, Decl *New) {
117   if (!Aligned->isPackExpansion()) {
118     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
119     return;
120   }
121 
122   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
123   if (Aligned->isAlignmentExpr())
124     S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
125                                       Unexpanded);
126   else
127     S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
128                                       Unexpanded);
129   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
130 
131   // Determine whether we can expand this attribute pack yet.
132   bool Expand = true, RetainExpansion = false;
133   std::optional<unsigned> NumExpansions;
134   // FIXME: Use the actual location of the ellipsis.
135   SourceLocation EllipsisLoc = Aligned->getLocation();
136   if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
137                                         Unexpanded, TemplateArgs, Expand,
138                                         RetainExpansion, NumExpansions))
139     return;
140 
141   if (!Expand) {
142     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
143     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
144   } else {
145     for (unsigned I = 0; I != *NumExpansions; ++I) {
146       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
147       instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
148     }
149   }
150 }
151 
152 static void instantiateDependentAssumeAlignedAttr(
153     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
154     const AssumeAlignedAttr *Aligned, Decl *New) {
155   // The alignment expression is a constant expression.
156   EnterExpressionEvaluationContext Unevaluated(
157       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
158 
159   Expr *E, *OE = nullptr;
160   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
161   if (Result.isInvalid())
162     return;
163   E = Result.getAs<Expr>();
164 
165   if (Aligned->getOffset()) {
166     Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
167     if (Result.isInvalid())
168       return;
169     OE = Result.getAs<Expr>();
170   }
171 
172   S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
173 }
174 
175 static void instantiateDependentAlignValueAttr(
176     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177     const AlignValueAttr *Aligned, Decl *New) {
178   // The alignment expression is a constant expression.
179   EnterExpressionEvaluationContext Unevaluated(
180       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
181   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
182   if (!Result.isInvalid())
183     S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
184 }
185 
186 static void instantiateDependentAllocAlignAttr(
187     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188     const AllocAlignAttr *Align, Decl *New) {
189   Expr *Param = IntegerLiteral::Create(
190       S.getASTContext(),
191       llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
192       S.getASTContext().UnsignedLongLongTy, Align->getLocation());
193   S.AddAllocAlignAttr(New, *Align, Param);
194 }
195 
196 static void instantiateDependentAnnotationAttr(
197     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
198     const AnnotateAttr *Attr, Decl *New) {
199   EnterExpressionEvaluationContext Unevaluated(
200       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
201 
202   // If the attribute has delayed arguments it will have to instantiate those
203   // and handle them as new arguments for the attribute.
204   bool HasDelayedArgs = Attr->delayedArgs_size();
205 
206   ArrayRef<Expr *> ArgsToInstantiate =
207       HasDelayedArgs
208           ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
209           : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
210 
211   SmallVector<Expr *, 4> Args;
212   if (S.SubstExprs(ArgsToInstantiate,
213                    /*IsCall=*/false, TemplateArgs, Args))
214     return;
215 
216   StringRef Str = Attr->getAnnotation();
217   if (HasDelayedArgs) {
218     if (Args.size() < 1) {
219       S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
220           << Attr << 1;
221       return;
222     }
223 
224     if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
225       return;
226 
227     llvm::SmallVector<Expr *, 4> ActualArgs;
228     ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
229     std::swap(Args, ActualArgs);
230   }
231   auto *AA = S.CreateAnnotationAttr(*Attr, Str, Args);
232   if (AA) {
233     New->addAttr(AA);
234   }
235 }
236 
237 static Expr *instantiateDependentFunctionAttrCondition(
238     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
239     const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
240   Expr *Cond = nullptr;
241   {
242     Sema::ContextRAII SwitchContext(S, New);
243     EnterExpressionEvaluationContext Unevaluated(
244         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
245     ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
246     if (Result.isInvalid())
247       return nullptr;
248     Cond = Result.getAs<Expr>();
249   }
250   if (!Cond->isTypeDependent()) {
251     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
252     if (Converted.isInvalid())
253       return nullptr;
254     Cond = Converted.get();
255   }
256 
257   SmallVector<PartialDiagnosticAt, 8> Diags;
258   if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
259       !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
260     S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
261     for (const auto &P : Diags)
262       S.Diag(P.first, P.second);
263     return nullptr;
264   }
265   return Cond;
266 }
267 
268 static void instantiateDependentEnableIfAttr(
269     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
270     const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
271   Expr *Cond = instantiateDependentFunctionAttrCondition(
272       S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
273 
274   if (Cond)
275     New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
276                                                       Cond, EIA->getMessage()));
277 }
278 
279 static void instantiateDependentDiagnoseIfAttr(
280     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
281     const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
282   Expr *Cond = instantiateDependentFunctionAttrCondition(
283       S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
284 
285   if (Cond)
286     New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
287         S.getASTContext(), *DIA, Cond, DIA->getMessage(),
288         DIA->getDefaultSeverity(), DIA->getWarningGroup(),
289         DIA->getArgDependent(), New));
290 }
291 
292 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
293 // template A as the base and arguments from TemplateArgs.
294 static void instantiateDependentCUDALaunchBoundsAttr(
295     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
296     const CUDALaunchBoundsAttr &Attr, Decl *New) {
297   // The alignment expression is a constant expression.
298   EnterExpressionEvaluationContext Unevaluated(
299       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
300 
301   ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
302   if (Result.isInvalid())
303     return;
304   Expr *MaxThreads = Result.getAs<Expr>();
305 
306   Expr *MinBlocks = nullptr;
307   if (Attr.getMinBlocks()) {
308     Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
309     if (Result.isInvalid())
310       return;
311     MinBlocks = Result.getAs<Expr>();
312   }
313 
314   Expr *MaxBlocks = nullptr;
315   if (Attr.getMaxBlocks()) {
316     Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
317     if (Result.isInvalid())
318       return;
319     MaxBlocks = Result.getAs<Expr>();
320   }
321 
322   S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
323 }
324 
325 static void
326 instantiateDependentModeAttr(Sema &S,
327                              const MultiLevelTemplateArgumentList &TemplateArgs,
328                              const ModeAttr &Attr, Decl *New) {
329   S.AddModeAttr(New, Attr, Attr.getMode(),
330                 /*InInstantiation=*/true);
331 }
332 
333 /// Instantiation of 'declare simd' attribute and its arguments.
334 static void instantiateOMPDeclareSimdDeclAttr(
335     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
336     const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
337   // Allow 'this' in clauses with varlist.
338   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
339     New = FTD->getTemplatedDecl();
340   auto *FD = cast<FunctionDecl>(New);
341   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
342   SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
343   SmallVector<unsigned, 4> LinModifiers;
344 
345   auto SubstExpr = [&](Expr *E) -> ExprResult {
346     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
347       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
348         Sema::ContextRAII SavedContext(S, FD);
349         LocalInstantiationScope Local(S);
350         if (FD->getNumParams() > PVD->getFunctionScopeIndex())
351           Local.InstantiatedLocal(
352               PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
353         return S.SubstExpr(E, TemplateArgs);
354       }
355     Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
356                                      FD->isCXXInstanceMember());
357     return S.SubstExpr(E, TemplateArgs);
358   };
359 
360   // Substitute a single OpenMP clause, which is a potentially-evaluated
361   // full-expression.
362   auto Subst = [&](Expr *E) -> ExprResult {
363     EnterExpressionEvaluationContext Evaluated(
364         S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
365     ExprResult Res = SubstExpr(E);
366     if (Res.isInvalid())
367       return Res;
368     return S.ActOnFinishFullExpr(Res.get(), false);
369   };
370 
371   ExprResult Simdlen;
372   if (auto *E = Attr.getSimdlen())
373     Simdlen = Subst(E);
374 
375   if (Attr.uniforms_size() > 0) {
376     for(auto *E : Attr.uniforms()) {
377       ExprResult Inst = Subst(E);
378       if (Inst.isInvalid())
379         continue;
380       Uniforms.push_back(Inst.get());
381     }
382   }
383 
384   auto AI = Attr.alignments_begin();
385   for (auto *E : Attr.aligneds()) {
386     ExprResult Inst = Subst(E);
387     if (Inst.isInvalid())
388       continue;
389     Aligneds.push_back(Inst.get());
390     Inst = ExprEmpty();
391     if (*AI)
392       Inst = S.SubstExpr(*AI, TemplateArgs);
393     Alignments.push_back(Inst.get());
394     ++AI;
395   }
396 
397   auto SI = Attr.steps_begin();
398   for (auto *E : Attr.linears()) {
399     ExprResult Inst = Subst(E);
400     if (Inst.isInvalid())
401       continue;
402     Linears.push_back(Inst.get());
403     Inst = ExprEmpty();
404     if (*SI)
405       Inst = S.SubstExpr(*SI, TemplateArgs);
406     Steps.push_back(Inst.get());
407     ++SI;
408   }
409   LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
410   (void)S.OpenMP().ActOnOpenMPDeclareSimdDirective(
411       S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
412       Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
413       Attr.getRange());
414 }
415 
416 /// Instantiation of 'declare variant' attribute and its arguments.
417 static void instantiateOMPDeclareVariantAttr(
418     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
419     const OMPDeclareVariantAttr &Attr, Decl *New) {
420   // Allow 'this' in clauses with varlist.
421   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
422     New = FTD->getTemplatedDecl();
423   auto *FD = cast<FunctionDecl>(New);
424   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
425 
426   auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
427     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
428       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
429         Sema::ContextRAII SavedContext(S, FD);
430         LocalInstantiationScope Local(S);
431         if (FD->getNumParams() > PVD->getFunctionScopeIndex())
432           Local.InstantiatedLocal(
433               PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
434         return S.SubstExpr(E, TemplateArgs);
435       }
436     Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
437                                      FD->isCXXInstanceMember());
438     return S.SubstExpr(E, TemplateArgs);
439   };
440 
441   // Substitute a single OpenMP clause, which is a potentially-evaluated
442   // full-expression.
443   auto &&Subst = [&SubstExpr, &S](Expr *E) {
444     EnterExpressionEvaluationContext Evaluated(
445         S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
446     ExprResult Res = SubstExpr(E);
447     if (Res.isInvalid())
448       return Res;
449     return S.ActOnFinishFullExpr(Res.get(), false);
450   };
451 
452   ExprResult VariantFuncRef;
453   if (Expr *E = Attr.getVariantFuncRef()) {
454     // Do not mark function as is used to prevent its emission if this is the
455     // only place where it is used.
456     EnterExpressionEvaluationContext Unevaluated(
457         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
458     VariantFuncRef = Subst(E);
459   }
460 
461   // Copy the template version of the OMPTraitInfo and run substitute on all
462   // score and condition expressiosn.
463   OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
464   TI = *Attr.getTraitInfos();
465 
466   // Try to substitute template parameters in score and condition expressions.
467   auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
468     if (E) {
469       EnterExpressionEvaluationContext Unevaluated(
470           S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
471       ExprResult ER = Subst(E);
472       if (ER.isUsable())
473         E = ER.get();
474       else
475         return true;
476     }
477     return false;
478   };
479   if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
480     return;
481 
482   Expr *E = VariantFuncRef.get();
483 
484   // Check function/variant ref for `omp declare variant` but not for `omp
485   // begin declare variant` (which use implicit attributes).
486   std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
487       S.OpenMP().checkOpenMPDeclareVariantFunction(
488           S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
489           Attr.getRange());
490 
491   if (!DeclVarData)
492     return;
493 
494   E = DeclVarData->second;
495   FD = DeclVarData->first;
496 
497   if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
498     if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
499       if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
500         if (!VariantFTD->isThisDeclarationADefinition())
501           return;
502         Sema::TentativeAnalysisScope Trap(S);
503         const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
504             S.Context, TemplateArgs.getInnermost());
505 
506         auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
507                                                          New->getLocation());
508         if (!SubstFD)
509           return;
510         QualType NewType = S.Context.mergeFunctionTypes(
511             SubstFD->getType(), FD->getType(),
512             /* OfBlockPointer */ false,
513             /* Unqualified */ false, /* AllowCXX */ true);
514         if (NewType.isNull())
515           return;
516         S.InstantiateFunctionDefinition(
517             New->getLocation(), SubstFD, /* Recursive */ true,
518             /* DefinitionRequired */ false, /* AtEndOfTU */ false);
519         SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
520         E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
521                                 SourceLocation(), SubstFD,
522                                 /* RefersToEnclosingVariableOrCapture */ false,
523                                 /* NameLoc */ SubstFD->getLocation(),
524                                 SubstFD->getType(), ExprValueKind::VK_PRValue);
525       }
526     }
527   }
528 
529   SmallVector<Expr *, 8> NothingExprs;
530   SmallVector<Expr *, 8> NeedDevicePtrExprs;
531   SmallVector<OMPInteropInfo, 4> AppendArgs;
532 
533   for (Expr *E : Attr.adjustArgsNothing()) {
534     ExprResult ER = Subst(E);
535     if (ER.isInvalid())
536       continue;
537     NothingExprs.push_back(ER.get());
538   }
539   for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
540     ExprResult ER = Subst(E);
541     if (ER.isInvalid())
542       continue;
543     NeedDevicePtrExprs.push_back(ER.get());
544   }
545   for (OMPInteropInfo &II : Attr.appendArgs()) {
546     // When prefer_type is implemented for append_args handle them here too.
547     AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
548   }
549 
550   S.OpenMP().ActOnOpenMPDeclareVariantDirective(
551       FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
552       SourceLocation(), Attr.getRange());
553 }
554 
555 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
556     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
557     const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
558   // Both min and max expression are constant expressions.
559   EnterExpressionEvaluationContext Unevaluated(
560       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
561 
562   ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
563   if (Result.isInvalid())
564     return;
565   Expr *MinExpr = Result.getAs<Expr>();
566 
567   Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
568   if (Result.isInvalid())
569     return;
570   Expr *MaxExpr = Result.getAs<Expr>();
571 
572   S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
573 }
574 
575 ExplicitSpecifier Sema::instantiateExplicitSpecifier(
576     const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
577   if (!ES.getExpr())
578     return ES;
579   Expr *OldCond = ES.getExpr();
580   Expr *Cond = nullptr;
581   {
582     EnterExpressionEvaluationContext Unevaluated(
583         *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
584     ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
585     if (SubstResult.isInvalid()) {
586       return ExplicitSpecifier::Invalid();
587     }
588     Cond = SubstResult.get();
589   }
590   ExplicitSpecifier Result(Cond, ES.getKind());
591   if (!Cond->isTypeDependent())
592     tryResolveExplicitSpecifier(Result);
593   return Result;
594 }
595 
596 static void instantiateDependentAMDGPUWavesPerEUAttr(
597     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
598     const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
599   // Both min and max expression are constant expressions.
600   EnterExpressionEvaluationContext Unevaluated(
601       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
602 
603   ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
604   if (Result.isInvalid())
605     return;
606   Expr *MinExpr = Result.getAs<Expr>();
607 
608   Expr *MaxExpr = nullptr;
609   if (auto Max = Attr.getMax()) {
610     Result = S.SubstExpr(Max, TemplateArgs);
611     if (Result.isInvalid())
612       return;
613     MaxExpr = Result.getAs<Expr>();
614   }
615 
616   S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
617 }
618 
619 static void instantiateDependentAMDGPUMaxNumWorkGroupsAttr(
620     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
621     const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
622   EnterExpressionEvaluationContext Unevaluated(
623       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
624 
625   ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
626   if (!ResultX.isUsable())
627     return;
628   ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
629   if (!ResultY.isUsable())
630     return;
631   ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
632   if (!ResultZ.isUsable())
633     return;
634 
635   Expr *XExpr = ResultX.getAs<Expr>();
636   Expr *YExpr = ResultY.getAs<Expr>();
637   Expr *ZExpr = ResultZ.getAs<Expr>();
638 
639   S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
640 }
641 
642 // This doesn't take any template parameters, but we have a custom action that
643 // needs to happen when the kernel itself is instantiated. We need to run the
644 // ItaniumMangler to mark the names required to name this kernel.
645 static void instantiateDependentSYCLKernelAttr(
646     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
647     const SYCLKernelAttr &Attr, Decl *New) {
648   New->addAttr(Attr.clone(S.getASTContext()));
649 }
650 
651 /// Determine whether the attribute A might be relevant to the declaration D.
652 /// If not, we can skip instantiating it. The attribute may or may not have
653 /// been instantiated yet.
654 static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
655   // 'preferred_name' is only relevant to the matching specialization of the
656   // template.
657   if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
658     QualType T = PNA->getTypedefType();
659     const auto *RD = cast<CXXRecordDecl>(D);
660     if (!T->isDependentType() && !RD->isDependentContext() &&
661         !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
662       return false;
663     for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
664       if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
665                                 PNA->getTypedefType()))
666         return false;
667     return true;
668   }
669 
670   if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
671     const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
672     switch (BA->getID()) {
673     case Builtin::BIforward:
674       // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
675       // type and returns an lvalue reference type. The library implementation
676       // will produce an error in this case; don't get in its way.
677       if (FD && FD->getNumParams() >= 1 &&
678           FD->getParamDecl(0)->getType()->isRValueReferenceType() &&
679           FD->getReturnType()->isLValueReferenceType()) {
680         return false;
681       }
682       [[fallthrough]];
683     case Builtin::BImove:
684     case Builtin::BImove_if_noexcept:
685       // HACK: Super-old versions of libc++ (3.1 and earlier) provide
686       // std::forward and std::move overloads that sometimes return by value
687       // instead of by reference when building in C++98 mode. Don't treat such
688       // cases as builtins.
689       if (FD && !FD->getReturnType()->isReferenceType())
690         return false;
691       break;
692     }
693   }
694 
695   return true;
696 }
697 
698 static void instantiateDependentHLSLParamModifierAttr(
699     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
700     const HLSLParamModifierAttr *Attr, Decl *New) {
701   ParmVarDecl *P = cast<ParmVarDecl>(New);
702   P->addAttr(Attr->clone(S.getASTContext()));
703   P->setType(S.HLSL().getInoutParameterType(P->getType()));
704 }
705 
706 void Sema::InstantiateAttrsForDecl(
707     const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
708     Decl *New, LateInstantiatedAttrVec *LateAttrs,
709     LocalInstantiationScope *OuterMostScope) {
710   if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
711     // FIXME: This function is called multiple times for the same template
712     // specialization. We should only instantiate attributes that were added
713     // since the previous instantiation.
714     for (const auto *TmplAttr : Tmpl->attrs()) {
715       if (!isRelevantAttr(*this, New, TmplAttr))
716         continue;
717 
718       // FIXME: If any of the special case versions from InstantiateAttrs become
719       // applicable to template declaration, we'll need to add them here.
720       CXXThisScopeRAII ThisScope(
721           *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
722           Qualifiers(), ND->isCXXInstanceMember());
723 
724       Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
725           TmplAttr, Context, *this, TemplateArgs);
726       if (NewAttr && isRelevantAttr(*this, New, NewAttr))
727         New->addAttr(NewAttr);
728     }
729   }
730 }
731 
732 static Sema::RetainOwnershipKind
733 attrToRetainOwnershipKind(const Attr *A) {
734   switch (A->getKind()) {
735   case clang::attr::CFConsumed:
736     return Sema::RetainOwnershipKind::CF;
737   case clang::attr::OSConsumed:
738     return Sema::RetainOwnershipKind::OS;
739   case clang::attr::NSConsumed:
740     return Sema::RetainOwnershipKind::NS;
741   default:
742     llvm_unreachable("Wrong argument supplied");
743   }
744 }
745 
746 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
747                             const Decl *Tmpl, Decl *New,
748                             LateInstantiatedAttrVec *LateAttrs,
749                             LocalInstantiationScope *OuterMostScope) {
750   for (const auto *TmplAttr : Tmpl->attrs()) {
751     if (!isRelevantAttr(*this, New, TmplAttr))
752       continue;
753 
754     // FIXME: This should be generalized to more than just the AlignedAttr.
755     const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
756     if (Aligned && Aligned->isAlignmentDependent()) {
757       instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
758       continue;
759     }
760 
761     if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
762       instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
763       continue;
764     }
765 
766     if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
767       instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
768       continue;
769     }
770 
771     if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
772       instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
773       continue;
774     }
775 
776     if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
777       instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
778       continue;
779     }
780 
781     if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
782       instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
783                                        cast<FunctionDecl>(New));
784       continue;
785     }
786 
787     if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
788       instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
789                                          cast<FunctionDecl>(New));
790       continue;
791     }
792 
793     if (const auto *CUDALaunchBounds =
794             dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
795       instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
796                                                *CUDALaunchBounds, New);
797       continue;
798     }
799 
800     if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
801       instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
802       continue;
803     }
804 
805     if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
806       instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
807       continue;
808     }
809 
810     if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
811       instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
812       continue;
813     }
814 
815     if (const auto *AMDGPUFlatWorkGroupSize =
816             dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
817       instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
818           *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
819     }
820 
821     if (const auto *AMDGPUFlatWorkGroupSize =
822             dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
823       instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
824                                                *AMDGPUFlatWorkGroupSize, New);
825     }
826 
827     if (const auto *AMDGPUMaxNumWorkGroups =
828             dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
829       instantiateDependentAMDGPUMaxNumWorkGroupsAttr(
830           *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
831     }
832 
833     if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
834       instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
835                                                 New);
836       continue;
837     }
838 
839     // Existing DLL attribute on the instantiation takes precedence.
840     if (TmplAttr->getKind() == attr::DLLExport ||
841         TmplAttr->getKind() == attr::DLLImport) {
842       if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
843         continue;
844       }
845     }
846 
847     if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
848       Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
849       continue;
850     }
851 
852     if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
853         isa<CFConsumedAttr>(TmplAttr)) {
854       ObjC().AddXConsumedAttr(New, *TmplAttr,
855                               attrToRetainOwnershipKind(TmplAttr),
856                               /*template instantiation=*/true);
857       continue;
858     }
859 
860     if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
861       if (!New->hasAttr<PointerAttr>())
862         New->addAttr(A->clone(Context));
863       continue;
864     }
865 
866     if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
867       if (!New->hasAttr<OwnerAttr>())
868         New->addAttr(A->clone(Context));
869       continue;
870     }
871 
872     if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
873       instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
874       continue;
875     }
876 
877     if (auto *A = dyn_cast<CUDAGridConstantAttr>(TmplAttr)) {
878       if (!New->hasAttr<CUDAGridConstantAttr>())
879         New->addAttr(A->clone(Context));
880       continue;
881     }
882 
883     assert(!TmplAttr->isPackExpansion());
884     if (TmplAttr->isLateParsed() && LateAttrs) {
885       // Late parsed attributes must be instantiated and attached after the
886       // enclosing class has been instantiated.  See Sema::InstantiateClass.
887       LocalInstantiationScope *Saved = nullptr;
888       if (CurrentInstantiationScope)
889         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
890       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
891     } else {
892       // Allow 'this' within late-parsed attributes.
893       auto *ND = cast<NamedDecl>(New);
894       auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
895       CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
896                                  ND->isCXXInstanceMember());
897 
898       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
899                                                          *this, TemplateArgs);
900       if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
901         New->addAttr(NewAttr);
902     }
903   }
904 }
905 
906 void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
907   for (const auto *Attr : Pattern->attrs()) {
908     if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
909       if (!Inst->hasAttr<StrictFPAttr>())
910         Inst->addAttr(A->clone(getASTContext()));
911       continue;
912     }
913   }
914 }
915 
916 void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
917   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
918          Ctor->isDefaultConstructor());
919   unsigned NumParams = Ctor->getNumParams();
920   if (NumParams == 0)
921     return;
922   DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
923   if (!Attr)
924     return;
925   for (unsigned I = 0; I != NumParams; ++I) {
926     (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
927                                    Ctor->getParamDecl(I));
928     CleanupVarDeclMarking();
929   }
930 }
931 
932 /// Get the previous declaration of a declaration for the purposes of template
933 /// instantiation. If this finds a previous declaration, then the previous
934 /// declaration of the instantiation of D should be an instantiation of the
935 /// result of this function.
936 template<typename DeclT>
937 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
938   DeclT *Result = D->getPreviousDecl();
939 
940   // If the declaration is within a class, and the previous declaration was
941   // merged from a different definition of that class, then we don't have a
942   // previous declaration for the purpose of template instantiation.
943   if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
944       D->getLexicalDeclContext() != Result->getLexicalDeclContext())
945     return nullptr;
946 
947   return Result;
948 }
949 
950 Decl *
951 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
952   llvm_unreachable("Translation units cannot be instantiated");
953 }
954 
955 Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
956   llvm_unreachable("HLSL buffer declarations cannot be instantiated");
957 }
958 
959 Decl *
960 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
961   llvm_unreachable("pragma comment cannot be instantiated");
962 }
963 
964 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
965     PragmaDetectMismatchDecl *D) {
966   llvm_unreachable("pragma comment cannot be instantiated");
967 }
968 
969 Decl *
970 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
971   llvm_unreachable("extern \"C\" context cannot be instantiated");
972 }
973 
974 Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
975   llvm_unreachable("GUID declaration cannot be instantiated");
976 }
977 
978 Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
979     UnnamedGlobalConstantDecl *D) {
980   llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
981 }
982 
983 Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
984     TemplateParamObjectDecl *D) {
985   llvm_unreachable("template parameter objects cannot be instantiated");
986 }
987 
988 Decl *
989 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
990   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
991                                       D->getIdentifier());
992   SemaRef.InstantiateAttrs(TemplateArgs, D, Inst, LateAttrs, StartingScope);
993   Owner->addDecl(Inst);
994   return Inst;
995 }
996 
997 Decl *
998 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
999   llvm_unreachable("Namespaces cannot be instantiated");
1000 }
1001 
1002 Decl *
1003 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1004   NamespaceAliasDecl *Inst
1005     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1006                                  D->getNamespaceLoc(),
1007                                  D->getAliasLoc(),
1008                                  D->getIdentifier(),
1009                                  D->getQualifierLoc(),
1010                                  D->getTargetNameLoc(),
1011                                  D->getNamespace());
1012   Owner->addDecl(Inst);
1013   return Inst;
1014 }
1015 
1016 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
1017                                                            bool IsTypeAlias) {
1018   bool Invalid = false;
1019   TypeSourceInfo *DI = D->getTypeSourceInfo();
1020   if (DI->getType()->isInstantiationDependentType() ||
1021       DI->getType()->isVariablyModifiedType()) {
1022     DI = SemaRef.SubstType(DI, TemplateArgs,
1023                            D->getLocation(), D->getDeclName());
1024     if (!DI) {
1025       Invalid = true;
1026       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1027     }
1028   } else {
1029     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1030   }
1031 
1032   // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1033   // libstdc++ relies upon this bug in its implementation of common_type.  If we
1034   // happen to be processing that implementation, fake up the g++ ?:
1035   // semantics. See LWG issue 2141 for more information on the bug.  The bugs
1036   // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1037   const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
1038   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1039   if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1040       DT->isReferenceType() &&
1041       RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1042       RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1043       D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1044       SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
1045     // Fold it to the (non-reference) type which g++ would have produced.
1046     DI = SemaRef.Context.getTrivialTypeSourceInfo(
1047       DI->getType().getNonReferenceType());
1048 
1049   // Create the new typedef
1050   TypedefNameDecl *Typedef;
1051   if (IsTypeAlias)
1052     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1053                                     D->getLocation(), D->getIdentifier(), DI);
1054   else
1055     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1056                                   D->getLocation(), D->getIdentifier(), DI);
1057   if (Invalid)
1058     Typedef->setInvalidDecl();
1059 
1060   // If the old typedef was the name for linkage purposes of an anonymous
1061   // tag decl, re-establish that relationship for the new typedef.
1062   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1063     TagDecl *oldTag = oldTagType->getDecl();
1064     if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1065       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1066       assert(!newTag->hasNameForLinkage());
1067       newTag->setTypedefNameForAnonDecl(Typedef);
1068     }
1069   }
1070 
1071   if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
1072     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1073                                                        TemplateArgs);
1074     if (!InstPrev)
1075       return nullptr;
1076 
1077     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1078 
1079     // If the typedef types are not identical, reject them.
1080     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1081 
1082     Typedef->setPreviousDecl(InstPrevTypedef);
1083   }
1084 
1085   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1086 
1087   if (D->getUnderlyingType()->getAs<DependentNameType>())
1088     SemaRef.inferGslPointerAttribute(Typedef);
1089 
1090   Typedef->setAccess(D->getAccess());
1091   Typedef->setReferenced(D->isReferenced());
1092 
1093   return Typedef;
1094 }
1095 
1096 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1097   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1098   if (Typedef)
1099     Owner->addDecl(Typedef);
1100   return Typedef;
1101 }
1102 
1103 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1104   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1105   if (Typedef)
1106     Owner->addDecl(Typedef);
1107   return Typedef;
1108 }
1109 
1110 Decl *TemplateDeclInstantiator::InstantiateTypeAliasTemplateDecl(
1111     TypeAliasTemplateDecl *D) {
1112   // Create a local instantiation scope for this type alias template, which
1113   // will contain the instantiations of the template parameters.
1114   LocalInstantiationScope Scope(SemaRef);
1115 
1116   TemplateParameterList *TempParams = D->getTemplateParameters();
1117   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1118   if (!InstParams)
1119     return nullptr;
1120 
1121   TypeAliasDecl *Pattern = D->getTemplatedDecl();
1122   Sema::InstantiatingTemplate InstTemplate(
1123       SemaRef, D->getBeginLoc(), D,
1124       D->getTemplateDepth() >= TemplateArgs.getNumLevels()
1125           ? ArrayRef<TemplateArgument>()
1126           : (TemplateArgs.begin() + TemplateArgs.getNumLevels() - 1 -
1127              D->getTemplateDepth())
1128                 ->Args);
1129   if (InstTemplate.isInvalid())
1130     return nullptr;
1131 
1132   TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1133   if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1134     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1135     if (!Found.empty()) {
1136       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1137     }
1138   }
1139 
1140   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1141     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1142   if (!AliasInst)
1143     return nullptr;
1144 
1145   TypeAliasTemplateDecl *Inst
1146     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1147                                     D->getDeclName(), InstParams, AliasInst);
1148   AliasInst->setDescribedAliasTemplate(Inst);
1149   if (PrevAliasTemplate)
1150     Inst->setPreviousDecl(PrevAliasTemplate);
1151 
1152   Inst->setAccess(D->getAccess());
1153 
1154   if (!PrevAliasTemplate)
1155     Inst->setInstantiatedFromMemberTemplate(D);
1156 
1157   return Inst;
1158 }
1159 
1160 Decl *
1161 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1162   Decl *Inst = InstantiateTypeAliasTemplateDecl(D);
1163   if (Inst)
1164     Owner->addDecl(Inst);
1165 
1166   return Inst;
1167 }
1168 
1169 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1170   auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1171                                     D->getIdentifier(), D->getType());
1172   NewBD->setReferenced(D->isReferenced());
1173   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1174 
1175   return NewBD;
1176 }
1177 
1178 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1179   // Transform the bindings first.
1180   // The transformed DD will have all of the concrete BindingDecls.
1181   SmallVector<BindingDecl*, 16> NewBindings;
1182   ResolvedUnexpandedPackExpr *OldResolvedPack = nullptr;
1183   for (auto *OldBD : D->bindings()) {
1184     Expr *BindingExpr = OldBD->getBinding();
1185     if (auto *RP =
1186             dyn_cast_if_present<ResolvedUnexpandedPackExpr>(BindingExpr)) {
1187       assert(!OldResolvedPack && "no more than one pack is allowed");
1188       OldResolvedPack = RP;
1189     }
1190     NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1191   }
1192   ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1193 
1194   auto *NewDD = cast_if_present<DecompositionDecl>(
1195       VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1196 
1197   if (!NewDD || NewDD->isInvalidDecl())
1198     for (auto *NewBD : NewBindings)
1199       NewBD->setInvalidDecl();
1200 
1201   if (OldResolvedPack) {
1202     // Mark the holding vars (if any) in the pack as instantiated since
1203     // they are created implicitly.
1204     auto Bindings = NewDD->bindings();
1205     auto BPack = llvm::find_if(
1206         Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1207     auto *NewResolvedPack =
1208         cast<ResolvedUnexpandedPackExpr>((*BPack)->getBinding());
1209     auto OldExprs = OldResolvedPack->getExprs();
1210     auto NewExprs = NewResolvedPack->getExprs();
1211     assert(OldExprs.size() == NewExprs.size());
1212     for (unsigned I = 0; I < OldResolvedPack->getNumExprs(); I++) {
1213       DeclRefExpr *OldDRE = cast<DeclRefExpr>(OldExprs[I]);
1214       BindingDecl *OldNestedBD = cast<BindingDecl>(OldDRE->getDecl());
1215       DeclRefExpr *NewDRE = cast<DeclRefExpr>(NewExprs[I]);
1216       BindingDecl *NewNestedBD = cast<BindingDecl>(NewDRE->getDecl());
1217       SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldNestedBD,
1218                                                            NewNestedBD);
1219     }
1220   }
1221 
1222   return NewDD;
1223 }
1224 
1225 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1226   return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1227 }
1228 
1229 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1230                                              bool InstantiatingVarTemplate,
1231                                              ArrayRef<BindingDecl*> *Bindings) {
1232 
1233   // Do substitution on the type of the declaration
1234   TypeSourceInfo *DI = SemaRef.SubstType(
1235       D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1236       D->getDeclName(), /*AllowDeducedTST*/true);
1237   if (!DI)
1238     return nullptr;
1239 
1240   if (DI->getType()->isFunctionType()) {
1241     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1242       << D->isStaticDataMember() << DI->getType();
1243     return nullptr;
1244   }
1245 
1246   DeclContext *DC = Owner;
1247   if (D->isLocalExternDecl())
1248     SemaRef.adjustContextForLocalExternDecl(DC);
1249 
1250   // Build the instantiated declaration.
1251   VarDecl *Var;
1252   if (Bindings)
1253     Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1254                                     D->getLocation(), DI->getType(), DI,
1255                                     D->getStorageClass(), *Bindings);
1256   else
1257     Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1258                           D->getLocation(), D->getIdentifier(), DI->getType(),
1259                           DI, D->getStorageClass());
1260 
1261   // In ARC, infer 'retaining' for variables of retainable type.
1262   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1263       SemaRef.ObjC().inferObjCARCLifetime(Var))
1264     Var->setInvalidDecl();
1265 
1266   if (SemaRef.getLangOpts().OpenCL)
1267     SemaRef.deduceOpenCLAddressSpace(Var);
1268 
1269   // Substitute the nested name specifier, if any.
1270   if (SubstQualifier(D, Var))
1271     return nullptr;
1272 
1273   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1274                                      StartingScope, InstantiatingVarTemplate);
1275   if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1276     QualType RT;
1277     if (auto *F = dyn_cast<FunctionDecl>(DC))
1278       RT = F->getReturnType();
1279     else if (isa<BlockDecl>(DC))
1280       RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1281                ->getReturnType();
1282     else
1283       llvm_unreachable("Unknown context type");
1284 
1285     // This is the last chance we have of checking copy elision eligibility
1286     // for functions in dependent contexts. The sema actions for building
1287     // the return statement during template instantiation will have no effect
1288     // regarding copy elision, since NRVO propagation runs on the scope exit
1289     // actions, and these are not run on instantiation.
1290     // This might run through some VarDecls which were returned from non-taken
1291     // 'if constexpr' branches, and these will end up being constructed on the
1292     // return slot even if they will never be returned, as a sort of accidental
1293     // 'optimization'. Notably, functions with 'auto' return types won't have it
1294     // deduced by this point. Coupled with the limitation described
1295     // previously, this makes it very hard to support copy elision for these.
1296     Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1297     bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1298     Var->setNRVOVariable(NRVO);
1299   }
1300 
1301   Var->setImplicit(D->isImplicit());
1302 
1303   if (Var->isStaticLocal())
1304     SemaRef.CheckStaticLocalForDllExport(Var);
1305 
1306   if (Var->getTLSKind())
1307     SemaRef.CheckThreadLocalForLargeAlignment(Var);
1308 
1309   return Var;
1310 }
1311 
1312 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1313   AccessSpecDecl* AD
1314     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1315                              D->getAccessSpecifierLoc(), D->getColonLoc());
1316   Owner->addHiddenDecl(AD);
1317   return AD;
1318 }
1319 
1320 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1321   bool Invalid = false;
1322   TypeSourceInfo *DI = D->getTypeSourceInfo();
1323   if (DI->getType()->isInstantiationDependentType() ||
1324       DI->getType()->isVariablyModifiedType())  {
1325     DI = SemaRef.SubstType(DI, TemplateArgs,
1326                            D->getLocation(), D->getDeclName());
1327     if (!DI) {
1328       DI = D->getTypeSourceInfo();
1329       Invalid = true;
1330     } else if (DI->getType()->isFunctionType()) {
1331       // C++ [temp.arg.type]p3:
1332       //   If a declaration acquires a function type through a type
1333       //   dependent on a template-parameter and this causes a
1334       //   declaration that does not use the syntactic form of a
1335       //   function declarator to have function type, the program is
1336       //   ill-formed.
1337       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1338         << DI->getType();
1339       Invalid = true;
1340     }
1341   } else {
1342     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1343   }
1344 
1345   Expr *BitWidth = D->getBitWidth();
1346   if (Invalid)
1347     BitWidth = nullptr;
1348   else if (BitWidth) {
1349     // The bit-width expression is a constant expression.
1350     EnterExpressionEvaluationContext Unevaluated(
1351         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1352 
1353     ExprResult InstantiatedBitWidth
1354       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1355     if (InstantiatedBitWidth.isInvalid()) {
1356       Invalid = true;
1357       BitWidth = nullptr;
1358     } else
1359       BitWidth = InstantiatedBitWidth.getAs<Expr>();
1360   }
1361 
1362   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1363                                             DI->getType(), DI,
1364                                             cast<RecordDecl>(Owner),
1365                                             D->getLocation(),
1366                                             D->isMutable(),
1367                                             BitWidth,
1368                                             D->getInClassInitStyle(),
1369                                             D->getInnerLocStart(),
1370                                             D->getAccess(),
1371                                             nullptr);
1372   if (!Field) {
1373     cast<Decl>(Owner)->setInvalidDecl();
1374     return nullptr;
1375   }
1376 
1377   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1378 
1379   if (Field->hasAttrs())
1380     SemaRef.CheckAlignasUnderalignment(Field);
1381 
1382   if (Invalid)
1383     Field->setInvalidDecl();
1384 
1385   if (!Field->getDeclName() || Field->isPlaceholderVar(SemaRef.getLangOpts())) {
1386     // Keep track of where this decl came from.
1387     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1388   }
1389   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1390     if (Parent->isAnonymousStructOrUnion() &&
1391         Parent->getRedeclContext()->isFunctionOrMethod())
1392       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1393   }
1394 
1395   Field->setImplicit(D->isImplicit());
1396   Field->setAccess(D->getAccess());
1397   Owner->addDecl(Field);
1398 
1399   return Field;
1400 }
1401 
1402 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1403   bool Invalid = false;
1404   TypeSourceInfo *DI = D->getTypeSourceInfo();
1405 
1406   if (DI->getType()->isVariablyModifiedType()) {
1407     SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1408       << D;
1409     Invalid = true;
1410   } else if (DI->getType()->isInstantiationDependentType())  {
1411     DI = SemaRef.SubstType(DI, TemplateArgs,
1412                            D->getLocation(), D->getDeclName());
1413     if (!DI) {
1414       DI = D->getTypeSourceInfo();
1415       Invalid = true;
1416     } else if (DI->getType()->isFunctionType()) {
1417       // C++ [temp.arg.type]p3:
1418       //   If a declaration acquires a function type through a type
1419       //   dependent on a template-parameter and this causes a
1420       //   declaration that does not use the syntactic form of a
1421       //   function declarator to have function type, the program is
1422       //   ill-formed.
1423       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1424       << DI->getType();
1425       Invalid = true;
1426     }
1427   } else {
1428     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1429   }
1430 
1431   MSPropertyDecl *Property = MSPropertyDecl::Create(
1432       SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1433       DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1434 
1435   SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1436                            StartingScope);
1437 
1438   if (Invalid)
1439     Property->setInvalidDecl();
1440 
1441   Property->setAccess(D->getAccess());
1442   Owner->addDecl(Property);
1443 
1444   return Property;
1445 }
1446 
1447 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1448   NamedDecl **NamedChain =
1449     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1450 
1451   int i = 0;
1452   for (auto *PI : D->chain()) {
1453     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1454                                               TemplateArgs);
1455     if (!Next)
1456       return nullptr;
1457 
1458     NamedChain[i++] = Next;
1459   }
1460 
1461   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1462   IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1463       SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1464       {NamedChain, D->getChainingSize()});
1465 
1466   for (const auto *Attr : D->attrs())
1467     IndirectField->addAttr(Attr->clone(SemaRef.Context));
1468 
1469   IndirectField->setImplicit(D->isImplicit());
1470   IndirectField->setAccess(D->getAccess());
1471   Owner->addDecl(IndirectField);
1472   return IndirectField;
1473 }
1474 
1475 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1476   // Handle friend type expressions by simply substituting template
1477   // parameters into the pattern type and checking the result.
1478   if (TypeSourceInfo *Ty = D->getFriendType()) {
1479     TypeSourceInfo *InstTy;
1480     // If this is an unsupported friend, don't bother substituting template
1481     // arguments into it. The actual type referred to won't be used by any
1482     // parts of Clang, and may not be valid for instantiating. Just use the
1483     // same info for the instantiated friend.
1484     if (D->isUnsupportedFriend()) {
1485       InstTy = Ty;
1486     } else {
1487       if (D->isPackExpansion()) {
1488         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1489         SemaRef.collectUnexpandedParameterPacks(Ty->getTypeLoc(), Unexpanded);
1490         assert(!Unexpanded.empty() && "Pack expansion without packs");
1491 
1492         bool ShouldExpand = true;
1493         bool RetainExpansion = false;
1494         std::optional<unsigned> NumExpansions;
1495         if (SemaRef.CheckParameterPacksForExpansion(
1496                 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded,
1497                 TemplateArgs, ShouldExpand, RetainExpansion, NumExpansions))
1498           return nullptr;
1499 
1500         assert(!RetainExpansion &&
1501                "should never retain an expansion for a variadic friend decl");
1502 
1503         if (ShouldExpand) {
1504           SmallVector<FriendDecl *> Decls;
1505           for (unsigned I = 0; I != *NumExpansions; I++) {
1506             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1507             TypeSourceInfo *TSI = SemaRef.SubstType(
1508                 Ty, TemplateArgs, D->getEllipsisLoc(), DeclarationName());
1509             if (!TSI)
1510               return nullptr;
1511 
1512             auto FD =
1513                 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1514                                    TSI, D->getFriendLoc());
1515 
1516             FD->setAccess(AS_public);
1517             Owner->addDecl(FD);
1518             Decls.push_back(FD);
1519           }
1520 
1521           // Just drop this node; we have no use for it anymore.
1522           return nullptr;
1523         }
1524       }
1525 
1526       InstTy = SemaRef.SubstType(Ty, TemplateArgs, D->getLocation(),
1527                                  DeclarationName());
1528     }
1529     if (!InstTy)
1530       return nullptr;
1531 
1532     FriendDecl *FD = FriendDecl::Create(
1533         SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
1534     FD->setAccess(AS_public);
1535     FD->setUnsupportedFriend(D->isUnsupportedFriend());
1536     Owner->addDecl(FD);
1537     return FD;
1538   }
1539 
1540   NamedDecl *ND = D->getFriendDecl();
1541   assert(ND && "friend decl must be a decl or a type!");
1542 
1543   // All of the Visit implementations for the various potential friend
1544   // declarations have to be carefully written to work for friend
1545   // objects, with the most important detail being that the target
1546   // decl should almost certainly not be placed in Owner.
1547   Decl *NewND = Visit(ND);
1548   if (!NewND) return nullptr;
1549 
1550   FriendDecl *FD =
1551     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1552                        cast<NamedDecl>(NewND), D->getFriendLoc());
1553   FD->setAccess(AS_public);
1554   FD->setUnsupportedFriend(D->isUnsupportedFriend());
1555   Owner->addDecl(FD);
1556   return FD;
1557 }
1558 
1559 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1560   Expr *AssertExpr = D->getAssertExpr();
1561 
1562   // The expression in a static assertion is a constant expression.
1563   EnterExpressionEvaluationContext Unevaluated(
1564       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1565 
1566   ExprResult InstantiatedAssertExpr
1567     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1568   if (InstantiatedAssertExpr.isInvalid())
1569     return nullptr;
1570 
1571   ExprResult InstantiatedMessageExpr =
1572       SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
1573   if (InstantiatedMessageExpr.isInvalid())
1574     return nullptr;
1575 
1576   return SemaRef.BuildStaticAssertDeclaration(
1577       D->getLocation(), InstantiatedAssertExpr.get(),
1578       InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
1579 }
1580 
1581 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1582   EnumDecl *PrevDecl = nullptr;
1583   if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1584     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1585                                                    PatternPrev,
1586                                                    TemplateArgs);
1587     if (!Prev) return nullptr;
1588     PrevDecl = cast<EnumDecl>(Prev);
1589   }
1590 
1591   EnumDecl *Enum =
1592       EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1593                        D->getLocation(), D->getIdentifier(), PrevDecl,
1594                        D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1595   if (D->isFixed()) {
1596     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1597       // If we have type source information for the underlying type, it means it
1598       // has been explicitly set by the user. Perform substitution on it before
1599       // moving on.
1600       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1601       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1602                                                 DeclarationName());
1603       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1604         Enum->setIntegerType(SemaRef.Context.IntTy);
1605       else
1606         Enum->setIntegerTypeSourceInfo(NewTI);
1607 
1608       // C++23 [conv.prom]p4
1609       // if integral promotion can be applied to its underlying type, a prvalue
1610       // of an unscoped enumeration type whose underlying type is fixed can also
1611       // be converted to a prvalue of the promoted underlying type.
1612       //
1613       // FIXME: that logic is already implemented in ActOnEnumBody, factor out
1614       // into (Re)BuildEnumBody.
1615       QualType UnderlyingType = Enum->getIntegerType();
1616       Enum->setPromotionType(
1617           SemaRef.Context.isPromotableIntegerType(UnderlyingType)
1618               ? SemaRef.Context.getPromotedIntegerType(UnderlyingType)
1619               : UnderlyingType);
1620     } else {
1621       assert(!D->getIntegerType()->isDependentType()
1622              && "Dependent type without type source info");
1623       Enum->setIntegerType(D->getIntegerType());
1624     }
1625   }
1626 
1627   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1628 
1629   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1630   Enum->setAccess(D->getAccess());
1631   // Forward the mangling number from the template to the instantiated decl.
1632   SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1633   // See if the old tag was defined along with a declarator.
1634   // If it did, mark the new tag as being associated with that declarator.
1635   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1636     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1637   // See if the old tag was defined along with a typedef.
1638   // If it did, mark the new tag as being associated with that typedef.
1639   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1640     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1641   if (SubstQualifier(D, Enum)) return nullptr;
1642   Owner->addDecl(Enum);
1643 
1644   EnumDecl *Def = D->getDefinition();
1645   if (Def && Def != D) {
1646     // If this is an out-of-line definition of an enum member template, check
1647     // that the underlying types match in the instantiation of both
1648     // declarations.
1649     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1650       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1651       QualType DefnUnderlying =
1652         SemaRef.SubstType(TI->getType(), TemplateArgs,
1653                           UnderlyingLoc, DeclarationName());
1654       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1655                                      DefnUnderlying, /*IsFixed=*/true, Enum);
1656     }
1657   }
1658 
1659   // C++11 [temp.inst]p1: The implicit instantiation of a class template
1660   // specialization causes the implicit instantiation of the declarations, but
1661   // not the definitions of scoped member enumerations.
1662   //
1663   // DR1484 clarifies that enumeration definitions inside a template
1664   // declaration aren't considered entities that can be separately instantiated
1665   // from the rest of the entity they are declared inside.
1666   if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1667     // Prevent redundant instantiation of the enumerator-definition if the
1668     // definition has already been instantiated due to a prior
1669     // opaque-enum-declaration.
1670     if (PrevDecl == nullptr) {
1671       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1672       InstantiateEnumDefinition(Enum, Def);
1673     }
1674   }
1675 
1676   return Enum;
1677 }
1678 
1679 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1680     EnumDecl *Enum, EnumDecl *Pattern) {
1681   Enum->startDefinition();
1682 
1683   // Update the location to refer to the definition.
1684   Enum->setLocation(Pattern->getLocation());
1685 
1686   SmallVector<Decl*, 4> Enumerators;
1687 
1688   EnumConstantDecl *LastEnumConst = nullptr;
1689   for (auto *EC : Pattern->enumerators()) {
1690     // The specified value for the enumerator.
1691     ExprResult Value((Expr *)nullptr);
1692     if (Expr *UninstValue = EC->getInitExpr()) {
1693       // The enumerator's value expression is a constant expression.
1694       EnterExpressionEvaluationContext Unevaluated(
1695           SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1696 
1697       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1698     }
1699 
1700     // Drop the initial value and continue.
1701     bool isInvalid = false;
1702     if (Value.isInvalid()) {
1703       Value = nullptr;
1704       isInvalid = true;
1705     }
1706 
1707     EnumConstantDecl *EnumConst
1708       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1709                                   EC->getLocation(), EC->getIdentifier(),
1710                                   Value.get());
1711 
1712     if (isInvalid) {
1713       if (EnumConst)
1714         EnumConst->setInvalidDecl();
1715       Enum->setInvalidDecl();
1716     }
1717 
1718     if (EnumConst) {
1719       SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1720 
1721       EnumConst->setAccess(Enum->getAccess());
1722       Enum->addDecl(EnumConst);
1723       Enumerators.push_back(EnumConst);
1724       LastEnumConst = EnumConst;
1725 
1726       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1727           !Enum->isScoped()) {
1728         // If the enumeration is within a function or method, record the enum
1729         // constant as a local.
1730         SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1731       }
1732     }
1733   }
1734 
1735   SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1736                         Enumerators, nullptr, ParsedAttributesView());
1737 }
1738 
1739 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1740   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1741 }
1742 
1743 Decl *
1744 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1745   llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1746 }
1747 
1748 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1749   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1750 
1751   // Create a local instantiation scope for this class template, which
1752   // will contain the instantiations of the template parameters.
1753   LocalInstantiationScope Scope(SemaRef);
1754   TemplateParameterList *TempParams = D->getTemplateParameters();
1755   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1756   if (!InstParams)
1757     return nullptr;
1758 
1759   CXXRecordDecl *Pattern = D->getTemplatedDecl();
1760 
1761   // Instantiate the qualifier.  We have to do this first in case
1762   // we're a friend declaration, because if we are then we need to put
1763   // the new declaration in the appropriate context.
1764   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1765   if (QualifierLoc) {
1766     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1767                                                        TemplateArgs);
1768     if (!QualifierLoc)
1769       return nullptr;
1770   }
1771 
1772   CXXRecordDecl *PrevDecl = nullptr;
1773   ClassTemplateDecl *PrevClassTemplate = nullptr;
1774 
1775   if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1776     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1777     if (!Found.empty()) {
1778       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1779       if (PrevClassTemplate)
1780         PrevDecl = PrevClassTemplate->getTemplatedDecl();
1781     }
1782   }
1783 
1784   // If this isn't a friend, then it's a member template, in which
1785   // case we just want to build the instantiation in the
1786   // specialization.  If it is a friend, we want to build it in
1787   // the appropriate context.
1788   DeclContext *DC = Owner;
1789   if (isFriend) {
1790     if (QualifierLoc) {
1791       CXXScopeSpec SS;
1792       SS.Adopt(QualifierLoc);
1793       DC = SemaRef.computeDeclContext(SS);
1794       if (!DC) return nullptr;
1795     } else {
1796       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1797                                            Pattern->getDeclContext(),
1798                                            TemplateArgs);
1799     }
1800 
1801     // Look for a previous declaration of the template in the owning
1802     // context.
1803     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1804                    Sema::LookupOrdinaryName,
1805                    SemaRef.forRedeclarationInCurContext());
1806     SemaRef.LookupQualifiedName(R, DC);
1807 
1808     if (R.isSingleResult()) {
1809       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1810       if (PrevClassTemplate)
1811         PrevDecl = PrevClassTemplate->getTemplatedDecl();
1812     }
1813 
1814     if (!PrevClassTemplate && QualifierLoc) {
1815       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1816           << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
1817           << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
1818       return nullptr;
1819     }
1820   }
1821 
1822   CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1823       SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1824       Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1825       /*DelayTypeCreation=*/true);
1826   if (QualifierLoc)
1827     RecordInst->setQualifierInfo(QualifierLoc);
1828 
1829   SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1830                                                               StartingScope);
1831 
1832   ClassTemplateDecl *Inst
1833     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1834                                 D->getIdentifier(), InstParams, RecordInst);
1835   RecordInst->setDescribedClassTemplate(Inst);
1836 
1837   if (isFriend) {
1838     assert(!Owner->isDependentContext());
1839     Inst->setLexicalDeclContext(Owner);
1840     RecordInst->setLexicalDeclContext(Owner);
1841     Inst->setObjectOfFriendDecl();
1842 
1843     if (PrevClassTemplate) {
1844       Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1845       RecordInst->setTypeForDecl(
1846           PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1847       const ClassTemplateDecl *MostRecentPrevCT =
1848           PrevClassTemplate->getMostRecentDecl();
1849       TemplateParameterList *PrevParams =
1850           MostRecentPrevCT->getTemplateParameters();
1851 
1852       // Make sure the parameter lists match.
1853       if (!SemaRef.TemplateParameterListsAreEqual(
1854               RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1855               PrevParams, true, Sema::TPL_TemplateMatch))
1856         return nullptr;
1857 
1858       // Do some additional validation, then merge default arguments
1859       // from the existing declarations.
1860       if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1861                                              Sema::TPC_ClassTemplate))
1862         return nullptr;
1863 
1864       Inst->setAccess(PrevClassTemplate->getAccess());
1865     } else {
1866       Inst->setAccess(D->getAccess());
1867     }
1868 
1869     Inst->setObjectOfFriendDecl();
1870     // TODO: do we want to track the instantiation progeny of this
1871     // friend target decl?
1872   } else {
1873     Inst->setAccess(D->getAccess());
1874     if (!PrevClassTemplate)
1875       Inst->setInstantiatedFromMemberTemplate(D);
1876   }
1877 
1878   Inst->setPreviousDecl(PrevClassTemplate);
1879 
1880   // Trigger creation of the type for the instantiation.
1881   SemaRef.Context.getInjectedClassNameType(
1882       RecordInst, Inst->getInjectedClassNameSpecialization());
1883 
1884   // Finish handling of friends.
1885   if (isFriend) {
1886     DC->makeDeclVisibleInContext(Inst);
1887     return Inst;
1888   }
1889 
1890   if (D->isOutOfLine()) {
1891     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1892     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1893   }
1894 
1895   Owner->addDecl(Inst);
1896 
1897   if (!PrevClassTemplate) {
1898     // Queue up any out-of-line partial specializations of this member
1899     // class template; the client will force their instantiation once
1900     // the enclosing class has been instantiated.
1901     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1902     D->getPartialSpecializations(PartialSpecs);
1903     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1904       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1905         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1906   }
1907 
1908   return Inst;
1909 }
1910 
1911 Decl *
1912 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1913                                    ClassTemplatePartialSpecializationDecl *D) {
1914   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1915 
1916   // Lookup the already-instantiated declaration in the instantiation
1917   // of the class template and return that.
1918   DeclContext::lookup_result Found
1919     = Owner->lookup(ClassTemplate->getDeclName());
1920   if (Found.empty())
1921     return nullptr;
1922 
1923   ClassTemplateDecl *InstClassTemplate
1924     = dyn_cast<ClassTemplateDecl>(Found.front());
1925   if (!InstClassTemplate)
1926     return nullptr;
1927 
1928   if (ClassTemplatePartialSpecializationDecl *Result
1929         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1930     return Result;
1931 
1932   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1933 }
1934 
1935 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1936   assert(D->getTemplatedDecl()->isStaticDataMember() &&
1937          "Only static data member templates are allowed.");
1938 
1939   // Create a local instantiation scope for this variable template, which
1940   // will contain the instantiations of the template parameters.
1941   LocalInstantiationScope Scope(SemaRef);
1942   TemplateParameterList *TempParams = D->getTemplateParameters();
1943   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1944   if (!InstParams)
1945     return nullptr;
1946 
1947   VarDecl *Pattern = D->getTemplatedDecl();
1948   VarTemplateDecl *PrevVarTemplate = nullptr;
1949 
1950   if (getPreviousDeclForInstantiation(Pattern)) {
1951     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1952     if (!Found.empty())
1953       PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1954   }
1955 
1956   VarDecl *VarInst =
1957       cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1958                                          /*InstantiatingVarTemplate=*/true));
1959   if (!VarInst) return nullptr;
1960 
1961   DeclContext *DC = Owner;
1962 
1963   VarTemplateDecl *Inst = VarTemplateDecl::Create(
1964       SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1965       VarInst);
1966   VarInst->setDescribedVarTemplate(Inst);
1967   Inst->setPreviousDecl(PrevVarTemplate);
1968 
1969   Inst->setAccess(D->getAccess());
1970   if (!PrevVarTemplate)
1971     Inst->setInstantiatedFromMemberTemplate(D);
1972 
1973   if (D->isOutOfLine()) {
1974     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1975     VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1976   }
1977 
1978   Owner->addDecl(Inst);
1979 
1980   if (!PrevVarTemplate) {
1981     // Queue up any out-of-line partial specializations of this member
1982     // variable template; the client will force their instantiation once
1983     // the enclosing class has been instantiated.
1984     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1985     D->getPartialSpecializations(PartialSpecs);
1986     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1987       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1988         OutOfLineVarPartialSpecs.push_back(
1989             std::make_pair(Inst, PartialSpecs[I]));
1990   }
1991 
1992   return Inst;
1993 }
1994 
1995 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1996     VarTemplatePartialSpecializationDecl *D) {
1997   assert(D->isStaticDataMember() &&
1998          "Only static data member templates are allowed.");
1999 
2000   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2001 
2002   // Lookup the already-instantiated declaration and return that.
2003   DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
2004   assert(!Found.empty() && "Instantiation found nothing?");
2005 
2006   VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2007   assert(InstVarTemplate && "Instantiation did not find a variable template?");
2008 
2009   if (VarTemplatePartialSpecializationDecl *Result =
2010           InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
2011     return Result;
2012 
2013   return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
2014 }
2015 
2016 Decl *
2017 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2018   // Create a local instantiation scope for this function template, which
2019   // will contain the instantiations of the template parameters and then get
2020   // merged with the local instantiation scope for the function template
2021   // itself.
2022   LocalInstantiationScope Scope(SemaRef);
2023   Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
2024 
2025   TemplateParameterList *TempParams = D->getTemplateParameters();
2026   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2027   if (!InstParams)
2028     return nullptr;
2029 
2030   FunctionDecl *Instantiated = nullptr;
2031   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
2032     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
2033                                                                  InstParams));
2034   else
2035     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
2036                                                           D->getTemplatedDecl(),
2037                                                                 InstParams));
2038 
2039   if (!Instantiated)
2040     return nullptr;
2041 
2042   // Link the instantiated function template declaration to the function
2043   // template from which it was instantiated.
2044   FunctionTemplateDecl *InstTemplate
2045     = Instantiated->getDescribedFunctionTemplate();
2046   InstTemplate->setAccess(D->getAccess());
2047   assert(InstTemplate &&
2048          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
2049 
2050   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2051 
2052   // Link the instantiation back to the pattern *unless* this is a
2053   // non-definition friend declaration.
2054   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2055       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2056     InstTemplate->setInstantiatedFromMemberTemplate(D);
2057 
2058   // Make declarations visible in the appropriate context.
2059   if (!isFriend) {
2060     Owner->addDecl(InstTemplate);
2061   } else if (InstTemplate->getDeclContext()->isRecord() &&
2062              !getPreviousDeclForInstantiation(D)) {
2063     SemaRef.CheckFriendAccess(InstTemplate);
2064   }
2065 
2066   return InstTemplate;
2067 }
2068 
2069 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2070   CXXRecordDecl *PrevDecl = nullptr;
2071   if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2072     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2073                                                    PatternPrev,
2074                                                    TemplateArgs);
2075     if (!Prev) return nullptr;
2076     PrevDecl = cast<CXXRecordDecl>(Prev);
2077   }
2078 
2079   CXXRecordDecl *Record = nullptr;
2080   bool IsInjectedClassName = D->isInjectedClassName();
2081   if (D->isLambda())
2082     Record = CXXRecordDecl::CreateLambda(
2083         SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2084         D->getLambdaDependencyKind(), D->isGenericLambda(),
2085         D->getLambdaCaptureDefault());
2086   else
2087     Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2088                                    D->getBeginLoc(), D->getLocation(),
2089                                    D->getIdentifier(), PrevDecl,
2090                                    /*DelayTypeCreation=*/IsInjectedClassName);
2091   // Link the type of the injected-class-name to that of the outer class.
2092   if (IsInjectedClassName)
2093     (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
2094 
2095   // Substitute the nested name specifier, if any.
2096   if (SubstQualifier(D, Record))
2097     return nullptr;
2098 
2099   SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2100                                                               StartingScope);
2101 
2102   Record->setImplicit(D->isImplicit());
2103   // FIXME: Check against AS_none is an ugly hack to work around the issue that
2104   // the tag decls introduced by friend class declarations don't have an access
2105   // specifier. Remove once this area of the code gets sorted out.
2106   if (D->getAccess() != AS_none)
2107     Record->setAccess(D->getAccess());
2108   if (!IsInjectedClassName)
2109     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2110 
2111   // If the original function was part of a friend declaration,
2112   // inherit its namespace state.
2113   if (D->getFriendObjectKind())
2114     Record->setObjectOfFriendDecl();
2115 
2116   // Make sure that anonymous structs and unions are recorded.
2117   if (D->isAnonymousStructOrUnion())
2118     Record->setAnonymousStructOrUnion(true);
2119 
2120   if (D->isLocalClass())
2121     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
2122 
2123   // Forward the mangling number from the template to the instantiated decl.
2124   SemaRef.Context.setManglingNumber(Record,
2125                                     SemaRef.Context.getManglingNumber(D));
2126 
2127   // See if the old tag was defined along with a declarator.
2128   // If it did, mark the new tag as being associated with that declarator.
2129   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
2130     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
2131 
2132   // See if the old tag was defined along with a typedef.
2133   // If it did, mark the new tag as being associated with that typedef.
2134   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
2135     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
2136 
2137   Owner->addDecl(Record);
2138 
2139   // DR1484 clarifies that the members of a local class are instantiated as part
2140   // of the instantiation of their enclosing entity.
2141   if (D->isCompleteDefinition() && D->isLocalClass()) {
2142     Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2143 
2144     SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2145                              TSK_ImplicitInstantiation,
2146                              /*Complain=*/true);
2147 
2148     // For nested local classes, we will instantiate the members when we
2149     // reach the end of the outermost (non-nested) local class.
2150     if (!D->isCXXClassMember())
2151       SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2152                                       TSK_ImplicitInstantiation);
2153 
2154     // This class may have local implicit instantiations that need to be
2155     // performed within this scope.
2156     LocalInstantiations.perform();
2157   }
2158 
2159   SemaRef.DiagnoseUnusedNestedTypedefs(Record);
2160 
2161   if (IsInjectedClassName)
2162     assert(Record->isInjectedClassName() && "Broken injected-class-name");
2163 
2164   return Record;
2165 }
2166 
2167 /// Adjust the given function type for an instantiation of the
2168 /// given declaration, to cope with modifications to the function's type that
2169 /// aren't reflected in the type-source information.
2170 ///
2171 /// \param D The declaration we're instantiating.
2172 /// \param TInfo The already-instantiated type.
2173 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
2174                                                    FunctionDecl *D,
2175                                                    TypeSourceInfo *TInfo) {
2176   const FunctionProtoType *OrigFunc
2177     = D->getType()->castAs<FunctionProtoType>();
2178   const FunctionProtoType *NewFunc
2179     = TInfo->getType()->castAs<FunctionProtoType>();
2180   if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2181     return TInfo->getType();
2182 
2183   FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2184   NewEPI.ExtInfo = OrigFunc->getExtInfo();
2185   return Context.getFunctionType(NewFunc->getReturnType(),
2186                                  NewFunc->getParamTypes(), NewEPI);
2187 }
2188 
2189 /// Normal class members are of more specific types and therefore
2190 /// don't make it here.  This function serves three purposes:
2191 ///   1) instantiating function templates
2192 ///   2) substituting friend and local function declarations
2193 ///   3) substituting deduction guide declarations for nested class templates
2194 Decl *TemplateDeclInstantiator::VisitFunctionDecl(
2195     FunctionDecl *D, TemplateParameterList *TemplateParams,
2196     RewriteKind FunctionRewriteKind) {
2197   // Check whether there is already a function template specialization for
2198   // this declaration.
2199   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2200   bool isFriend;
2201   if (FunctionTemplate)
2202     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2203   else
2204     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2205 
2206   // Friend function defined withing class template may stop being function
2207   // definition during AST merges from different modules, in this case decl
2208   // with function body should be used for instantiation.
2209   if (isFriend) {
2210     const FunctionDecl *Defn = nullptr;
2211     if (D->hasBody(Defn)) {
2212       D = const_cast<FunctionDecl *>(Defn);
2213       FunctionTemplate = Defn->getDescribedFunctionTemplate();
2214     }
2215   }
2216 
2217   if (FunctionTemplate && !TemplateParams) {
2218     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2219 
2220     void *InsertPos = nullptr;
2221     FunctionDecl *SpecFunc
2222       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2223 
2224     // If we already have a function template specialization, return it.
2225     if (SpecFunc)
2226       return SpecFunc;
2227   }
2228 
2229   bool MergeWithParentScope = (TemplateParams != nullptr) ||
2230     Owner->isFunctionOrMethod() ||
2231     !(isa<Decl>(Owner) &&
2232       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2233   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2234 
2235   ExplicitSpecifier InstantiatedExplicitSpecifier;
2236   if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2237     InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2238         TemplateArgs, DGuide->getExplicitSpecifier());
2239     if (InstantiatedExplicitSpecifier.isInvalid())
2240       return nullptr;
2241   }
2242 
2243   SmallVector<ParmVarDecl *, 4> Params;
2244   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2245   if (!TInfo)
2246     return nullptr;
2247   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2248 
2249   if (TemplateParams && TemplateParams->size()) {
2250     auto *LastParam =
2251         dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2252     if (LastParam && LastParam->isImplicit() &&
2253         LastParam->hasTypeConstraint()) {
2254       // In abbreviated templates, the type-constraints of invented template
2255       // type parameters are instantiated with the function type, invalidating
2256       // the TemplateParameterList which relied on the template type parameter
2257       // not having a type constraint. Recreate the TemplateParameterList with
2258       // the updated parameter list.
2259       TemplateParams = TemplateParameterList::Create(
2260           SemaRef.Context, TemplateParams->getTemplateLoc(),
2261           TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2262           TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2263     }
2264   }
2265 
2266   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2267   if (QualifierLoc) {
2268     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2269                                                        TemplateArgs);
2270     if (!QualifierLoc)
2271       return nullptr;
2272   }
2273 
2274   Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2275 
2276   // If we're instantiating a local function declaration, put the result
2277   // in the enclosing namespace; otherwise we need to find the instantiated
2278   // context.
2279   DeclContext *DC;
2280   if (D->isLocalExternDecl()) {
2281     DC = Owner;
2282     SemaRef.adjustContextForLocalExternDecl(DC);
2283   } else if (isFriend && QualifierLoc) {
2284     CXXScopeSpec SS;
2285     SS.Adopt(QualifierLoc);
2286     DC = SemaRef.computeDeclContext(SS);
2287     if (!DC) return nullptr;
2288   } else {
2289     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2290                                          TemplateArgs);
2291   }
2292 
2293   DeclarationNameInfo NameInfo
2294     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2295 
2296   if (FunctionRewriteKind != RewriteKind::None)
2297     adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2298 
2299   FunctionDecl *Function;
2300   if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2301     Function = CXXDeductionGuideDecl::Create(
2302         SemaRef.Context, DC, D->getInnerLocStart(),
2303         InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2304         D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2305         DGuide->getDeductionCandidateKind(), TrailingRequiresClause,
2306         DGuide->getSourceDeductionGuide(),
2307         DGuide->getSourceDeductionGuideKind());
2308     Function->setAccess(D->getAccess());
2309   } else {
2310     Function = FunctionDecl::Create(
2311         SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2312         D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2313         D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2314         TrailingRequiresClause);
2315     Function->setFriendConstraintRefersToEnclosingTemplate(
2316         D->FriendConstraintRefersToEnclosingTemplate());
2317     Function->setRangeEnd(D->getSourceRange().getEnd());
2318   }
2319 
2320   if (D->isInlined())
2321     Function->setImplicitlyInline();
2322 
2323   if (QualifierLoc)
2324     Function->setQualifierInfo(QualifierLoc);
2325 
2326   if (D->isLocalExternDecl())
2327     Function->setLocalExternDecl();
2328 
2329   DeclContext *LexicalDC = Owner;
2330   if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2331     assert(D->getDeclContext()->isFileContext());
2332     LexicalDC = D->getDeclContext();
2333   }
2334   else if (D->isLocalExternDecl()) {
2335     LexicalDC = SemaRef.CurContext;
2336   }
2337 
2338   Function->setLexicalDeclContext(LexicalDC);
2339 
2340   // Attach the parameters
2341   for (unsigned P = 0; P < Params.size(); ++P)
2342     if (Params[P])
2343       Params[P]->setOwningFunction(Function);
2344   Function->setParams(Params);
2345 
2346   if (TrailingRequiresClause)
2347     Function->setTrailingRequiresClause(TrailingRequiresClause);
2348 
2349   if (TemplateParams) {
2350     // Our resulting instantiation is actually a function template, since we
2351     // are substituting only the outer template parameters. For example, given
2352     //
2353     //   template<typename T>
2354     //   struct X {
2355     //     template<typename U> friend void f(T, U);
2356     //   };
2357     //
2358     //   X<int> x;
2359     //
2360     // We are instantiating the friend function template "f" within X<int>,
2361     // which means substituting int for T, but leaving "f" as a friend function
2362     // template.
2363     // Build the function template itself.
2364     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2365                                                     Function->getLocation(),
2366                                                     Function->getDeclName(),
2367                                                     TemplateParams, Function);
2368     Function->setDescribedFunctionTemplate(FunctionTemplate);
2369 
2370     FunctionTemplate->setLexicalDeclContext(LexicalDC);
2371 
2372     if (isFriend && D->isThisDeclarationADefinition()) {
2373       FunctionTemplate->setInstantiatedFromMemberTemplate(
2374                                            D->getDescribedFunctionTemplate());
2375     }
2376   } else if (FunctionTemplate &&
2377              SemaRef.CodeSynthesisContexts.back().Kind !=
2378                  Sema::CodeSynthesisContext::BuildingDeductionGuides) {
2379     // Record this function template specialization.
2380     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2381     Function->setFunctionTemplateSpecialization(FunctionTemplate,
2382                             TemplateArgumentList::CreateCopy(SemaRef.Context,
2383                                                              Innermost),
2384                                                 /*InsertPos=*/nullptr);
2385   } else if (FunctionRewriteKind == RewriteKind::None) {
2386     if (isFriend && D->isThisDeclarationADefinition()) {
2387       // Do not connect the friend to the template unless it's actually a
2388       // definition. We don't want non-template functions to be marked as being
2389       // template instantiations.
2390       Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2391     } else if (!isFriend) {
2392       // If this is not a function template, and this is not a friend (that is,
2393       // this is a locally declared function), save the instantiation
2394       // relationship for the purposes of constraint instantiation.
2395       Function->setInstantiatedFromDecl(D);
2396     }
2397   }
2398 
2399   if (isFriend) {
2400     Function->setObjectOfFriendDecl();
2401     if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2402       FT->setObjectOfFriendDecl();
2403   }
2404 
2405   if (InitFunctionInstantiation(Function, D))
2406     Function->setInvalidDecl();
2407 
2408   bool IsExplicitSpecialization = false;
2409 
2410   LookupResult Previous(
2411       SemaRef, Function->getDeclName(), SourceLocation(),
2412       D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2413                              : Sema::LookupOrdinaryName,
2414       D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
2415                              : SemaRef.forRedeclarationInCurContext());
2416 
2417   if (DependentFunctionTemplateSpecializationInfo *DFTSI =
2418           D->getDependentSpecializationInfo()) {
2419     assert(isFriend && "dependent specialization info on "
2420                        "non-member non-friend function?");
2421 
2422     // Instantiate the explicit template arguments.
2423     TemplateArgumentListInfo ExplicitArgs;
2424     if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2425       ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2426       ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2427       if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2428                                          ExplicitArgs))
2429         return nullptr;
2430     }
2431 
2432     // Map the candidates for the primary template to their instantiations.
2433     for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2434       if (NamedDecl *ND =
2435               SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2436         Previous.addDecl(ND);
2437       else
2438         return nullptr;
2439     }
2440 
2441     if (SemaRef.CheckFunctionTemplateSpecialization(
2442             Function,
2443             DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2444             Previous))
2445       Function->setInvalidDecl();
2446 
2447     IsExplicitSpecialization = true;
2448   } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2449                  D->getTemplateSpecializationArgsAsWritten()) {
2450     // The name of this function was written as a template-id.
2451     SemaRef.LookupQualifiedName(Previous, DC);
2452 
2453     // Instantiate the explicit template arguments.
2454     TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2455                                           ArgsWritten->getRAngleLoc());
2456     if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2457                                        ExplicitArgs))
2458       return nullptr;
2459 
2460     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2461                                                     &ExplicitArgs,
2462                                                     Previous))
2463       Function->setInvalidDecl();
2464 
2465     IsExplicitSpecialization = true;
2466   } else if (TemplateParams || !FunctionTemplate) {
2467     // Look only into the namespace where the friend would be declared to
2468     // find a previous declaration. This is the innermost enclosing namespace,
2469     // as described in ActOnFriendFunctionDecl.
2470     SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2471 
2472     // In C++, the previous declaration we find might be a tag type
2473     // (class or enum). In this case, the new declaration will hide the
2474     // tag type. Note that this does not apply if we're declaring a
2475     // typedef (C++ [dcl.typedef]p4).
2476     if (Previous.isSingleTagDecl())
2477       Previous.clear();
2478 
2479     // Filter out previous declarations that don't match the scope. The only
2480     // effect this has is to remove declarations found in inline namespaces
2481     // for friend declarations with unqualified names.
2482     if (isFriend && !QualifierLoc) {
2483       SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2484                                    /*ConsiderLinkage=*/ true,
2485                                    QualifierLoc.hasQualifier());
2486     }
2487   }
2488 
2489   // Per [temp.inst], default arguments in function declarations at local scope
2490   // are instantiated along with the enclosing declaration. For example:
2491   //
2492   //   template<typename T>
2493   //   void ft() {
2494   //     void f(int = []{ return T::value; }());
2495   //   }
2496   //   template void ft<int>(); // error: type 'int' cannot be used prior
2497   //                                      to '::' because it has no members
2498   //
2499   // The error is issued during instantiation of ft<int>() because substitution
2500   // into the default argument fails; the default argument is instantiated even
2501   // though it is never used.
2502   if (Function->isLocalExternDecl()) {
2503     for (ParmVarDecl *PVD : Function->parameters()) {
2504       if (!PVD->hasDefaultArg())
2505         continue;
2506       if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2507         // If substitution fails, the default argument is set to a
2508         // RecoveryExpr that wraps the uninstantiated default argument so
2509         // that downstream diagnostics are omitted.
2510         Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2511         ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2512             UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2513             { UninstExpr }, UninstExpr->getType());
2514         if (ErrorResult.isUsable())
2515           PVD->setDefaultArg(ErrorResult.get());
2516       }
2517     }
2518   }
2519 
2520   SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2521                                    IsExplicitSpecialization,
2522                                    Function->isThisDeclarationADefinition());
2523 
2524   // Check the template parameter list against the previous declaration. The
2525   // goal here is to pick up default arguments added since the friend was
2526   // declared; we know the template parameter lists match, since otherwise
2527   // we would not have picked this template as the previous declaration.
2528   if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2529     SemaRef.CheckTemplateParameterList(
2530         TemplateParams,
2531         FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2532         Function->isThisDeclarationADefinition()
2533             ? Sema::TPC_FriendFunctionTemplateDefinition
2534             : Sema::TPC_FriendFunctionTemplate);
2535   }
2536 
2537   // If we're introducing a friend definition after the first use, trigger
2538   // instantiation.
2539   // FIXME: If this is a friend function template definition, we should check
2540   // to see if any specializations have been used.
2541   if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2542     if (MemberSpecializationInfo *MSInfo =
2543             Function->getMemberSpecializationInfo()) {
2544       if (MSInfo->getPointOfInstantiation().isInvalid()) {
2545         SourceLocation Loc = D->getLocation(); // FIXME
2546         MSInfo->setPointOfInstantiation(Loc);
2547         SemaRef.PendingLocalImplicitInstantiations.push_back(
2548             std::make_pair(Function, Loc));
2549       }
2550     }
2551   }
2552 
2553   if (D->isExplicitlyDefaulted()) {
2554     if (SubstDefaultedFunction(Function, D))
2555       return nullptr;
2556   }
2557   if (D->isDeleted())
2558     SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
2559 
2560   NamedDecl *PrincipalDecl =
2561       (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2562 
2563   // If this declaration lives in a different context from its lexical context,
2564   // add it to the corresponding lookup table.
2565   if (isFriend ||
2566       (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2567     DC->makeDeclVisibleInContext(PrincipalDecl);
2568 
2569   if (Function->isOverloadedOperator() && !DC->isRecord() &&
2570       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2571     PrincipalDecl->setNonMemberOperator();
2572 
2573   return Function;
2574 }
2575 
2576 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2577     CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2578     RewriteKind FunctionRewriteKind) {
2579   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2580   if (FunctionTemplate && !TemplateParams) {
2581     // We are creating a function template specialization from a function
2582     // template. Check whether there is already a function template
2583     // specialization for this particular set of template arguments.
2584     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2585 
2586     void *InsertPos = nullptr;
2587     FunctionDecl *SpecFunc
2588       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2589 
2590     // If we already have a function template specialization, return it.
2591     if (SpecFunc)
2592       return SpecFunc;
2593   }
2594 
2595   bool isFriend;
2596   if (FunctionTemplate)
2597     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2598   else
2599     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2600 
2601   bool MergeWithParentScope = (TemplateParams != nullptr) ||
2602     !(isa<Decl>(Owner) &&
2603       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2604   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2605 
2606   Sema::LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
2607       SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
2608 
2609   // Instantiate enclosing template arguments for friends.
2610   SmallVector<TemplateParameterList *, 4> TempParamLists;
2611   unsigned NumTempParamLists = 0;
2612   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2613     TempParamLists.resize(NumTempParamLists);
2614     for (unsigned I = 0; I != NumTempParamLists; ++I) {
2615       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2616       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2617       if (!InstParams)
2618         return nullptr;
2619       TempParamLists[I] = InstParams;
2620     }
2621   }
2622 
2623   auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
2624   // deduction guides need this
2625   const bool CouldInstantiate =
2626       InstantiatedExplicitSpecifier.getExpr() == nullptr ||
2627       !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
2628 
2629   // Delay the instantiation of the explicit-specifier until after the
2630   // constraints are checked during template argument deduction.
2631   if (CouldInstantiate ||
2632       SemaRef.CodeSynthesisContexts.back().Kind !=
2633           Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution) {
2634     InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2635         TemplateArgs, InstantiatedExplicitSpecifier);
2636 
2637     if (InstantiatedExplicitSpecifier.isInvalid())
2638       return nullptr;
2639   } else {
2640     InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
2641   }
2642 
2643   // Implicit destructors/constructors created for local classes in
2644   // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2645   // Unfortunately there isn't enough context in those functions to
2646   // conditionally populate the TSI without breaking non-template related use
2647   // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2648   // a proper transformation.
2649   if (isLambdaMethod(D) && !D->getTypeSourceInfo() &&
2650       isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2651     TypeSourceInfo *TSI =
2652         SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2653     D->setTypeSourceInfo(TSI);
2654   }
2655 
2656   SmallVector<ParmVarDecl *, 4> Params;
2657   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2658   if (!TInfo)
2659     return nullptr;
2660   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2661 
2662   if (TemplateParams && TemplateParams->size()) {
2663     auto *LastParam =
2664         dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2665     if (LastParam && LastParam->isImplicit() &&
2666         LastParam->hasTypeConstraint()) {
2667       // In abbreviated templates, the type-constraints of invented template
2668       // type parameters are instantiated with the function type, invalidating
2669       // the TemplateParameterList which relied on the template type parameter
2670       // not having a type constraint. Recreate the TemplateParameterList with
2671       // the updated parameter list.
2672       TemplateParams = TemplateParameterList::Create(
2673           SemaRef.Context, TemplateParams->getTemplateLoc(),
2674           TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2675           TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2676     }
2677   }
2678 
2679   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2680   if (QualifierLoc) {
2681     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2682                                                  TemplateArgs);
2683     if (!QualifierLoc)
2684       return nullptr;
2685   }
2686 
2687   DeclContext *DC = Owner;
2688   if (isFriend) {
2689     if (QualifierLoc) {
2690       CXXScopeSpec SS;
2691       SS.Adopt(QualifierLoc);
2692       DC = SemaRef.computeDeclContext(SS);
2693 
2694       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2695         return nullptr;
2696     } else {
2697       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2698                                            D->getDeclContext(),
2699                                            TemplateArgs);
2700     }
2701     if (!DC) return nullptr;
2702   }
2703 
2704   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2705   Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2706 
2707   DeclarationNameInfo NameInfo
2708     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2709 
2710   if (FunctionRewriteKind != RewriteKind::None)
2711     adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2712 
2713   // Build the instantiated method declaration.
2714   CXXMethodDecl *Method = nullptr;
2715 
2716   SourceLocation StartLoc = D->getInnerLocStart();
2717   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2718     Method = CXXConstructorDecl::Create(
2719         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2720         InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2721         Constructor->isInlineSpecified(), false,
2722         Constructor->getConstexprKind(), InheritedConstructor(),
2723         TrailingRequiresClause);
2724     Method->setRangeEnd(Constructor->getEndLoc());
2725   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2726     Method = CXXDestructorDecl::Create(
2727         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2728         Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2729         Destructor->getConstexprKind(), TrailingRequiresClause);
2730     Method->setIneligibleOrNotSelected(true);
2731     Method->setRangeEnd(Destructor->getEndLoc());
2732     Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2733         SemaRef.Context.getCanonicalType(
2734             SemaRef.Context.getTypeDeclType(Record))));
2735   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2736     Method = CXXConversionDecl::Create(
2737         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2738         Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2739         InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2740         Conversion->getEndLoc(), TrailingRequiresClause);
2741   } else {
2742     StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2743     Method = CXXMethodDecl::Create(
2744         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2745         D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2746         D->getEndLoc(), TrailingRequiresClause);
2747   }
2748 
2749   if (D->isInlined())
2750     Method->setImplicitlyInline();
2751 
2752   if (QualifierLoc)
2753     Method->setQualifierInfo(QualifierLoc);
2754 
2755   if (TemplateParams) {
2756     // Our resulting instantiation is actually a function template, since we
2757     // are substituting only the outer template parameters. For example, given
2758     //
2759     //   template<typename T>
2760     //   struct X {
2761     //     template<typename U> void f(T, U);
2762     //   };
2763     //
2764     //   X<int> x;
2765     //
2766     // We are instantiating the member template "f" within X<int>, which means
2767     // substituting int for T, but leaving "f" as a member function template.
2768     // Build the function template itself.
2769     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2770                                                     Method->getLocation(),
2771                                                     Method->getDeclName(),
2772                                                     TemplateParams, Method);
2773     if (isFriend) {
2774       FunctionTemplate->setLexicalDeclContext(Owner);
2775       FunctionTemplate->setObjectOfFriendDecl();
2776     } else if (D->isOutOfLine())
2777       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2778     Method->setDescribedFunctionTemplate(FunctionTemplate);
2779   } else if (FunctionTemplate) {
2780     // Record this function template specialization.
2781     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2782     Method->setFunctionTemplateSpecialization(FunctionTemplate,
2783                          TemplateArgumentList::CreateCopy(SemaRef.Context,
2784                                                           Innermost),
2785                                               /*InsertPos=*/nullptr);
2786   } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
2787     // Record that this is an instantiation of a member function.
2788     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2789   }
2790 
2791   // If we are instantiating a member function defined
2792   // out-of-line, the instantiation will have the same lexical
2793   // context (which will be a namespace scope) as the template.
2794   if (isFriend) {
2795     if (NumTempParamLists)
2796       Method->setTemplateParameterListsInfo(
2797           SemaRef.Context,
2798           llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2799 
2800     Method->setLexicalDeclContext(Owner);
2801     Method->setObjectOfFriendDecl();
2802   } else if (D->isOutOfLine())
2803     Method->setLexicalDeclContext(D->getLexicalDeclContext());
2804 
2805   // Attach the parameters
2806   for (unsigned P = 0; P < Params.size(); ++P)
2807     Params[P]->setOwningFunction(Method);
2808   Method->setParams(Params);
2809 
2810   if (InitMethodInstantiation(Method, D))
2811     Method->setInvalidDecl();
2812 
2813   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2814                         RedeclarationKind::ForExternalRedeclaration);
2815 
2816   bool IsExplicitSpecialization = false;
2817 
2818   // If the name of this function was written as a template-id, instantiate
2819   // the explicit template arguments.
2820   if (DependentFunctionTemplateSpecializationInfo *DFTSI =
2821           D->getDependentSpecializationInfo()) {
2822     // Instantiate the explicit template arguments.
2823     TemplateArgumentListInfo ExplicitArgs;
2824     if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2825       ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2826       ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2827       if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2828                                          ExplicitArgs))
2829         return nullptr;
2830     }
2831 
2832     // Map the candidates for the primary template to their instantiations.
2833     for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2834       if (NamedDecl *ND =
2835               SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2836         Previous.addDecl(ND);
2837       else
2838         return nullptr;
2839     }
2840 
2841     if (SemaRef.CheckFunctionTemplateSpecialization(
2842             Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2843             Previous))
2844       Method->setInvalidDecl();
2845 
2846     IsExplicitSpecialization = true;
2847   } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2848                  D->getTemplateSpecializationArgsAsWritten()) {
2849     SemaRef.LookupQualifiedName(Previous, DC);
2850 
2851     TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2852                                           ArgsWritten->getRAngleLoc());
2853 
2854     if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2855                                        ExplicitArgs))
2856       return nullptr;
2857 
2858     if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2859                                                     &ExplicitArgs,
2860                                                     Previous))
2861       Method->setInvalidDecl();
2862 
2863     IsExplicitSpecialization = true;
2864   } else if (!FunctionTemplate || TemplateParams || isFriend) {
2865     SemaRef.LookupQualifiedName(Previous, Record);
2866 
2867     // In C++, the previous declaration we find might be a tag type
2868     // (class or enum). In this case, the new declaration will hide the
2869     // tag type. Note that this does not apply if we're declaring a
2870     // typedef (C++ [dcl.typedef]p4).
2871     if (Previous.isSingleTagDecl())
2872       Previous.clear();
2873   }
2874 
2875   // Per [temp.inst], default arguments in member functions of local classes
2876   // are instantiated along with the member function declaration. For example:
2877   //
2878   //   template<typename T>
2879   //   void ft() {
2880   //     struct lc {
2881   //       int operator()(int p = []{ return T::value; }());
2882   //     };
2883   //   }
2884   //   template void ft<int>(); // error: type 'int' cannot be used prior
2885   //                                      to '::'because it has no members
2886   //
2887   // The error is issued during instantiation of ft<int>()::lc::operator()
2888   // because substitution into the default argument fails; the default argument
2889   // is instantiated even though it is never used.
2890   if (D->isInLocalScopeForInstantiation()) {
2891     for (unsigned P = 0; P < Params.size(); ++P) {
2892       if (!Params[P]->hasDefaultArg())
2893         continue;
2894       if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2895         // If substitution fails, the default argument is set to a
2896         // RecoveryExpr that wraps the uninstantiated default argument so
2897         // that downstream diagnostics are omitted.
2898         Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2899         ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2900             UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2901             { UninstExpr }, UninstExpr->getType());
2902         if (ErrorResult.isUsable())
2903           Params[P]->setDefaultArg(ErrorResult.get());
2904       }
2905     }
2906   }
2907 
2908   SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2909                                    IsExplicitSpecialization,
2910                                    Method->isThisDeclarationADefinition());
2911 
2912   if (D->isPureVirtual())
2913     SemaRef.CheckPureMethod(Method, SourceRange());
2914 
2915   // Propagate access.  For a non-friend declaration, the access is
2916   // whatever we're propagating from.  For a friend, it should be the
2917   // previous declaration we just found.
2918   if (isFriend && Method->getPreviousDecl())
2919     Method->setAccess(Method->getPreviousDecl()->getAccess());
2920   else
2921     Method->setAccess(D->getAccess());
2922   if (FunctionTemplate)
2923     FunctionTemplate->setAccess(Method->getAccess());
2924 
2925   SemaRef.CheckOverrideControl(Method);
2926 
2927   // If a function is defined as defaulted or deleted, mark it as such now.
2928   if (D->isExplicitlyDefaulted()) {
2929     if (SubstDefaultedFunction(Method, D))
2930       return nullptr;
2931   }
2932   if (D->isDeletedAsWritten())
2933     SemaRef.SetDeclDeleted(Method, Method->getLocation(),
2934                            D->getDeletedMessage());
2935 
2936   // If this is an explicit specialization, mark the implicitly-instantiated
2937   // template specialization as being an explicit specialization too.
2938   // FIXME: Is this necessary?
2939   if (IsExplicitSpecialization && !isFriend)
2940     SemaRef.CompleteMemberSpecialization(Method, Previous);
2941 
2942   // If the method is a special member function, we need to mark it as
2943   // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2944   // At the end of the class instantiation, we calculate eligibility again and
2945   // then we adjust trivility if needed.
2946   // We need this check to happen only after the method parameters are set,
2947   // because being e.g. a copy constructor depends on the instantiated
2948   // arguments.
2949   if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2950     if (Constructor->isDefaultConstructor() ||
2951         Constructor->isCopyOrMoveConstructor())
2952       Method->setIneligibleOrNotSelected(true);
2953   } else if (Method->isCopyAssignmentOperator() ||
2954              Method->isMoveAssignmentOperator()) {
2955     Method->setIneligibleOrNotSelected(true);
2956   }
2957 
2958   // If there's a function template, let our caller handle it.
2959   if (FunctionTemplate) {
2960     // do nothing
2961 
2962   // Don't hide a (potentially) valid declaration with an invalid one.
2963   } else if (Method->isInvalidDecl() && !Previous.empty()) {
2964     // do nothing
2965 
2966   // Otherwise, check access to friends and make them visible.
2967   } else if (isFriend) {
2968     // We only need to re-check access for methods which we didn't
2969     // manage to match during parsing.
2970     if (!D->getPreviousDecl())
2971       SemaRef.CheckFriendAccess(Method);
2972 
2973     Record->makeDeclVisibleInContext(Method);
2974 
2975   // Otherwise, add the declaration.  We don't need to do this for
2976   // class-scope specializations because we'll have matched them with
2977   // the appropriate template.
2978   } else {
2979     Owner->addDecl(Method);
2980   }
2981 
2982   // PR17480: Honor the used attribute to instantiate member function
2983   // definitions
2984   if (Method->hasAttr<UsedAttr>()) {
2985     if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2986       SourceLocation Loc;
2987       if (const MemberSpecializationInfo *MSInfo =
2988               A->getMemberSpecializationInfo())
2989         Loc = MSInfo->getPointOfInstantiation();
2990       else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2991         Loc = Spec->getPointOfInstantiation();
2992       SemaRef.MarkFunctionReferenced(Loc, Method);
2993     }
2994   }
2995 
2996   return Method;
2997 }
2998 
2999 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3000   return VisitCXXMethodDecl(D);
3001 }
3002 
3003 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3004   return VisitCXXMethodDecl(D);
3005 }
3006 
3007 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
3008   return VisitCXXMethodDecl(D);
3009 }
3010 
3011 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
3012   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
3013                                   std::nullopt,
3014                                   /*ExpectParameterPack=*/false);
3015 }
3016 
3017 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
3018                                                     TemplateTypeParmDecl *D) {
3019   assert(D->getTypeForDecl()->isTemplateTypeParmType());
3020 
3021   std::optional<unsigned> NumExpanded;
3022 
3023   if (const TypeConstraint *TC = D->getTypeConstraint()) {
3024     if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
3025       assert(TC->getTemplateArgsAsWritten() &&
3026              "type parameter can only be an expansion when explicit arguments "
3027              "are specified");
3028       // The template type parameter pack's type is a pack expansion of types.
3029       // Determine whether we need to expand this parameter pack into separate
3030       // types.
3031       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3032       for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3033         SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
3034 
3035       // Determine whether the set of unexpanded parameter packs can and should
3036       // be expanded.
3037       bool Expand = true;
3038       bool RetainExpansion = false;
3039       if (SemaRef.CheckParameterPacksForExpansion(
3040               cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3041                   ->getEllipsisLoc(),
3042               SourceRange(TC->getConceptNameLoc(),
3043                           TC->hasExplicitTemplateArgs() ?
3044                           TC->getTemplateArgsAsWritten()->getRAngleLoc() :
3045                           TC->getConceptNameInfo().getEndLoc()),
3046               Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
3047         return nullptr;
3048     }
3049   }
3050 
3051   TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
3052       SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
3053       D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
3054       D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
3055       D->hasTypeConstraint(), NumExpanded);
3056 
3057   Inst->setAccess(AS_public);
3058   Inst->setImplicit(D->isImplicit());
3059   if (auto *TC = D->getTypeConstraint()) {
3060     if (!D->isImplicit()) {
3061       // Invented template parameter type constraints will be instantiated
3062       // with the corresponding auto-typed parameter as it might reference
3063       // other parameters.
3064       if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3065                                       EvaluateConstraints))
3066         return nullptr;
3067     }
3068   }
3069   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3070     TemplateArgumentLoc Output;
3071     if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3072                                        Output))
3073       Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3074   }
3075 
3076   // Introduce this template parameter's instantiation into the instantiation
3077   // scope.
3078   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3079 
3080   return Inst;
3081 }
3082 
3083 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3084                                                  NonTypeTemplateParmDecl *D) {
3085   // Substitute into the type of the non-type template parameter.
3086   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3087   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3088   SmallVector<QualType, 4> ExpandedParameterPackTypes;
3089   bool IsExpandedParameterPack = false;
3090   TypeSourceInfo *DI;
3091   QualType T;
3092   bool Invalid = false;
3093 
3094   if (D->isExpandedParameterPack()) {
3095     // The non-type template parameter pack is an already-expanded pack
3096     // expansion of types. Substitute into each of the expanded types.
3097     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3098     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3099     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3100       TypeSourceInfo *NewDI =
3101           SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3102                             D->getLocation(), D->getDeclName());
3103       if (!NewDI)
3104         return nullptr;
3105 
3106       QualType NewT =
3107           SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
3108       if (NewT.isNull())
3109         return nullptr;
3110 
3111       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3112       ExpandedParameterPackTypes.push_back(NewT);
3113     }
3114 
3115     IsExpandedParameterPack = true;
3116     DI = D->getTypeSourceInfo();
3117     T = DI->getType();
3118   } else if (D->isPackExpansion()) {
3119     // The non-type template parameter pack's type is a pack expansion of types.
3120     // Determine whether we need to expand this parameter pack into separate
3121     // types.
3122     PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
3123     TypeLoc Pattern = Expansion.getPatternLoc();
3124     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3125     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3126 
3127     // Determine whether the set of unexpanded parameter packs can and should
3128     // be expanded.
3129     bool Expand = true;
3130     bool RetainExpansion = false;
3131     std::optional<unsigned> OrigNumExpansions =
3132         Expansion.getTypePtr()->getNumExpansions();
3133     std::optional<unsigned> NumExpansions = OrigNumExpansions;
3134     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
3135                                                 Pattern.getSourceRange(),
3136                                                 Unexpanded,
3137                                                 TemplateArgs,
3138                                                 Expand, RetainExpansion,
3139                                                 NumExpansions))
3140       return nullptr;
3141 
3142     if (Expand) {
3143       for (unsigned I = 0; I != *NumExpansions; ++I) {
3144         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3145         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
3146                                                   D->getLocation(),
3147                                                   D->getDeclName());
3148         if (!NewDI)
3149           return nullptr;
3150 
3151         QualType NewT =
3152             SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
3153         if (NewT.isNull())
3154           return nullptr;
3155 
3156         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3157         ExpandedParameterPackTypes.push_back(NewT);
3158       }
3159 
3160       // Note that we have an expanded parameter pack. The "type" of this
3161       // expanded parameter pack is the original expansion type, but callers
3162       // will end up using the expanded parameter pack types for type-checking.
3163       IsExpandedParameterPack = true;
3164       DI = D->getTypeSourceInfo();
3165       T = DI->getType();
3166     } else {
3167       // We cannot fully expand the pack expansion now, so substitute into the
3168       // pattern and create a new pack expansion type.
3169       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3170       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3171                                                      D->getLocation(),
3172                                                      D->getDeclName());
3173       if (!NewPattern)
3174         return nullptr;
3175 
3176       SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3177       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3178                                       NumExpansions);
3179       if (!DI)
3180         return nullptr;
3181 
3182       T = DI->getType();
3183     }
3184   } else {
3185     // Simple case: substitution into a parameter that is not a parameter pack.
3186     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3187                            D->getLocation(), D->getDeclName());
3188     if (!DI)
3189       return nullptr;
3190 
3191     // Check that this type is acceptable for a non-type template parameter.
3192     T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
3193     if (T.isNull()) {
3194       T = SemaRef.Context.IntTy;
3195       Invalid = true;
3196     }
3197   }
3198 
3199   NonTypeTemplateParmDecl *Param;
3200   if (IsExpandedParameterPack)
3201     Param = NonTypeTemplateParmDecl::Create(
3202         SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3203         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3204         D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3205         ExpandedParameterPackTypesAsWritten);
3206   else
3207     Param = NonTypeTemplateParmDecl::Create(
3208         SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3209         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3210         D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3211 
3212   if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3213     if (AutoLoc.isConstrained()) {
3214       SourceLocation EllipsisLoc;
3215       if (IsExpandedParameterPack)
3216         EllipsisLoc =
3217             DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3218       else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3219                    D->getPlaceholderTypeConstraint()))
3220         EllipsisLoc = Constraint->getEllipsisLoc();
3221       // Note: We attach the uninstantiated constriant here, so that it can be
3222       // instantiated relative to the top level, like all our other
3223       // constraints.
3224       if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3225                                        /*OrigConstrainedParm=*/D, EllipsisLoc))
3226         Invalid = true;
3227     }
3228 
3229   Param->setAccess(AS_public);
3230   Param->setImplicit(D->isImplicit());
3231   if (Invalid)
3232     Param->setInvalidDecl();
3233 
3234   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3235     EnterExpressionEvaluationContext ConstantEvaluated(
3236         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3237     TemplateArgumentLoc Result;
3238     if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3239                                        Result))
3240       Param->setDefaultArgument(SemaRef.Context, Result);
3241   }
3242 
3243   // Introduce this template parameter's instantiation into the instantiation
3244   // scope.
3245   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3246   return Param;
3247 }
3248 
3249 static void collectUnexpandedParameterPacks(
3250     Sema &S,
3251     TemplateParameterList *Params,
3252     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
3253   for (const auto &P : *Params) {
3254     if (P->isTemplateParameterPack())
3255       continue;
3256     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3257       S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3258                                         Unexpanded);
3259     if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3260       collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3261                                       Unexpanded);
3262   }
3263 }
3264 
3265 Decl *
3266 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3267                                                   TemplateTemplateParmDecl *D) {
3268   // Instantiate the template parameter list of the template template parameter.
3269   TemplateParameterList *TempParams = D->getTemplateParameters();
3270   TemplateParameterList *InstParams;
3271   SmallVector<TemplateParameterList*, 8> ExpandedParams;
3272 
3273   bool IsExpandedParameterPack = false;
3274 
3275   if (D->isExpandedParameterPack()) {
3276     // The template template parameter pack is an already-expanded pack
3277     // expansion of template parameters. Substitute into each of the expanded
3278     // parameters.
3279     ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3280     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3281          I != N; ++I) {
3282       LocalInstantiationScope Scope(SemaRef);
3283       TemplateParameterList *Expansion =
3284         SubstTemplateParams(D->getExpansionTemplateParameters(I));
3285       if (!Expansion)
3286         return nullptr;
3287       ExpandedParams.push_back(Expansion);
3288     }
3289 
3290     IsExpandedParameterPack = true;
3291     InstParams = TempParams;
3292   } else if (D->isPackExpansion()) {
3293     // The template template parameter pack expands to a pack of template
3294     // template parameters. Determine whether we need to expand this parameter
3295     // pack into separate parameters.
3296     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3297     collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3298                                     Unexpanded);
3299 
3300     // Determine whether the set of unexpanded parameter packs can and should
3301     // be expanded.
3302     bool Expand = true;
3303     bool RetainExpansion = false;
3304     std::optional<unsigned> NumExpansions;
3305     if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
3306                                                 TempParams->getSourceRange(),
3307                                                 Unexpanded,
3308                                                 TemplateArgs,
3309                                                 Expand, RetainExpansion,
3310                                                 NumExpansions))
3311       return nullptr;
3312 
3313     if (Expand) {
3314       for (unsigned I = 0; I != *NumExpansions; ++I) {
3315         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3316         LocalInstantiationScope Scope(SemaRef);
3317         TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3318         if (!Expansion)
3319           return nullptr;
3320         ExpandedParams.push_back(Expansion);
3321       }
3322 
3323       // Note that we have an expanded parameter pack. The "type" of this
3324       // expanded parameter pack is the original expansion type, but callers
3325       // will end up using the expanded parameter pack types for type-checking.
3326       IsExpandedParameterPack = true;
3327       InstParams = TempParams;
3328     } else {
3329       // We cannot fully expand the pack expansion now, so just substitute
3330       // into the pattern.
3331       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3332 
3333       LocalInstantiationScope Scope(SemaRef);
3334       InstParams = SubstTemplateParams(TempParams);
3335       if (!InstParams)
3336         return nullptr;
3337     }
3338   } else {
3339     // Perform the actual substitution of template parameters within a new,
3340     // local instantiation scope.
3341     LocalInstantiationScope Scope(SemaRef);
3342     InstParams = SubstTemplateParams(TempParams);
3343     if (!InstParams)
3344       return nullptr;
3345   }
3346 
3347   // Build the template template parameter.
3348   TemplateTemplateParmDecl *Param;
3349   if (IsExpandedParameterPack)
3350     Param = TemplateTemplateParmDecl::Create(
3351         SemaRef.Context, Owner, D->getLocation(),
3352         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3353         D->getPosition(), D->getIdentifier(), D->wasDeclaredWithTypename(),
3354         InstParams, ExpandedParams);
3355   else
3356     Param = TemplateTemplateParmDecl::Create(
3357         SemaRef.Context, Owner, D->getLocation(),
3358         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3359         D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3360         D->wasDeclaredWithTypename(), InstParams);
3361   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3362     NestedNameSpecifierLoc QualifierLoc =
3363         D->getDefaultArgument().getTemplateQualifierLoc();
3364     QualifierLoc =
3365         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3366     TemplateName TName = SemaRef.SubstTemplateName(
3367         QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3368         D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3369     if (!TName.isNull())
3370       Param->setDefaultArgument(
3371           SemaRef.Context,
3372           TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3373                               D->getDefaultArgument().getTemplateQualifierLoc(),
3374                               D->getDefaultArgument().getTemplateNameLoc()));
3375   }
3376   Param->setAccess(AS_public);
3377   Param->setImplicit(D->isImplicit());
3378 
3379   // Introduce this template parameter's instantiation into the instantiation
3380   // scope.
3381   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3382 
3383   return Param;
3384 }
3385 
3386 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3387   // Using directives are never dependent (and never contain any types or
3388   // expressions), so they require no explicit instantiation work.
3389 
3390   UsingDirectiveDecl *Inst
3391     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3392                                  D->getNamespaceKeyLocation(),
3393                                  D->getQualifierLoc(),
3394                                  D->getIdentLocation(),
3395                                  D->getNominatedNamespace(),
3396                                  D->getCommonAncestor());
3397 
3398   // Add the using directive to its declaration context
3399   // only if this is not a function or method.
3400   if (!Owner->isFunctionOrMethod())
3401     Owner->addDecl(Inst);
3402 
3403   return Inst;
3404 }
3405 
3406 Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3407                                                     BaseUsingDecl *Inst,
3408                                                     LookupResult *Lookup) {
3409 
3410   bool isFunctionScope = Owner->isFunctionOrMethod();
3411 
3412   for (auto *Shadow : D->shadows()) {
3413     // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3414     // reconstruct it in the case where it matters. Hm, can we extract it from
3415     // the DeclSpec when parsing and save it in the UsingDecl itself?
3416     NamedDecl *OldTarget = Shadow->getTargetDecl();
3417     if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3418       if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3419         OldTarget = BaseShadow;
3420 
3421     NamedDecl *InstTarget = nullptr;
3422     if (auto *EmptyD =
3423             dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3424       InstTarget = UnresolvedUsingIfExistsDecl::Create(
3425           SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3426     } else {
3427       InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3428           Shadow->getLocation(), OldTarget, TemplateArgs));
3429     }
3430     if (!InstTarget)
3431       return nullptr;
3432 
3433     UsingShadowDecl *PrevDecl = nullptr;
3434     if (Lookup &&
3435         SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3436       continue;
3437 
3438     if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3439       PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3440           Shadow->getLocation(), OldPrev, TemplateArgs));
3441 
3442     UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3443         /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3444     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3445 
3446     if (isFunctionScope)
3447       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3448   }
3449 
3450   return Inst;
3451 }
3452 
3453 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3454 
3455   // The nested name specifier may be dependent, for example
3456   //     template <typename T> struct t {
3457   //       struct s1 { T f1(); };
3458   //       struct s2 : s1 { using s1::f1; };
3459   //     };
3460   //     template struct t<int>;
3461   // Here, in using s1::f1, s1 refers to t<T>::s1;
3462   // we need to substitute for t<int>::s1.
3463   NestedNameSpecifierLoc QualifierLoc
3464     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3465                                           TemplateArgs);
3466   if (!QualifierLoc)
3467     return nullptr;
3468 
3469   // For an inheriting constructor declaration, the name of the using
3470   // declaration is the name of a constructor in this class, not in the
3471   // base class.
3472   DeclarationNameInfo NameInfo = D->getNameInfo();
3473   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3474     if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3475       NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3476           SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3477 
3478   // We only need to do redeclaration lookups if we're in a class scope (in
3479   // fact, it's not really even possible in non-class scopes).
3480   bool CheckRedeclaration = Owner->isRecord();
3481   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3482                     RedeclarationKind::ForVisibleRedeclaration);
3483 
3484   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3485                                        D->getUsingLoc(),
3486                                        QualifierLoc,
3487                                        NameInfo,
3488                                        D->hasTypename());
3489 
3490   CXXScopeSpec SS;
3491   SS.Adopt(QualifierLoc);
3492   if (CheckRedeclaration) {
3493     Prev.setHideTags(false);
3494     SemaRef.LookupQualifiedName(Prev, Owner);
3495 
3496     // Check for invalid redeclarations.
3497     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3498                                             D->hasTypename(), SS,
3499                                             D->getLocation(), Prev))
3500       NewUD->setInvalidDecl();
3501   }
3502 
3503   if (!NewUD->isInvalidDecl() &&
3504       SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3505                                       NameInfo, D->getLocation(), nullptr, D))
3506     NewUD->setInvalidDecl();
3507 
3508   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3509   NewUD->setAccess(D->getAccess());
3510   Owner->addDecl(NewUD);
3511 
3512   // Don't process the shadow decls for an invalid decl.
3513   if (NewUD->isInvalidDecl())
3514     return NewUD;
3515 
3516   // If the using scope was dependent, or we had dependent bases, we need to
3517   // recheck the inheritance
3518   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3519     SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3520 
3521   return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3522 }
3523 
3524 Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3525   // Cannot be a dependent type, but still could be an instantiation
3526   EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3527       D->getLocation(), D->getEnumDecl(), TemplateArgs));
3528 
3529   if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3530     return nullptr;
3531 
3532   TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3533                                           D->getLocation(), D->getDeclName());
3534 
3535   if (!TSI)
3536     return nullptr;
3537 
3538   UsingEnumDecl *NewUD =
3539       UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3540                             D->getEnumLoc(), D->getLocation(), TSI);
3541 
3542   SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3543   NewUD->setAccess(D->getAccess());
3544   Owner->addDecl(NewUD);
3545 
3546   // Don't process the shadow decls for an invalid decl.
3547   if (NewUD->isInvalidDecl())
3548     return NewUD;
3549 
3550   // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3551   // cannot be dependent, and will therefore have been checked during template
3552   // definition.
3553 
3554   return VisitBaseUsingDecls(D, NewUD, nullptr);
3555 }
3556 
3557 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3558   // Ignore these;  we handle them in bulk when processing the UsingDecl.
3559   return nullptr;
3560 }
3561 
3562 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3563     ConstructorUsingShadowDecl *D) {
3564   // Ignore these;  we handle them in bulk when processing the UsingDecl.
3565   return nullptr;
3566 }
3567 
3568 template <typename T>
3569 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3570     T *D, bool InstantiatingPackElement) {
3571   // If this is a pack expansion, expand it now.
3572   if (D->isPackExpansion() && !InstantiatingPackElement) {
3573     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3574     SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3575     SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3576 
3577     // Determine whether the set of unexpanded parameter packs can and should
3578     // be expanded.
3579     bool Expand = true;
3580     bool RetainExpansion = false;
3581     std::optional<unsigned> NumExpansions;
3582     if (SemaRef.CheckParameterPacksForExpansion(
3583           D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3584             Expand, RetainExpansion, NumExpansions))
3585       return nullptr;
3586 
3587     // This declaration cannot appear within a function template signature,
3588     // so we can't have a partial argument list for a parameter pack.
3589     assert(!RetainExpansion &&
3590            "should never need to retain an expansion for UsingPackDecl");
3591 
3592     if (!Expand) {
3593       // We cannot fully expand the pack expansion now, so substitute into the
3594       // pattern and create a new pack expansion.
3595       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3596       return instantiateUnresolvedUsingDecl(D, true);
3597     }
3598 
3599     // Within a function, we don't have any normal way to check for conflicts
3600     // between shadow declarations from different using declarations in the
3601     // same pack expansion, but this is always ill-formed because all expansions
3602     // must produce (conflicting) enumerators.
3603     //
3604     // Sadly we can't just reject this in the template definition because it
3605     // could be valid if the pack is empty or has exactly one expansion.
3606     if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3607       SemaRef.Diag(D->getEllipsisLoc(),
3608                    diag::err_using_decl_redeclaration_expansion);
3609       return nullptr;
3610     }
3611 
3612     // Instantiate the slices of this pack and build a UsingPackDecl.
3613     SmallVector<NamedDecl*, 8> Expansions;
3614     for (unsigned I = 0; I != *NumExpansions; ++I) {
3615       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3616       Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3617       if (!Slice)
3618         return nullptr;
3619       // Note that we can still get unresolved using declarations here, if we
3620       // had arguments for all packs but the pattern also contained other
3621       // template arguments (this only happens during partial substitution, eg
3622       // into the body of a generic lambda in a function template).
3623       Expansions.push_back(cast<NamedDecl>(Slice));
3624     }
3625 
3626     auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3627     if (isDeclWithinFunction(D))
3628       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3629     return NewD;
3630   }
3631 
3632   UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3633   SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3634 
3635   NestedNameSpecifierLoc QualifierLoc
3636     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3637                                           TemplateArgs);
3638   if (!QualifierLoc)
3639     return nullptr;
3640 
3641   CXXScopeSpec SS;
3642   SS.Adopt(QualifierLoc);
3643 
3644   DeclarationNameInfo NameInfo
3645     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3646 
3647   // Produce a pack expansion only if we're not instantiating a particular
3648   // slice of a pack expansion.
3649   bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3650                             SemaRef.ArgumentPackSubstitutionIndex != -1;
3651   SourceLocation EllipsisLoc =
3652       InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3653 
3654   bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3655   NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3656       /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3657       /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3658       ParsedAttributesView(),
3659       /*IsInstantiation*/ true, IsUsingIfExists);
3660   if (UD) {
3661     SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3662     SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3663   }
3664 
3665   return UD;
3666 }
3667 
3668 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3669     UnresolvedUsingTypenameDecl *D) {
3670   return instantiateUnresolvedUsingDecl(D);
3671 }
3672 
3673 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3674     UnresolvedUsingValueDecl *D) {
3675   return instantiateUnresolvedUsingDecl(D);
3676 }
3677 
3678 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3679     UnresolvedUsingIfExistsDecl *D) {
3680   llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3681 }
3682 
3683 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3684   SmallVector<NamedDecl*, 8> Expansions;
3685   for (auto *UD : D->expansions()) {
3686     if (NamedDecl *NewUD =
3687             SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3688       Expansions.push_back(NewUD);
3689     else
3690       return nullptr;
3691   }
3692 
3693   auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3694   if (isDeclWithinFunction(D))
3695     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3696   return NewD;
3697 }
3698 
3699 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3700                                      OMPThreadPrivateDecl *D) {
3701   SmallVector<Expr *, 5> Vars;
3702   for (auto *I : D->varlist()) {
3703     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3704     assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3705     Vars.push_back(Var);
3706   }
3707 
3708   OMPThreadPrivateDecl *TD =
3709       SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3710 
3711   TD->setAccess(AS_public);
3712   Owner->addDecl(TD);
3713 
3714   return TD;
3715 }
3716 
3717 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3718   SmallVector<Expr *, 5> Vars;
3719   for (auto *I : D->varlist()) {
3720     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3721     assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3722     Vars.push_back(Var);
3723   }
3724   SmallVector<OMPClause *, 4> Clauses;
3725   // Copy map clauses from the original mapper.
3726   for (OMPClause *C : D->clauselists()) {
3727     OMPClause *IC = nullptr;
3728     if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3729       ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3730       if (!NewE.isUsable())
3731         continue;
3732       IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
3733           NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3734     } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3735       ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3736       if (!NewE.isUsable())
3737         continue;
3738       IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
3739           NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3740       // If align clause value ends up being invalid, this can end up null.
3741       if (!IC)
3742         continue;
3743     }
3744     Clauses.push_back(IC);
3745   }
3746 
3747   Sema::DeclGroupPtrTy Res = SemaRef.OpenMP().ActOnOpenMPAllocateDirective(
3748       D->getLocation(), Vars, Clauses, Owner);
3749   if (Res.get().isNull())
3750     return nullptr;
3751   return Res.get().getSingleDecl();
3752 }
3753 
3754 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3755   llvm_unreachable(
3756       "Requires directive cannot be instantiated within a dependent context");
3757 }
3758 
3759 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3760     OMPDeclareReductionDecl *D) {
3761   // Instantiate type and check if it is allowed.
3762   const bool RequiresInstantiation =
3763       D->getType()->isDependentType() ||
3764       D->getType()->isInstantiationDependentType() ||
3765       D->getType()->containsUnexpandedParameterPack();
3766   QualType SubstReductionType;
3767   if (RequiresInstantiation) {
3768     SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
3769         D->getLocation(),
3770         ParsedType::make(SemaRef.SubstType(
3771             D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3772   } else {
3773     SubstReductionType = D->getType();
3774   }
3775   if (SubstReductionType.isNull())
3776     return nullptr;
3777   Expr *Combiner = D->getCombiner();
3778   Expr *Init = D->getInitializer();
3779   bool IsCorrect = true;
3780   // Create instantiated copy.
3781   std::pair<QualType, SourceLocation> ReductionTypes[] = {
3782       std::make_pair(SubstReductionType, D->getLocation())};
3783   auto *PrevDeclInScope = D->getPrevDeclInScope();
3784   if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3785     PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3786         cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3787             PrevDeclInScope)));
3788   }
3789   auto DRD = SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart(
3790       /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3791       PrevDeclInScope);
3792   auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3793   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3794   Expr *SubstCombiner = nullptr;
3795   Expr *SubstInitializer = nullptr;
3796   // Combiners instantiation sequence.
3797   if (Combiner) {
3798     SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerStart(
3799         /*S=*/nullptr, NewDRD);
3800     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3801         cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3802         cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3803     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3804         cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3805         cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3806     auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3807     Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3808                                      ThisContext);
3809     SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3810     SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(NewDRD,
3811                                                             SubstCombiner);
3812   }
3813   // Initializers instantiation sequence.
3814   if (Init) {
3815     VarDecl *OmpPrivParm =
3816         SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerStart(
3817             /*S=*/nullptr, NewDRD);
3818     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3819         cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3820         cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3821     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3822         cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3823         cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3824     if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) {
3825       SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3826     } else {
3827       auto *OldPrivParm =
3828           cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3829       IsCorrect = IsCorrect && OldPrivParm->hasInit();
3830       if (IsCorrect)
3831         SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3832                                                TemplateArgs);
3833     }
3834     SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd(
3835         NewDRD, SubstInitializer, OmpPrivParm);
3836   }
3837   IsCorrect = IsCorrect && SubstCombiner &&
3838               (!Init ||
3839                (D->getInitializerKind() == OMPDeclareReductionInitKind::Call &&
3840                 SubstInitializer) ||
3841                (D->getInitializerKind() != OMPDeclareReductionInitKind::Call &&
3842                 !SubstInitializer));
3843 
3844   (void)SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd(
3845       /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3846 
3847   return NewDRD;
3848 }
3849 
3850 Decl *
3851 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3852   // Instantiate type and check if it is allowed.
3853   const bool RequiresInstantiation =
3854       D->getType()->isDependentType() ||
3855       D->getType()->isInstantiationDependentType() ||
3856       D->getType()->containsUnexpandedParameterPack();
3857   QualType SubstMapperTy;
3858   DeclarationName VN = D->getVarName();
3859   if (RequiresInstantiation) {
3860     SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
3861         D->getLocation(),
3862         ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3863                                            D->getLocation(), VN)));
3864   } else {
3865     SubstMapperTy = D->getType();
3866   }
3867   if (SubstMapperTy.isNull())
3868     return nullptr;
3869   // Create an instantiated copy of mapper.
3870   auto *PrevDeclInScope = D->getPrevDeclInScope();
3871   if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3872     PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3873         cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3874             PrevDeclInScope)));
3875   }
3876   bool IsCorrect = true;
3877   SmallVector<OMPClause *, 6> Clauses;
3878   // Instantiate the mapper variable.
3879   DeclarationNameInfo DirName;
3880   SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3881                                        /*S=*/nullptr,
3882                                        (*D->clauselist_begin())->getBeginLoc());
3883   ExprResult MapperVarRef =
3884       SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl(
3885           /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3886   SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3887       cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3888       cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3889   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3890   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3891                                    ThisContext);
3892   // Instantiate map clauses.
3893   for (OMPClause *C : D->clauselists()) {
3894     auto *OldC = cast<OMPMapClause>(C);
3895     SmallVector<Expr *, 4> NewVars;
3896     for (Expr *OE : OldC->varlist()) {
3897       Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3898       if (!NE) {
3899         IsCorrect = false;
3900         break;
3901       }
3902       NewVars.push_back(NE);
3903     }
3904     if (!IsCorrect)
3905       break;
3906     NestedNameSpecifierLoc NewQualifierLoc =
3907         SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3908                                             TemplateArgs);
3909     CXXScopeSpec SS;
3910     SS.Adopt(NewQualifierLoc);
3911     DeclarationNameInfo NewNameInfo =
3912         SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3913     OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3914                          OldC->getEndLoc());
3915     OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
3916         OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3917         OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3918         OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3919         NewVars, Locs);
3920     Clauses.push_back(NewC);
3921   }
3922   SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
3923   if (!IsCorrect)
3924     return nullptr;
3925   Sema::DeclGroupPtrTy DG = SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirective(
3926       /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3927       VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3928   Decl *NewDMD = DG.get().getSingleDecl();
3929   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3930   return NewDMD;
3931 }
3932 
3933 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3934     OMPCapturedExprDecl * /*D*/) {
3935   llvm_unreachable("Should not be met in templates");
3936 }
3937 
3938 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3939   return VisitFunctionDecl(D, nullptr);
3940 }
3941 
3942 Decl *
3943 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3944   Decl *Inst = VisitFunctionDecl(D, nullptr);
3945   if (Inst && !D->getDescribedFunctionTemplate())
3946     Owner->addDecl(Inst);
3947   return Inst;
3948 }
3949 
3950 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3951   return VisitCXXMethodDecl(D, nullptr);
3952 }
3953 
3954 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3955   llvm_unreachable("There are only CXXRecordDecls in C++");
3956 }
3957 
3958 Decl *
3959 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3960     ClassTemplateSpecializationDecl *D) {
3961   // As a MS extension, we permit class-scope explicit specialization
3962   // of member class templates.
3963   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3964   assert(ClassTemplate->getDeclContext()->isRecord() &&
3965          D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3966          "can only instantiate an explicit specialization "
3967          "for a member class template");
3968 
3969   // Lookup the already-instantiated declaration in the instantiation
3970   // of the class template.
3971   ClassTemplateDecl *InstClassTemplate =
3972       cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3973           D->getLocation(), ClassTemplate, TemplateArgs));
3974   if (!InstClassTemplate)
3975     return nullptr;
3976 
3977   // Substitute into the template arguments of the class template explicit
3978   // specialization.
3979   TemplateArgumentListInfo InstTemplateArgs;
3980   if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3981           D->getTemplateArgsAsWritten()) {
3982     InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3983     InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3984 
3985     if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3986                                        TemplateArgs, InstTemplateArgs))
3987       return nullptr;
3988   }
3989 
3990   // Check that the template argument list is well-formed for this
3991   // class template.
3992   Sema::CheckTemplateArgumentInfo CTAI;
3993   if (SemaRef.CheckTemplateArgumentList(
3994           InstClassTemplate, D->getLocation(), InstTemplateArgs,
3995           /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
3996           /*UpdateArgsWithConversions=*/true))
3997     return nullptr;
3998 
3999   // Figure out where to insert this class template explicit specialization
4000   // in the member template's set of class template explicit specializations.
4001   void *InsertPos = nullptr;
4002   ClassTemplateSpecializationDecl *PrevDecl =
4003       InstClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4004 
4005   // Check whether we've already seen a conflicting instantiation of this
4006   // declaration (for instance, if there was a prior implicit instantiation).
4007   bool Ignored;
4008   if (PrevDecl &&
4009       SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
4010                                                      D->getSpecializationKind(),
4011                                                      PrevDecl,
4012                                                      PrevDecl->getSpecializationKind(),
4013                                                      PrevDecl->getPointOfInstantiation(),
4014                                                      Ignored))
4015     return nullptr;
4016 
4017   // If PrevDecl was a definition and D is also a definition, diagnose.
4018   // This happens in cases like:
4019   //
4020   //   template<typename T, typename U>
4021   //   struct Outer {
4022   //     template<typename X> struct Inner;
4023   //     template<> struct Inner<T> {};
4024   //     template<> struct Inner<U> {};
4025   //   };
4026   //
4027   //   Outer<int, int> outer; // error: the explicit specializations of Inner
4028   //                          // have the same signature.
4029   if (PrevDecl && PrevDecl->getDefinition() &&
4030       D->isThisDeclarationADefinition()) {
4031     SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
4032     SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
4033                  diag::note_previous_definition);
4034     return nullptr;
4035   }
4036 
4037   // Create the class template partial specialization declaration.
4038   ClassTemplateSpecializationDecl *InstD =
4039       ClassTemplateSpecializationDecl::Create(
4040           SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
4041           D->getLocation(), InstClassTemplate, CTAI.CanonicalConverted,
4042           PrevDecl);
4043   InstD->setTemplateArgsAsWritten(InstTemplateArgs);
4044 
4045   // Add this partial specialization to the set of class template partial
4046   // specializations.
4047   if (!PrevDecl)
4048     InstClassTemplate->AddSpecialization(InstD, InsertPos);
4049 
4050   // Substitute the nested name specifier, if any.
4051   if (SubstQualifier(D, InstD))
4052     return nullptr;
4053 
4054   InstD->setAccess(D->getAccess());
4055   InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
4056   InstD->setSpecializationKind(D->getSpecializationKind());
4057   InstD->setExternKeywordLoc(D->getExternKeywordLoc());
4058   InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
4059 
4060   Owner->addDecl(InstD);
4061 
4062   // Instantiate the members of the class-scope explicit specialization eagerly.
4063   // We don't have support for lazy instantiation of an explicit specialization
4064   // yet, and MSVC eagerly instantiates in this case.
4065   // FIXME: This is wrong in standard C++.
4066   if (D->isThisDeclarationADefinition() &&
4067       SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4068                                TSK_ImplicitInstantiation,
4069                                /*Complain=*/true))
4070     return nullptr;
4071 
4072   return InstD;
4073 }
4074 
4075 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
4076     VarTemplateSpecializationDecl *D) {
4077 
4078   TemplateArgumentListInfo VarTemplateArgsInfo;
4079   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
4080   assert(VarTemplate &&
4081          "A template specialization without specialized template?");
4082 
4083   VarTemplateDecl *InstVarTemplate =
4084       cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4085           D->getLocation(), VarTemplate, TemplateArgs));
4086   if (!InstVarTemplate)
4087     return nullptr;
4088 
4089   // Substitute the current template arguments.
4090   if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4091           D->getTemplateArgsAsWritten()) {
4092     VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4093     VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4094 
4095     if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4096                                        TemplateArgs, VarTemplateArgsInfo))
4097       return nullptr;
4098   }
4099 
4100   // Check that the template argument list is well-formed for this template.
4101   Sema::CheckTemplateArgumentInfo CTAI;
4102   if (SemaRef.CheckTemplateArgumentList(
4103           InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4104           /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4105           /*UpdateArgsWithConversions=*/true))
4106     return nullptr;
4107 
4108   // Check whether we've already seen a declaration of this specialization.
4109   void *InsertPos = nullptr;
4110   VarTemplateSpecializationDecl *PrevDecl =
4111       InstVarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4112 
4113   // Check whether we've already seen a conflicting instantiation of this
4114   // declaration (for instance, if there was a prior implicit instantiation).
4115   bool Ignored;
4116   if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4117                       D->getLocation(), D->getSpecializationKind(), PrevDecl,
4118                       PrevDecl->getSpecializationKind(),
4119                       PrevDecl->getPointOfInstantiation(), Ignored))
4120     return nullptr;
4121 
4122   return VisitVarTemplateSpecializationDecl(InstVarTemplate, D,
4123                                             VarTemplateArgsInfo,
4124                                             CTAI.CanonicalConverted, PrevDecl);
4125 }
4126 
4127 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
4128     VarTemplateDecl *VarTemplate, VarDecl *D,
4129     const TemplateArgumentListInfo &TemplateArgsInfo,
4130     ArrayRef<TemplateArgument> Converted,
4131     VarTemplateSpecializationDecl *PrevDecl) {
4132 
4133   // Do substitution on the type of the declaration
4134   TypeSourceInfo *DI =
4135       SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4136                         D->getTypeSpecStartLoc(), D->getDeclName());
4137   if (!DI)
4138     return nullptr;
4139 
4140   if (DI->getType()->isFunctionType()) {
4141     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4142         << D->isStaticDataMember() << DI->getType();
4143     return nullptr;
4144   }
4145 
4146   // Build the instantiated declaration
4147   VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
4148       SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4149       VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4150   Var->setTemplateArgsAsWritten(TemplateArgsInfo);
4151   if (!PrevDecl) {
4152     void *InsertPos = nullptr;
4153     VarTemplate->findSpecialization(Converted, InsertPos);
4154     VarTemplate->AddSpecialization(Var, InsertPos);
4155   }
4156 
4157   if (SemaRef.getLangOpts().OpenCL)
4158     SemaRef.deduceOpenCLAddressSpace(Var);
4159 
4160   // Substitute the nested name specifier, if any.
4161   if (SubstQualifier(D, Var))
4162     return nullptr;
4163 
4164   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4165                                      StartingScope, false, PrevDecl);
4166 
4167   return Var;
4168 }
4169 
4170 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4171   llvm_unreachable("@defs is not supported in Objective-C++");
4172 }
4173 
4174 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4175   // FIXME: We need to be able to instantiate FriendTemplateDecls.
4176   unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4177                                                DiagnosticsEngine::Error,
4178                                                "cannot instantiate %0 yet");
4179   SemaRef.Diag(D->getLocation(), DiagID)
4180     << D->getDeclKindName();
4181 
4182   return nullptr;
4183 }
4184 
4185 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4186   llvm_unreachable("Concept definitions cannot reside inside a template");
4187 }
4188 
4189 Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4190     ImplicitConceptSpecializationDecl *D) {
4191   llvm_unreachable("Concept specializations cannot reside inside a template");
4192 }
4193 
4194 Decl *
4195 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4196   return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4197                                       D->getBeginLoc());
4198 }
4199 
4200 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
4201   llvm_unreachable("Unexpected decl");
4202 }
4203 
4204 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
4205                       const MultiLevelTemplateArgumentList &TemplateArgs) {
4206   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4207   if (D->isInvalidDecl())
4208     return nullptr;
4209 
4210   Decl *SubstD;
4211   runWithSufficientStackSpace(D->getLocation(), [&] {
4212     SubstD = Instantiator.Visit(D);
4213   });
4214   return SubstD;
4215 }
4216 
4217 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
4218                                                 FunctionDecl *Orig, QualType &T,
4219                                                 TypeSourceInfo *&TInfo,
4220                                                 DeclarationNameInfo &NameInfo) {
4221   assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
4222 
4223   // C++2a [class.compare.default]p3:
4224   //   the return type is replaced with bool
4225   auto *FPT = T->castAs<FunctionProtoType>();
4226   T = SemaRef.Context.getFunctionType(
4227       SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4228 
4229   // Update the return type in the source info too. The most straightforward
4230   // way is to create new TypeSourceInfo for the new type. Use the location of
4231   // the '= default' as the location of the new type.
4232   //
4233   // FIXME: Set the correct return type when we initially transform the type,
4234   // rather than delaying it to now.
4235   TypeSourceInfo *NewTInfo =
4236       SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4237   auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4238   assert(OldLoc && "type of function is not a function type?");
4239   auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4240   for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4241     NewLoc.setParam(I, OldLoc.getParam(I));
4242   TInfo = NewTInfo;
4243 
4244   //   and the declarator-id is replaced with operator==
4245   NameInfo.setName(
4246       SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4247 }
4248 
4249 FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
4250                                                FunctionDecl *Spaceship) {
4251   if (Spaceship->isInvalidDecl())
4252     return nullptr;
4253 
4254   // C++2a [class.compare.default]p3:
4255   //   an == operator function is declared implicitly [...] with the same
4256   //   access and function-definition and in the same class scope as the
4257   //   three-way comparison operator function
4258   MultiLevelTemplateArgumentList NoTemplateArgs;
4259   NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
4260   NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4261   TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4262   Decl *R;
4263   if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4264     R = Instantiator.VisitCXXMethodDecl(
4265         MD, /*TemplateParams=*/nullptr,
4266         TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4267   } else {
4268     assert(Spaceship->getFriendObjectKind() &&
4269            "defaulted spaceship is neither a member nor a friend");
4270 
4271     R = Instantiator.VisitFunctionDecl(
4272         Spaceship, /*TemplateParams=*/nullptr,
4273         TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4274     if (!R)
4275       return nullptr;
4276 
4277     FriendDecl *FD =
4278         FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4279                            cast<NamedDecl>(R), Spaceship->getBeginLoc());
4280     FD->setAccess(AS_public);
4281     RD->addDecl(FD);
4282   }
4283   return cast_or_null<FunctionDecl>(R);
4284 }
4285 
4286 /// Instantiates a nested template parameter list in the current
4287 /// instantiation context.
4288 ///
4289 /// \param L The parameter list to instantiate
4290 ///
4291 /// \returns NULL if there was an error
4292 TemplateParameterList *
4293 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
4294   // Get errors for all the parameters before bailing out.
4295   bool Invalid = false;
4296 
4297   unsigned N = L->size();
4298   typedef SmallVector<NamedDecl *, 8> ParamVector;
4299   ParamVector Params;
4300   Params.reserve(N);
4301   for (auto &P : *L) {
4302     NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4303     Params.push_back(D);
4304     Invalid = Invalid || !D || D->isInvalidDecl();
4305   }
4306 
4307   // Clean up if we had an error.
4308   if (Invalid)
4309     return nullptr;
4310 
4311   Expr *InstRequiresClause = L->getRequiresClause();
4312 
4313   TemplateParameterList *InstL
4314     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4315                                     L->getLAngleLoc(), Params,
4316                                     L->getRAngleLoc(), InstRequiresClause);
4317   return InstL;
4318 }
4319 
4320 TemplateParameterList *
4321 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
4322                           const MultiLevelTemplateArgumentList &TemplateArgs,
4323                           bool EvaluateConstraints) {
4324   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4325   Instantiator.setEvaluateConstraints(EvaluateConstraints);
4326   return Instantiator.SubstTemplateParams(Params);
4327 }
4328 
4329 /// Instantiate the declaration of a class template partial
4330 /// specialization.
4331 ///
4332 /// \param ClassTemplate the (instantiated) class template that is partially
4333 // specialized by the instantiation of \p PartialSpec.
4334 ///
4335 /// \param PartialSpec the (uninstantiated) class template partial
4336 /// specialization that we are instantiating.
4337 ///
4338 /// \returns The instantiated partial specialization, if successful; otherwise,
4339 /// NULL to indicate an error.
4340 ClassTemplatePartialSpecializationDecl *
4341 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4342                                             ClassTemplateDecl *ClassTemplate,
4343                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
4344   // Create a local instantiation scope for this class template partial
4345   // specialization, which will contain the instantiations of the template
4346   // parameters.
4347   LocalInstantiationScope Scope(SemaRef);
4348 
4349   // Substitute into the template parameters of the class template partial
4350   // specialization.
4351   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4352   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4353   if (!InstParams)
4354     return nullptr;
4355 
4356   // Substitute into the template arguments of the class template partial
4357   // specialization.
4358   const ASTTemplateArgumentListInfo *TemplArgInfo
4359     = PartialSpec->getTemplateArgsAsWritten();
4360   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4361                                             TemplArgInfo->RAngleLoc);
4362   if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4363                                      InstTemplateArgs))
4364     return nullptr;
4365 
4366   // Check that the template argument list is well-formed for this
4367   // class template.
4368   Sema::CheckTemplateArgumentInfo CTAI;
4369   if (SemaRef.CheckTemplateArgumentList(
4370           ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4371           /*DefaultArgs=*/{},
4372           /*PartialTemplateArgs=*/false, CTAI))
4373     return nullptr;
4374 
4375   // Check these arguments are valid for a template partial specialization.
4376   if (SemaRef.CheckTemplatePartialSpecializationArgs(
4377           PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4378           CTAI.CanonicalConverted))
4379     return nullptr;
4380 
4381   // Figure out where to insert this class template partial specialization
4382   // in the member template's set of class template partial specializations.
4383   void *InsertPos = nullptr;
4384   ClassTemplateSpecializationDecl *PrevDecl =
4385       ClassTemplate->findPartialSpecialization(CTAI.CanonicalConverted,
4386                                                InstParams, InsertPos);
4387 
4388   // Build the canonical type that describes the converted template
4389   // arguments of the class template partial specialization.
4390   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4391       TemplateName(ClassTemplate), CTAI.CanonicalConverted);
4392 
4393   // Create the class template partial specialization declaration.
4394   ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4395       ClassTemplatePartialSpecializationDecl::Create(
4396           SemaRef.Context, PartialSpec->getTagKind(), Owner,
4397           PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4398           ClassTemplate, CTAI.CanonicalConverted, CanonType,
4399           /*PrevDecl=*/nullptr);
4400 
4401   InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4402 
4403   // Substitute the nested name specifier, if any.
4404   if (SubstQualifier(PartialSpec, InstPartialSpec))
4405     return nullptr;
4406 
4407   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4408 
4409   if (PrevDecl) {
4410     // We've already seen a partial specialization with the same template
4411     // parameters and template arguments. This can happen, for example, when
4412     // substituting the outer template arguments ends up causing two
4413     // class template partial specializations of a member class template
4414     // to have identical forms, e.g.,
4415     //
4416     //   template<typename T, typename U>
4417     //   struct Outer {
4418     //     template<typename X, typename Y> struct Inner;
4419     //     template<typename Y> struct Inner<T, Y>;
4420     //     template<typename Y> struct Inner<U, Y>;
4421     //   };
4422     //
4423     //   Outer<int, int> outer; // error: the partial specializations of Inner
4424     //                          // have the same signature.
4425     SemaRef.Diag(InstPartialSpec->getLocation(),
4426                  diag::err_partial_spec_redeclared)
4427         << InstPartialSpec;
4428     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4429       << SemaRef.Context.getTypeDeclType(PrevDecl);
4430     return nullptr;
4431   }
4432 
4433   // Check the completed partial specialization.
4434   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4435 
4436   // Add this partial specialization to the set of class template partial
4437   // specializations.
4438   ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4439                                           /*InsertPos=*/nullptr);
4440   return InstPartialSpec;
4441 }
4442 
4443 /// Instantiate the declaration of a variable template partial
4444 /// specialization.
4445 ///
4446 /// \param VarTemplate the (instantiated) variable template that is partially
4447 /// specialized by the instantiation of \p PartialSpec.
4448 ///
4449 /// \param PartialSpec the (uninstantiated) variable template partial
4450 /// specialization that we are instantiating.
4451 ///
4452 /// \returns The instantiated partial specialization, if successful; otherwise,
4453 /// NULL to indicate an error.
4454 VarTemplatePartialSpecializationDecl *
4455 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4456     VarTemplateDecl *VarTemplate,
4457     VarTemplatePartialSpecializationDecl *PartialSpec) {
4458   // Create a local instantiation scope for this variable template partial
4459   // specialization, which will contain the instantiations of the template
4460   // parameters.
4461   LocalInstantiationScope Scope(SemaRef);
4462 
4463   // Substitute into the template parameters of the variable template partial
4464   // specialization.
4465   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4466   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4467   if (!InstParams)
4468     return nullptr;
4469 
4470   // Substitute into the template arguments of the variable template partial
4471   // specialization.
4472   const ASTTemplateArgumentListInfo *TemplArgInfo
4473     = PartialSpec->getTemplateArgsAsWritten();
4474   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4475                                             TemplArgInfo->RAngleLoc);
4476   if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4477                                      InstTemplateArgs))
4478     return nullptr;
4479 
4480   // Check that the template argument list is well-formed for this
4481   // class template.
4482   Sema::CheckTemplateArgumentInfo CTAI;
4483   if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4484                                         InstTemplateArgs, /*DefaultArgs=*/{},
4485                                         /*PartialTemplateArgs=*/false, CTAI))
4486     return nullptr;
4487 
4488   // Check these arguments are valid for a template partial specialization.
4489   if (SemaRef.CheckTemplatePartialSpecializationArgs(
4490           PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4491           CTAI.CanonicalConverted))
4492     return nullptr;
4493 
4494   // Figure out where to insert this variable template partial specialization
4495   // in the member template's set of variable template partial specializations.
4496   void *InsertPos = nullptr;
4497   VarTemplateSpecializationDecl *PrevDecl =
4498       VarTemplate->findPartialSpecialization(CTAI.CanonicalConverted,
4499                                              InstParams, InsertPos);
4500 
4501   // Do substitution on the type of the declaration
4502   TypeSourceInfo *DI = SemaRef.SubstType(
4503       PartialSpec->getTypeSourceInfo(), TemplateArgs,
4504       PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4505   if (!DI)
4506     return nullptr;
4507 
4508   if (DI->getType()->isFunctionType()) {
4509     SemaRef.Diag(PartialSpec->getLocation(),
4510                  diag::err_variable_instantiates_to_function)
4511         << PartialSpec->isStaticDataMember() << DI->getType();
4512     return nullptr;
4513   }
4514 
4515   // Create the variable template partial specialization declaration.
4516   VarTemplatePartialSpecializationDecl *InstPartialSpec =
4517       VarTemplatePartialSpecializationDecl::Create(
4518           SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4519           PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4520           DI, PartialSpec->getStorageClass(), CTAI.CanonicalConverted);
4521 
4522   InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4523 
4524   // Substitute the nested name specifier, if any.
4525   if (SubstQualifier(PartialSpec, InstPartialSpec))
4526     return nullptr;
4527 
4528   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4529 
4530   if (PrevDecl) {
4531     // We've already seen a partial specialization with the same template
4532     // parameters and template arguments. This can happen, for example, when
4533     // substituting the outer template arguments ends up causing two
4534     // variable template partial specializations of a member variable template
4535     // to have identical forms, e.g.,
4536     //
4537     //   template<typename T, typename U>
4538     //   struct Outer {
4539     //     template<typename X, typename Y> pair<X,Y> p;
4540     //     template<typename Y> pair<T, Y> p;
4541     //     template<typename Y> pair<U, Y> p;
4542     //   };
4543     //
4544     //   Outer<int, int> outer; // error: the partial specializations of Inner
4545     //                          // have the same signature.
4546     SemaRef.Diag(PartialSpec->getLocation(),
4547                  diag::err_var_partial_spec_redeclared)
4548         << InstPartialSpec;
4549     SemaRef.Diag(PrevDecl->getLocation(),
4550                  diag::note_var_prev_partial_spec_here);
4551     return nullptr;
4552   }
4553   // Check the completed partial specialization.
4554   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4555 
4556   // Add this partial specialization to the set of variable template partial
4557   // specializations. The instantiation of the initializer is not necessary.
4558   VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4559 
4560   SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4561                                      LateAttrs, Owner, StartingScope);
4562 
4563   return InstPartialSpec;
4564 }
4565 
4566 TypeSourceInfo*
4567 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4568                               SmallVectorImpl<ParmVarDecl *> &Params) {
4569   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4570   assert(OldTInfo && "substituting function without type source info");
4571   assert(Params.empty() && "parameter vector is non-empty at start");
4572 
4573   CXXRecordDecl *ThisContext = nullptr;
4574   Qualifiers ThisTypeQuals;
4575   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4576     ThisContext = cast<CXXRecordDecl>(Owner);
4577     ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4578   }
4579 
4580   TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4581       OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4582       ThisContext, ThisTypeQuals, EvaluateConstraints);
4583   if (!NewTInfo)
4584     return nullptr;
4585 
4586   TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4587   if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4588     if (NewTInfo != OldTInfo) {
4589       // Get parameters from the new type info.
4590       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4591       FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4592       unsigned NewIdx = 0;
4593       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4594            OldIdx != NumOldParams; ++OldIdx) {
4595         ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4596         if (!OldParam)
4597           return nullptr;
4598 
4599         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4600 
4601         std::optional<unsigned> NumArgumentsInExpansion;
4602         if (OldParam->isParameterPack())
4603           NumArgumentsInExpansion =
4604               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4605                                                  TemplateArgs);
4606         if (!NumArgumentsInExpansion) {
4607           // Simple case: normal parameter, or a parameter pack that's
4608           // instantiated to a (still-dependent) parameter pack.
4609           ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4610           Params.push_back(NewParam);
4611           Scope->InstantiatedLocal(OldParam, NewParam);
4612         } else {
4613           // Parameter pack expansion: make the instantiation an argument pack.
4614           Scope->MakeInstantiatedLocalArgPack(OldParam);
4615           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4616             ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4617             Params.push_back(NewParam);
4618             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4619           }
4620         }
4621       }
4622     } else {
4623       // The function type itself was not dependent and therefore no
4624       // substitution occurred. However, we still need to instantiate
4625       // the function parameters themselves.
4626       const FunctionProtoType *OldProto =
4627           cast<FunctionProtoType>(OldProtoLoc.getType());
4628       for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4629            ++i) {
4630         ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4631         if (!OldParam) {
4632           Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4633               D, D->getLocation(), OldProto->getParamType(i)));
4634           continue;
4635         }
4636 
4637         ParmVarDecl *Parm =
4638             cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4639         if (!Parm)
4640           return nullptr;
4641         Params.push_back(Parm);
4642       }
4643     }
4644   } else {
4645     // If the type of this function, after ignoring parentheses, is not
4646     // *directly* a function type, then we're instantiating a function that
4647     // was declared via a typedef or with attributes, e.g.,
4648     //
4649     //   typedef int functype(int, int);
4650     //   functype func;
4651     //   int __cdecl meth(int, int);
4652     //
4653     // In this case, we'll just go instantiate the ParmVarDecls that we
4654     // synthesized in the method declaration.
4655     SmallVector<QualType, 4> ParamTypes;
4656     Sema::ExtParameterInfoBuilder ExtParamInfos;
4657     if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4658                                TemplateArgs, ParamTypes, &Params,
4659                                ExtParamInfos))
4660       return nullptr;
4661   }
4662 
4663   return NewTInfo;
4664 }
4665 
4666 void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
4667                                            const FunctionDecl *PatternDecl,
4668                                            LocalInstantiationScope &Scope) {
4669   LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
4670 
4671   for (auto *decl : PatternDecl->decls()) {
4672     if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
4673       continue;
4674 
4675     VarDecl *VD = cast<VarDecl>(decl);
4676     IdentifierInfo *II = VD->getIdentifier();
4677 
4678     auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
4679       VarDecl *InstVD = dyn_cast<VarDecl>(inst);
4680       return InstVD && InstVD->isLocalVarDecl() &&
4681              InstVD->getIdentifier() == II;
4682     });
4683 
4684     if (it == Function->decls().end())
4685       continue;
4686 
4687     Scope.InstantiatedLocal(VD, *it);
4688     LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
4689                     /*isNested=*/false, VD->getLocation(), SourceLocation(),
4690                     VD->getType(), /*Invalid=*/false);
4691   }
4692 }
4693 
4694 bool Sema::addInstantiatedParametersToScope(
4695     FunctionDecl *Function, const FunctionDecl *PatternDecl,
4696     LocalInstantiationScope &Scope,
4697     const MultiLevelTemplateArgumentList &TemplateArgs) {
4698   unsigned FParamIdx = 0;
4699   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4700     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4701     if (!PatternParam->isParameterPack()) {
4702       // Simple case: not a parameter pack.
4703       assert(FParamIdx < Function->getNumParams());
4704       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4705       FunctionParam->setDeclName(PatternParam->getDeclName());
4706       // If the parameter's type is not dependent, update it to match the type
4707       // in the pattern. They can differ in top-level cv-qualifiers, and we want
4708       // the pattern's type here. If the type is dependent, they can't differ,
4709       // per core issue 1668. Substitute into the type from the pattern, in case
4710       // it's instantiation-dependent.
4711       // FIXME: Updating the type to work around this is at best fragile.
4712       if (!PatternDecl->getType()->isDependentType()) {
4713         QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4714                                FunctionParam->getLocation(),
4715                                FunctionParam->getDeclName());
4716         if (T.isNull())
4717           return true;
4718         FunctionParam->setType(T);
4719       }
4720 
4721       Scope.InstantiatedLocal(PatternParam, FunctionParam);
4722       ++FParamIdx;
4723       continue;
4724     }
4725 
4726     // Expand the parameter pack.
4727     Scope.MakeInstantiatedLocalArgPack(PatternParam);
4728     std::optional<unsigned> NumArgumentsInExpansion =
4729         getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4730     if (NumArgumentsInExpansion) {
4731       QualType PatternType =
4732           PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4733       for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4734         ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4735         FunctionParam->setDeclName(PatternParam->getDeclName());
4736         if (!PatternDecl->getType()->isDependentType()) {
4737           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4738           QualType T =
4739               SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4740                         FunctionParam->getDeclName());
4741           if (T.isNull())
4742             return true;
4743           FunctionParam->setType(T);
4744         }
4745 
4746         Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4747         ++FParamIdx;
4748       }
4749     }
4750   }
4751 
4752   return false;
4753 }
4754 
4755 bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4756                                       ParmVarDecl *Param) {
4757   assert(Param->hasUninstantiatedDefaultArg());
4758 
4759   // FIXME: We don't track member specialization info for non-defining
4760   // friend declarations, so we will not be able to later find the function
4761   // pattern. As a workaround, don't instantiate the default argument in this
4762   // case. This is correct per the standard and only an issue for recovery
4763   // purposes. [dcl.fct.default]p4:
4764   //   if a friend declaration D specifies a default argument expression,
4765   //   that declaration shall be a definition.
4766   if (FD->getFriendObjectKind() != Decl::FOK_None &&
4767       !FD->getTemplateInstantiationPattern())
4768     return true;
4769 
4770   // Instantiate the expression.
4771   //
4772   // FIXME: Pass in a correct Pattern argument, otherwise
4773   // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4774   //
4775   // template<typename T>
4776   // struct A {
4777   //   static int FooImpl();
4778   //
4779   //   template<typename Tp>
4780   //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4781   //   // template argument list [[T], [Tp]], should be [[Tp]].
4782   //   friend A<Tp> Foo(int a);
4783   // };
4784   //
4785   // template<typename T>
4786   // A<T> Foo(int a = A<T>::FooImpl());
4787   MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4788       FD, FD->getLexicalDeclContext(),
4789       /*Final=*/false, /*Innermost=*/std::nullopt,
4790       /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
4791       /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
4792       /*ForDefaultArgumentSubstitution=*/true);
4793 
4794   if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4795     return true;
4796 
4797   if (ASTMutationListener *L = getASTMutationListener())
4798     L->DefaultArgumentInstantiated(Param);
4799 
4800   return false;
4801 }
4802 
4803 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4804                                     FunctionDecl *Decl) {
4805   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4806   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4807     return;
4808 
4809   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4810                              InstantiatingTemplate::ExceptionSpecification());
4811   if (Inst.isInvalid()) {
4812     // We hit the instantiation depth limit. Clear the exception specification
4813     // so that our callers don't have to cope with EST_Uninstantiated.
4814     UpdateExceptionSpec(Decl, EST_None);
4815     return;
4816   }
4817   if (Inst.isAlreadyInstantiating()) {
4818     // This exception specification indirectly depends on itself. Reject.
4819     // FIXME: Corresponding rule in the standard?
4820     Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4821     UpdateExceptionSpec(Decl, EST_None);
4822     return;
4823   }
4824 
4825   // Enter the scope of this instantiation. We don't use
4826   // PushDeclContext because we don't have a scope.
4827   Sema::ContextRAII savedContext(*this, Decl);
4828   LocalInstantiationScope Scope(*this);
4829 
4830   MultiLevelTemplateArgumentList TemplateArgs =
4831       getTemplateInstantiationArgs(Decl, Decl->getLexicalDeclContext(),
4832                                    /*Final=*/false, /*Innermost=*/std::nullopt,
4833                                    /*RelativeToPrimary*/ true);
4834 
4835   // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4836   // here, because for a non-defining friend declaration in a class template,
4837   // we don't store enough information to map back to the friend declaration in
4838   // the template.
4839   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4840   if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4841     UpdateExceptionSpec(Decl, EST_None);
4842     return;
4843   }
4844 
4845   // The noexcept specification could reference any lambda captures. Ensure
4846   // those are added to the LocalInstantiationScope.
4847   LambdaScopeForCallOperatorInstantiationRAII PushLambdaCaptures(
4848       *this, Decl, TemplateArgs, Scope,
4849       /*ShouldAddDeclsFromParentScope=*/false);
4850 
4851   SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4852                      TemplateArgs);
4853 }
4854 
4855 /// Initializes the common fields of an instantiation function
4856 /// declaration (New) from the corresponding fields of its template (Tmpl).
4857 ///
4858 /// \returns true if there was an error
4859 bool
4860 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4861                                                     FunctionDecl *Tmpl) {
4862   New->setImplicit(Tmpl->isImplicit());
4863 
4864   // Forward the mangling number from the template to the instantiated decl.
4865   SemaRef.Context.setManglingNumber(New,
4866                                     SemaRef.Context.getManglingNumber(Tmpl));
4867 
4868   // If we are performing substituting explicitly-specified template arguments
4869   // or deduced template arguments into a function template and we reach this
4870   // point, we are now past the point where SFINAE applies and have committed
4871   // to keeping the new function template specialization. We therefore
4872   // convert the active template instantiation for the function template
4873   // into a template instantiation for this specific function template
4874   // specialization, which is not a SFINAE context, so that we diagnose any
4875   // further errors in the declaration itself.
4876   //
4877   // FIXME: This is a hack.
4878   typedef Sema::CodeSynthesisContext ActiveInstType;
4879   ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4880   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4881       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4882     if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4883       SemaRef.InstantiatingSpecializations.erase(
4884           {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4885       atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4886       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4887       ActiveInst.Entity = New;
4888       atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4889     }
4890   }
4891 
4892   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4893   assert(Proto && "Function template without prototype?");
4894 
4895   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4896     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4897 
4898     // DR1330: In C++11, defer instantiation of a non-trivial
4899     // exception specification.
4900     // DR1484: Local classes and their members are instantiated along with the
4901     // containing function.
4902     if (SemaRef.getLangOpts().CPlusPlus11 &&
4903         EPI.ExceptionSpec.Type != EST_None &&
4904         EPI.ExceptionSpec.Type != EST_DynamicNone &&
4905         EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4906         !Tmpl->isInLocalScopeForInstantiation()) {
4907       FunctionDecl *ExceptionSpecTemplate = Tmpl;
4908       if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4909         ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4910       ExceptionSpecificationType NewEST = EST_Uninstantiated;
4911       if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4912         NewEST = EST_Unevaluated;
4913 
4914       // Mark the function has having an uninstantiated exception specification.
4915       const FunctionProtoType *NewProto
4916         = New->getType()->getAs<FunctionProtoType>();
4917       assert(NewProto && "Template instantiation without function prototype?");
4918       EPI = NewProto->getExtProtoInfo();
4919       EPI.ExceptionSpec.Type = NewEST;
4920       EPI.ExceptionSpec.SourceDecl = New;
4921       EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4922       New->setType(SemaRef.Context.getFunctionType(
4923           NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4924     } else {
4925       Sema::ContextRAII SwitchContext(SemaRef, New);
4926       SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4927     }
4928   }
4929 
4930   // Get the definition. Leaves the variable unchanged if undefined.
4931   const FunctionDecl *Definition = Tmpl;
4932   Tmpl->isDefined(Definition);
4933 
4934   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4935                            LateAttrs, StartingScope);
4936 
4937   return false;
4938 }
4939 
4940 /// Initializes common fields of an instantiated method
4941 /// declaration (New) from the corresponding fields of its template
4942 /// (Tmpl).
4943 ///
4944 /// \returns true if there was an error
4945 bool
4946 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4947                                                   CXXMethodDecl *Tmpl) {
4948   if (InitFunctionInstantiation(New, Tmpl))
4949     return true;
4950 
4951   if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4952     SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4953 
4954   New->setAccess(Tmpl->getAccess());
4955   if (Tmpl->isVirtualAsWritten())
4956     New->setVirtualAsWritten(true);
4957 
4958   // FIXME: New needs a pointer to Tmpl
4959   return false;
4960 }
4961 
4962 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4963                                                       FunctionDecl *Tmpl) {
4964   // Transfer across any unqualified lookups.
4965   if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) {
4966     SmallVector<DeclAccessPair, 32> Lookups;
4967     Lookups.reserve(DFI->getUnqualifiedLookups().size());
4968     bool AnyChanged = false;
4969     for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4970       NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4971                                                   DA.getDecl(), TemplateArgs);
4972       if (!D)
4973         return true;
4974       AnyChanged |= (D != DA.getDecl());
4975       Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4976     }
4977 
4978     // It's unlikely that substitution will change any declarations. Don't
4979     // store an unnecessary copy in that case.
4980     New->setDefaultedOrDeletedInfo(
4981         AnyChanged ? FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
4982                          SemaRef.Context, Lookups)
4983                    : DFI);
4984   }
4985 
4986   SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4987   return false;
4988 }
4989 
4990 FunctionDecl *Sema::InstantiateFunctionDeclaration(
4991     FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
4992     SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC) {
4993   FunctionDecl *FD = FTD->getTemplatedDecl();
4994 
4995   sema::TemplateDeductionInfo Info(Loc);
4996   InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info);
4997   if (Inst.isInvalid())
4998     return nullptr;
4999 
5000   ContextRAII SavedContext(*this, FD);
5001   MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
5002                                        /*Final=*/false);
5003 
5004   return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
5005 }
5006 
5007 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
5008                                          FunctionDecl *Function,
5009                                          bool Recursive,
5010                                          bool DefinitionRequired,
5011                                          bool AtEndOfTU) {
5012   if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
5013     return;
5014 
5015   // Never instantiate an explicit specialization except if it is a class scope
5016   // explicit specialization.
5017   TemplateSpecializationKind TSK =
5018       Function->getTemplateSpecializationKindForInstantiation();
5019   if (TSK == TSK_ExplicitSpecialization)
5020     return;
5021 
5022   // Never implicitly instantiate a builtin; we don't actually need a function
5023   // body.
5024   if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
5025       !DefinitionRequired)
5026     return;
5027 
5028   // Don't instantiate a definition if we already have one.
5029   const FunctionDecl *ExistingDefn = nullptr;
5030   if (Function->isDefined(ExistingDefn,
5031                           /*CheckForPendingFriendDefinition=*/true)) {
5032     if (ExistingDefn->isThisDeclarationADefinition())
5033       return;
5034 
5035     // If we're asked to instantiate a function whose body comes from an
5036     // instantiated friend declaration, attach the instantiated body to the
5037     // corresponding declaration of the function.
5038     assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
5039     Function = const_cast<FunctionDecl*>(ExistingDefn);
5040   }
5041 
5042   // Find the function body that we'll be substituting.
5043   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
5044   assert(PatternDecl && "instantiating a non-template");
5045 
5046   const FunctionDecl *PatternDef = PatternDecl->getDefinition();
5047   Stmt *Pattern = nullptr;
5048   if (PatternDef) {
5049     Pattern = PatternDef->getBody(PatternDef);
5050     PatternDecl = PatternDef;
5051     if (PatternDef->willHaveBody())
5052       PatternDef = nullptr;
5053   }
5054 
5055   // FIXME: We need to track the instantiation stack in order to know which
5056   // definitions should be visible within this instantiation.
5057   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
5058                                 Function->getInstantiatedFromMemberFunction(),
5059                                      PatternDecl, PatternDef, TSK,
5060                                      /*Complain*/DefinitionRequired)) {
5061     if (DefinitionRequired)
5062       Function->setInvalidDecl();
5063     else if (TSK == TSK_ExplicitInstantiationDefinition ||
5064              (Function->isConstexpr() && !Recursive)) {
5065       // Try again at the end of the translation unit (at which point a
5066       // definition will be required).
5067       assert(!Recursive);
5068       Function->setInstantiationIsPending(true);
5069       PendingInstantiations.push_back(
5070         std::make_pair(Function, PointOfInstantiation));
5071 
5072       if (llvm::isTimeTraceVerbose()) {
5073         llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
5074           std::string Name;
5075           llvm::raw_string_ostream OS(Name);
5076           Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5077                                          /*Qualified=*/true);
5078           return Name;
5079         });
5080       }
5081     } else if (TSK == TSK_ImplicitInstantiation) {
5082       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5083           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5084         Diag(PointOfInstantiation, diag::warn_func_template_missing)
5085           << Function;
5086         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5087         if (getLangOpts().CPlusPlus11)
5088           Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
5089               << Function;
5090       }
5091     }
5092 
5093     return;
5094   }
5095 
5096   // Postpone late parsed template instantiations.
5097   if (PatternDecl->isLateTemplateParsed() &&
5098       !LateTemplateParser) {
5099     Function->setInstantiationIsPending(true);
5100     LateParsedInstantiations.push_back(
5101         std::make_pair(Function, PointOfInstantiation));
5102     return;
5103   }
5104 
5105   llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5106     llvm::TimeTraceMetadata M;
5107     llvm::raw_string_ostream OS(M.Detail);
5108     Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5109                                    /*Qualified=*/true);
5110     if (llvm::isTimeTraceVerbose()) {
5111       auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
5112       M.File = SourceMgr.getFilename(Loc);
5113       M.Line = SourceMgr.getExpansionLineNumber(Loc);
5114     }
5115     return M;
5116   });
5117 
5118   // If we're performing recursive template instantiation, create our own
5119   // queue of pending implicit instantiations that we will instantiate later,
5120   // while we're still within our own instantiation context.
5121   // This has to happen before LateTemplateParser below is called, so that
5122   // it marks vtables used in late parsed templates as used.
5123   GlobalEagerInstantiationScope GlobalInstantiations(*this,
5124                                                      /*Enabled=*/Recursive);
5125   LocalEagerInstantiationScope LocalInstantiations(*this);
5126 
5127   // Call the LateTemplateParser callback if there is a need to late parse
5128   // a templated function definition.
5129   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5130       LateTemplateParser) {
5131     // FIXME: Optimize to allow individual templates to be deserialized.
5132     if (PatternDecl->isFromASTFile())
5133       ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5134 
5135     auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5136     assert(LPTIter != LateParsedTemplateMap.end() &&
5137            "missing LateParsedTemplate");
5138     LateTemplateParser(OpaqueParser, *LPTIter->second);
5139     Pattern = PatternDecl->getBody(PatternDecl);
5140     updateAttrsForLateParsedTemplate(PatternDecl, Function);
5141   }
5142 
5143   // Note, we should never try to instantiate a deleted function template.
5144   assert((Pattern || PatternDecl->isDefaulted() ||
5145           PatternDecl->hasSkippedBody()) &&
5146          "unexpected kind of function template definition");
5147 
5148   // C++1y [temp.explicit]p10:
5149   //   Except for inline functions, declarations with types deduced from their
5150   //   initializer or return value, and class template specializations, other
5151   //   explicit instantiation declarations have the effect of suppressing the
5152   //   implicit instantiation of the entity to which they refer.
5153   if (TSK == TSK_ExplicitInstantiationDeclaration &&
5154       !PatternDecl->isInlined() &&
5155       !PatternDecl->getReturnType()->getContainedAutoType())
5156     return;
5157 
5158   if (PatternDecl->isInlined()) {
5159     // Function, and all later redeclarations of it (from imported modules,
5160     // for instance), are now implicitly inline.
5161     for (auto *D = Function->getMostRecentDecl(); /**/;
5162          D = D->getPreviousDecl()) {
5163       D->setImplicitlyInline();
5164       if (D == Function)
5165         break;
5166     }
5167   }
5168 
5169   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5170   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5171     return;
5172   PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
5173                                       "instantiating function definition");
5174 
5175   // The instantiation is visible here, even if it was first declared in an
5176   // unimported module.
5177   Function->setVisibleDespiteOwningModule();
5178 
5179   // Copy the source locations from the pattern.
5180   Function->setLocation(PatternDecl->getLocation());
5181   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5182   Function->setRangeEnd(PatternDecl->getEndLoc());
5183   Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo());
5184 
5185   EnterExpressionEvaluationContext EvalContext(
5186       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5187 
5188   Qualifiers ThisTypeQuals;
5189   CXXRecordDecl *ThisContext = nullptr;
5190   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5191     ThisContext = Method->getParent();
5192     ThisTypeQuals = Method->getMethodQualifiers();
5193   }
5194   CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5195 
5196   // Introduce a new scope where local variable instantiations will be
5197   // recorded, unless we're actually a member function within a local
5198   // class, in which case we need to merge our results with the parent
5199   // scope (of the enclosing function). The exception is instantiating
5200   // a function template specialization, since the template to be
5201   // instantiated already has references to locals properly substituted.
5202   bool MergeWithParentScope = false;
5203   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5204     MergeWithParentScope =
5205         Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5206 
5207   LocalInstantiationScope Scope(*this, MergeWithParentScope);
5208   auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5209     // Special members might get their TypeSourceInfo set up w.r.t the
5210     // PatternDecl context, in which case parameters could still be pointing
5211     // back to the original class, make sure arguments are bound to the
5212     // instantiated record instead.
5213     assert(PatternDecl->isDefaulted() &&
5214            "Special member needs to be defaulted");
5215     auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5216     if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5217           PatternSM == CXXSpecialMemberKind::CopyAssignment ||
5218           PatternSM == CXXSpecialMemberKind::MoveConstructor ||
5219           PatternSM == CXXSpecialMemberKind::MoveAssignment))
5220       return;
5221 
5222     auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5223     const auto *PatternRec =
5224         dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5225     if (!NewRec || !PatternRec)
5226       return;
5227     if (!PatternRec->isLambda())
5228       return;
5229 
5230     struct SpecialMemberTypeInfoRebuilder
5231         : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5232       using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
5233       const CXXRecordDecl *OldDecl;
5234       CXXRecordDecl *NewDecl;
5235 
5236       SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5237                                      CXXRecordDecl *N)
5238           : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5239 
5240       bool TransformExceptionSpec(SourceLocation Loc,
5241                                   FunctionProtoType::ExceptionSpecInfo &ESI,
5242                                   SmallVectorImpl<QualType> &Exceptions,
5243                                   bool &Changed) {
5244         return false;
5245       }
5246 
5247       QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5248         const RecordType *T = TL.getTypePtr();
5249         RecordDecl *Record = cast_or_null<RecordDecl>(
5250             getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5251         if (Record != OldDecl)
5252           return Base::TransformRecordType(TLB, TL);
5253 
5254         QualType Result = getDerived().RebuildRecordType(NewDecl);
5255         if (Result.isNull())
5256           return QualType();
5257 
5258         RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5259         NewTL.setNameLoc(TL.getNameLoc());
5260         return Result;
5261       }
5262     } IR{*this, PatternRec, NewRec};
5263 
5264     TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5265     assert(NewSI && "Type Transform failed?");
5266     Function->setType(NewSI->getType());
5267     Function->setTypeSourceInfo(NewSI);
5268 
5269     ParmVarDecl *Parm = Function->getParamDecl(0);
5270     TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5271     assert(NewParmSI && "Type transformation failed.");
5272     Parm->setType(NewParmSI->getType());
5273     Parm->setTypeSourceInfo(NewParmSI);
5274   };
5275 
5276   if (PatternDecl->isDefaulted()) {
5277     RebuildTypeSourceInfoForDefaultSpecialMembers();
5278     SetDeclDefaulted(Function, PatternDecl->getLocation());
5279   } else {
5280     NamedDecl *ND = Function;
5281     DeclContext *DC = ND->getLexicalDeclContext();
5282     std::optional<ArrayRef<TemplateArgument>> Innermost;
5283     if (auto *Primary = Function->getPrimaryTemplate();
5284         Primary &&
5285         !isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function) &&
5286         Function->getTemplateSpecializationKind() !=
5287             TSK_ExplicitSpecialization) {
5288       auto It = llvm::find_if(Primary->redecls(),
5289                               [](const RedeclarableTemplateDecl *RTD) {
5290                                 return cast<FunctionTemplateDecl>(RTD)
5291                                     ->isCompatibleWithDefinition();
5292                               });
5293       assert(It != Primary->redecls().end() &&
5294              "Should't get here without a definition");
5295       DC = (*It)->getLexicalDeclContext();
5296       Innermost.emplace(Function->getTemplateSpecializationArgs()->asArray());
5297     }
5298     MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
5299         Function, DC, /*Final=*/false, Innermost, false, PatternDecl);
5300 
5301     // Substitute into the qualifier; we can get a substitution failure here
5302     // through evil use of alias templates.
5303     // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5304     // of the) lexical context of the pattern?
5305     SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5306 
5307     ActOnStartOfFunctionDef(nullptr, Function);
5308 
5309     // Enter the scope of this instantiation. We don't use
5310     // PushDeclContext because we don't have a scope.
5311     Sema::ContextRAII savedContext(*this, Function);
5312 
5313     FPFeaturesStateRAII SavedFPFeatures(*this);
5314     CurFPFeatures = FPOptions(getLangOpts());
5315     FpPragmaStack.CurrentValue = FPOptionsOverride();
5316 
5317     if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5318                                          TemplateArgs))
5319       return;
5320 
5321     StmtResult Body;
5322     if (PatternDecl->hasSkippedBody()) {
5323       ActOnSkippedFunctionBody(Function);
5324       Body = nullptr;
5325     } else {
5326       if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5327         // If this is a constructor, instantiate the member initializers.
5328         InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5329                                    TemplateArgs);
5330 
5331         // If this is an MS ABI dllexport default constructor, instantiate any
5332         // default arguments.
5333         if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5334             Ctor->isDefaultConstructor()) {
5335           InstantiateDefaultCtorDefaultArgs(Ctor);
5336         }
5337       }
5338 
5339       // Instantiate the function body.
5340       Body = SubstStmt(Pattern, TemplateArgs);
5341 
5342       if (Body.isInvalid())
5343         Function->setInvalidDecl();
5344     }
5345     // FIXME: finishing the function body while in an expression evaluation
5346     // context seems wrong. Investigate more.
5347     ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5348 
5349     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5350 
5351     if (auto *Listener = getASTMutationListener())
5352       Listener->FunctionDefinitionInstantiated(Function);
5353 
5354     savedContext.pop();
5355   }
5356 
5357   DeclGroupRef DG(Function);
5358   Consumer.HandleTopLevelDecl(DG);
5359 
5360   // This class may have local implicit instantiations that need to be
5361   // instantiation within this scope.
5362   LocalInstantiations.perform();
5363   Scope.Exit();
5364   GlobalInstantiations.perform();
5365 }
5366 
5367 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
5368     VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5369     const TemplateArgumentList *PartialSpecArgs,
5370     const TemplateArgumentListInfo &TemplateArgsInfo,
5371     SmallVectorImpl<TemplateArgument> &Converted,
5372     SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5373     LocalInstantiationScope *StartingScope) {
5374   if (FromVar->isInvalidDecl())
5375     return nullptr;
5376 
5377   InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5378   if (Inst.isInvalid())
5379     return nullptr;
5380 
5381   // Instantiate the first declaration of the variable template: for a partial
5382   // specialization of a static data member template, the first declaration may
5383   // or may not be the declaration in the class; if it's in the class, we want
5384   // to instantiate a member in the class (a declaration), and if it's outside,
5385   // we want to instantiate a definition.
5386   //
5387   // If we're instantiating an explicitly-specialized member template or member
5388   // partial specialization, don't do this. The member specialization completely
5389   // replaces the original declaration in this case.
5390   bool IsMemberSpec = false;
5391   MultiLevelTemplateArgumentList MultiLevelList;
5392   if (auto *PartialSpec =
5393           dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5394     assert(PartialSpecArgs);
5395     IsMemberSpec = PartialSpec->isMemberSpecialization();
5396     MultiLevelList.addOuterTemplateArguments(
5397         PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
5398   } else {
5399     assert(VarTemplate == FromVar->getDescribedVarTemplate());
5400     IsMemberSpec = VarTemplate->isMemberSpecialization();
5401     MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
5402                                              /*Final=*/false);
5403   }
5404   if (!IsMemberSpec)
5405     FromVar = FromVar->getFirstDecl();
5406 
5407   TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5408                                         MultiLevelList);
5409 
5410   // TODO: Set LateAttrs and StartingScope ...
5411 
5412   return cast_or_null<VarTemplateSpecializationDecl>(
5413       Instantiator.VisitVarTemplateSpecializationDecl(
5414           VarTemplate, FromVar, TemplateArgsInfo, Converted));
5415 }
5416 
5417 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
5418     VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5419     const MultiLevelTemplateArgumentList &TemplateArgs) {
5420   assert(PatternDecl->isThisDeclarationADefinition() &&
5421          "don't have a definition to instantiate from");
5422 
5423   // Do substitution on the type of the declaration
5424   TypeSourceInfo *DI =
5425       SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5426                 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5427   if (!DI)
5428     return nullptr;
5429 
5430   // Update the type of this variable template specialization.
5431   VarSpec->setType(DI->getType());
5432 
5433   // Convert the declaration into a definition now.
5434   VarSpec->setCompleteDefinition();
5435 
5436   // Instantiate the initializer.
5437   InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5438 
5439   if (getLangOpts().OpenCL)
5440     deduceOpenCLAddressSpace(VarSpec);
5441 
5442   return VarSpec;
5443 }
5444 
5445 void Sema::BuildVariableInstantiation(
5446     VarDecl *NewVar, VarDecl *OldVar,
5447     const MultiLevelTemplateArgumentList &TemplateArgs,
5448     LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5449     LocalInstantiationScope *StartingScope,
5450     bool InstantiatingVarTemplate,
5451     VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5452   // Instantiating a partial specialization to produce a partial
5453   // specialization.
5454   bool InstantiatingVarTemplatePartialSpec =
5455       isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5456       isa<VarTemplatePartialSpecializationDecl>(NewVar);
5457   // Instantiating from a variable template (or partial specialization) to
5458   // produce a variable template specialization.
5459   bool InstantiatingSpecFromTemplate =
5460       isa<VarTemplateSpecializationDecl>(NewVar) &&
5461       (OldVar->getDescribedVarTemplate() ||
5462        isa<VarTemplatePartialSpecializationDecl>(OldVar));
5463 
5464   // If we are instantiating a local extern declaration, the
5465   // instantiation belongs lexically to the containing function.
5466   // If we are instantiating a static data member defined
5467   // out-of-line, the instantiation will have the same lexical
5468   // context (which will be a namespace scope) as the template.
5469   if (OldVar->isLocalExternDecl()) {
5470     NewVar->setLocalExternDecl();
5471     NewVar->setLexicalDeclContext(Owner);
5472   } else if (OldVar->isOutOfLine())
5473     NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5474   NewVar->setTSCSpec(OldVar->getTSCSpec());
5475   NewVar->setInitStyle(OldVar->getInitStyle());
5476   NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5477   NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5478   NewVar->setConstexpr(OldVar->isConstexpr());
5479   NewVar->setInitCapture(OldVar->isInitCapture());
5480   NewVar->setPreviousDeclInSameBlockScope(
5481       OldVar->isPreviousDeclInSameBlockScope());
5482   NewVar->setAccess(OldVar->getAccess());
5483 
5484   if (!OldVar->isStaticDataMember()) {
5485     if (OldVar->isUsed(false))
5486       NewVar->setIsUsed();
5487     NewVar->setReferenced(OldVar->isReferenced());
5488   }
5489 
5490   InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5491 
5492   LookupResult Previous(
5493       *this, NewVar->getDeclName(), NewVar->getLocation(),
5494       NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5495                                   : Sema::LookupOrdinaryName,
5496       NewVar->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
5497                                   : forRedeclarationInCurContext());
5498 
5499   if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5500       (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5501        OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5502     // We have a previous declaration. Use that one, so we merge with the
5503     // right type.
5504     if (NamedDecl *NewPrev = FindInstantiatedDecl(
5505             NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5506       Previous.addDecl(NewPrev);
5507   } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5508              OldVar->hasLinkage()) {
5509     LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5510   } else if (PrevDeclForVarTemplateSpecialization) {
5511     Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5512   }
5513   CheckVariableDeclaration(NewVar, Previous);
5514 
5515   if (!InstantiatingVarTemplate) {
5516     NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5517     if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5518       NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5519   }
5520 
5521   if (!OldVar->isOutOfLine()) {
5522     if (NewVar->getDeclContext()->isFunctionOrMethod())
5523       CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
5524   }
5525 
5526   // Link instantiations of static data members back to the template from
5527   // which they were instantiated.
5528   //
5529   // Don't do this when instantiating a template (we link the template itself
5530   // back in that case) nor when instantiating a static data member template
5531   // (that's not a member specialization).
5532   if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5533       !InstantiatingSpecFromTemplate)
5534     NewVar->setInstantiationOfStaticDataMember(OldVar,
5535                                                TSK_ImplicitInstantiation);
5536 
5537   // If the pattern is an (in-class) explicit specialization, then the result
5538   // is also an explicit specialization.
5539   if (VarTemplateSpecializationDecl *OldVTSD =
5540           dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5541     if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5542         !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5543       cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5544           TSK_ExplicitSpecialization);
5545   }
5546 
5547   // Forward the mangling number from the template to the instantiated decl.
5548   Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
5549   Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
5550 
5551   // Figure out whether to eagerly instantiate the initializer.
5552   if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5553     // We're producing a template. Don't instantiate the initializer yet.
5554   } else if (NewVar->getType()->isUndeducedType()) {
5555     // We need the type to complete the declaration of the variable.
5556     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5557   } else if (InstantiatingSpecFromTemplate ||
5558              (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5559               !NewVar->isThisDeclarationADefinition())) {
5560     // Delay instantiation of the initializer for variable template
5561     // specializations or inline static data members until a definition of the
5562     // variable is needed.
5563   } else {
5564     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5565   }
5566 
5567   // Diagnose unused local variables with dependent types, where the diagnostic
5568   // will have been deferred.
5569   if (!NewVar->isInvalidDecl() &&
5570       NewVar->getDeclContext()->isFunctionOrMethod() &&
5571       OldVar->getType()->isDependentType())
5572     DiagnoseUnusedDecl(NewVar);
5573 }
5574 
5575 void Sema::InstantiateVariableInitializer(
5576     VarDecl *Var, VarDecl *OldVar,
5577     const MultiLevelTemplateArgumentList &TemplateArgs) {
5578   if (ASTMutationListener *L = getASTContext().getASTMutationListener())
5579     L->VariableDefinitionInstantiated(Var);
5580 
5581   // We propagate the 'inline' flag with the initializer, because it
5582   // would otherwise imply that the variable is a definition for a
5583   // non-static data member.
5584   if (OldVar->isInlineSpecified())
5585     Var->setInlineSpecified();
5586   else if (OldVar->isInline())
5587     Var->setImplicitlyInline();
5588 
5589   if (OldVar->getInit()) {
5590     EnterExpressionEvaluationContext Evaluated(
5591         *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
5592 
5593     currentEvaluationContext().InLifetimeExtendingContext =
5594         parentEvaluationContext().InLifetimeExtendingContext;
5595     currentEvaluationContext().RebuildDefaultArgOrDefaultInit =
5596         parentEvaluationContext().RebuildDefaultArgOrDefaultInit;
5597     // Instantiate the initializer.
5598     ExprResult Init;
5599 
5600     {
5601       ContextRAII SwitchContext(*this, Var->getDeclContext());
5602       Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5603                               OldVar->getInitStyle() == VarDecl::CallInit);
5604     }
5605 
5606     if (!Init.isInvalid()) {
5607       Expr *InitExpr = Init.get();
5608 
5609       if (Var->hasAttr<DLLImportAttr>() &&
5610           (!InitExpr ||
5611            !InitExpr->isConstantInitializer(getASTContext(), false))) {
5612         // Do not dynamically initialize dllimport variables.
5613       } else if (InitExpr) {
5614         bool DirectInit = OldVar->isDirectInit();
5615         AddInitializerToDecl(Var, InitExpr, DirectInit);
5616       } else
5617         ActOnUninitializedDecl(Var);
5618     } else {
5619       // FIXME: Not too happy about invalidating the declaration
5620       // because of a bogus initializer.
5621       Var->setInvalidDecl();
5622     }
5623   } else {
5624     // `inline` variables are a definition and declaration all in one; we won't
5625     // pick up an initializer from anywhere else.
5626     if (Var->isStaticDataMember() && !Var->isInline()) {
5627       if (!Var->isOutOfLine())
5628         return;
5629 
5630       // If the declaration inside the class had an initializer, don't add
5631       // another one to the out-of-line definition.
5632       if (OldVar->getFirstDecl()->hasInit())
5633         return;
5634     }
5635 
5636     // We'll add an initializer to a for-range declaration later.
5637     if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5638       return;
5639 
5640     ActOnUninitializedDecl(Var);
5641   }
5642 
5643   if (getLangOpts().CUDA)
5644     CUDA().checkAllowedInitializer(Var);
5645 }
5646 
5647 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
5648                                          VarDecl *Var, bool Recursive,
5649                                       bool DefinitionRequired, bool AtEndOfTU) {
5650   if (Var->isInvalidDecl())
5651     return;
5652 
5653   // Never instantiate an explicitly-specialized entity.
5654   TemplateSpecializationKind TSK =
5655       Var->getTemplateSpecializationKindForInstantiation();
5656   if (TSK == TSK_ExplicitSpecialization)
5657     return;
5658 
5659   // Find the pattern and the arguments to substitute into it.
5660   VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5661   assert(PatternDecl && "no pattern for templated variable");
5662   MultiLevelTemplateArgumentList TemplateArgs =
5663       getTemplateInstantiationArgs(Var);
5664 
5665   VarTemplateSpecializationDecl *VarSpec =
5666       dyn_cast<VarTemplateSpecializationDecl>(Var);
5667   if (VarSpec) {
5668     // If this is a static data member template, there might be an
5669     // uninstantiated initializer on the declaration. If so, instantiate
5670     // it now.
5671     //
5672     // FIXME: This largely duplicates what we would do below. The difference
5673     // is that along this path we may instantiate an initializer from an
5674     // in-class declaration of the template and instantiate the definition
5675     // from a separate out-of-class definition.
5676     if (PatternDecl->isStaticDataMember() &&
5677         (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5678         !Var->hasInit()) {
5679       // FIXME: Factor out the duplicated instantiation context setup/tear down
5680       // code here.
5681       InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5682       if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5683         return;
5684       PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5685                                           "instantiating variable initializer");
5686 
5687       // The instantiation is visible here, even if it was first declared in an
5688       // unimported module.
5689       Var->setVisibleDespiteOwningModule();
5690 
5691       // If we're performing recursive template instantiation, create our own
5692       // queue of pending implicit instantiations that we will instantiate
5693       // later, while we're still within our own instantiation context.
5694       GlobalEagerInstantiationScope GlobalInstantiations(*this,
5695                                                          /*Enabled=*/Recursive);
5696       LocalInstantiationScope Local(*this);
5697       LocalEagerInstantiationScope LocalInstantiations(*this);
5698 
5699       // Enter the scope of this instantiation. We don't use
5700       // PushDeclContext because we don't have a scope.
5701       ContextRAII PreviousContext(*this, Var->getDeclContext());
5702       InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5703       PreviousContext.pop();
5704 
5705       // This variable may have local implicit instantiations that need to be
5706       // instantiated within this scope.
5707       LocalInstantiations.perform();
5708       Local.Exit();
5709       GlobalInstantiations.perform();
5710     }
5711   } else {
5712     assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5713            "not a static data member?");
5714   }
5715 
5716   VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5717 
5718   // If we don't have a definition of the variable template, we won't perform
5719   // any instantiation. Rather, we rely on the user to instantiate this
5720   // definition (or provide a specialization for it) in another translation
5721   // unit.
5722   if (!Def && !DefinitionRequired) {
5723     if (TSK == TSK_ExplicitInstantiationDefinition) {
5724       PendingInstantiations.push_back(
5725         std::make_pair(Var, PointOfInstantiation));
5726     } else if (TSK == TSK_ImplicitInstantiation) {
5727       // Warn about missing definition at the end of translation unit.
5728       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5729           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5730         Diag(PointOfInstantiation, diag::warn_var_template_missing)
5731           << Var;
5732         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5733         if (getLangOpts().CPlusPlus11)
5734           Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5735       }
5736       return;
5737     }
5738   }
5739 
5740   // FIXME: We need to track the instantiation stack in order to know which
5741   // definitions should be visible within this instantiation.
5742   // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5743   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5744                                      /*InstantiatedFromMember*/false,
5745                                      PatternDecl, Def, TSK,
5746                                      /*Complain*/DefinitionRequired))
5747     return;
5748 
5749   // C++11 [temp.explicit]p10:
5750   //   Except for inline functions, const variables of literal types, variables
5751   //   of reference types, [...] explicit instantiation declarations
5752   //   have the effect of suppressing the implicit instantiation of the entity
5753   //   to which they refer.
5754   //
5755   // FIXME: That's not exactly the same as "might be usable in constant
5756   // expressions", which only allows constexpr variables and const integral
5757   // types, not arbitrary const literal types.
5758   if (TSK == TSK_ExplicitInstantiationDeclaration &&
5759       !Var->mightBeUsableInConstantExpressions(getASTContext()))
5760     return;
5761 
5762   // Make sure to pass the instantiated variable to the consumer at the end.
5763   struct PassToConsumerRAII {
5764     ASTConsumer &Consumer;
5765     VarDecl *Var;
5766 
5767     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5768       : Consumer(Consumer), Var(Var) { }
5769 
5770     ~PassToConsumerRAII() {
5771       Consumer.HandleCXXStaticMemberVarInstantiation(Var);
5772     }
5773   } PassToConsumerRAII(Consumer, Var);
5774 
5775   // If we already have a definition, we're done.
5776   if (VarDecl *Def = Var->getDefinition()) {
5777     // We may be explicitly instantiating something we've already implicitly
5778     // instantiated.
5779     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
5780                                        PointOfInstantiation);
5781     return;
5782   }
5783 
5784   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5785   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5786     return;
5787   PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5788                                       "instantiating variable definition");
5789 
5790   // If we're performing recursive template instantiation, create our own
5791   // queue of pending implicit instantiations that we will instantiate later,
5792   // while we're still within our own instantiation context.
5793   GlobalEagerInstantiationScope GlobalInstantiations(*this,
5794                                                      /*Enabled=*/Recursive);
5795 
5796   // Enter the scope of this instantiation. We don't use
5797   // PushDeclContext because we don't have a scope.
5798   ContextRAII PreviousContext(*this, Var->getDeclContext());
5799   LocalInstantiationScope Local(*this);
5800 
5801   LocalEagerInstantiationScope LocalInstantiations(*this);
5802 
5803   VarDecl *OldVar = Var;
5804   if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5805     // We're instantiating an inline static data member whose definition was
5806     // provided inside the class.
5807     InstantiateVariableInitializer(Var, Def, TemplateArgs);
5808   } else if (!VarSpec) {
5809     Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5810                                           TemplateArgs));
5811   } else if (Var->isStaticDataMember() &&
5812              Var->getLexicalDeclContext()->isRecord()) {
5813     // We need to instantiate the definition of a static data member template,
5814     // and all we have is the in-class declaration of it. Instantiate a separate
5815     // declaration of the definition.
5816     TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5817                                           TemplateArgs);
5818 
5819     TemplateArgumentListInfo TemplateArgInfo;
5820     if (const ASTTemplateArgumentListInfo *ArgInfo =
5821             VarSpec->getTemplateArgsAsWritten()) {
5822       TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5823       TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5824       for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5825         TemplateArgInfo.addArgument(Arg);
5826     }
5827 
5828     Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5829         VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5830         VarSpec->getTemplateArgs().asArray(), VarSpec));
5831     if (Var) {
5832       llvm::PointerUnion<VarTemplateDecl *,
5833                          VarTemplatePartialSpecializationDecl *> PatternPtr =
5834           VarSpec->getSpecializedTemplateOrPartial();
5835       if (VarTemplatePartialSpecializationDecl *Partial =
5836           PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5837         cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5838             Partial, &VarSpec->getTemplateInstantiationArgs());
5839 
5840       // Attach the initializer.
5841       InstantiateVariableInitializer(Var, Def, TemplateArgs);
5842     }
5843   } else
5844     // Complete the existing variable's definition with an appropriately
5845     // substituted type and initializer.
5846     Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5847 
5848   PreviousContext.pop();
5849 
5850   if (Var) {
5851     PassToConsumerRAII.Var = Var;
5852     Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5853                                        OldVar->getPointOfInstantiation());
5854   }
5855 
5856   // This variable may have local implicit instantiations that need to be
5857   // instantiated within this scope.
5858   LocalInstantiations.perform();
5859   Local.Exit();
5860   GlobalInstantiations.perform();
5861 }
5862 
5863 void
5864 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5865                                  const CXXConstructorDecl *Tmpl,
5866                            const MultiLevelTemplateArgumentList &TemplateArgs) {
5867 
5868   SmallVector<CXXCtorInitializer*, 4> NewInits;
5869   bool AnyErrors = Tmpl->isInvalidDecl();
5870 
5871   // Instantiate all the initializers.
5872   for (const auto *Init : Tmpl->inits()) {
5873     // Only instantiate written initializers, let Sema re-construct implicit
5874     // ones.
5875     if (!Init->isWritten())
5876       continue;
5877 
5878     SourceLocation EllipsisLoc;
5879 
5880     if (Init->isPackExpansion()) {
5881       // This is a pack expansion. We should expand it now.
5882       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5883       SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5884       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5885       collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5886       bool ShouldExpand = false;
5887       bool RetainExpansion = false;
5888       std::optional<unsigned> NumExpansions;
5889       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5890                                           BaseTL.getSourceRange(),
5891                                           Unexpanded,
5892                                           TemplateArgs, ShouldExpand,
5893                                           RetainExpansion,
5894                                           NumExpansions)) {
5895         AnyErrors = true;
5896         New->setInvalidDecl();
5897         continue;
5898       }
5899       assert(ShouldExpand && "Partial instantiation of base initializer?");
5900 
5901       // Loop over all of the arguments in the argument pack(s),
5902       for (unsigned I = 0; I != *NumExpansions; ++I) {
5903         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5904 
5905         // Instantiate the initializer.
5906         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5907                                                /*CXXDirectInit=*/true);
5908         if (TempInit.isInvalid()) {
5909           AnyErrors = true;
5910           break;
5911         }
5912 
5913         // Instantiate the base type.
5914         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5915                                               TemplateArgs,
5916                                               Init->getSourceLocation(),
5917                                               New->getDeclName());
5918         if (!BaseTInfo) {
5919           AnyErrors = true;
5920           break;
5921         }
5922 
5923         // Build the initializer.
5924         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5925                                                      BaseTInfo, TempInit.get(),
5926                                                      New->getParent(),
5927                                                      SourceLocation());
5928         if (NewInit.isInvalid()) {
5929           AnyErrors = true;
5930           break;
5931         }
5932 
5933         NewInits.push_back(NewInit.get());
5934       }
5935 
5936       continue;
5937     }
5938 
5939     // Instantiate the initializer.
5940     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5941                                            /*CXXDirectInit=*/true);
5942     if (TempInit.isInvalid()) {
5943       AnyErrors = true;
5944       continue;
5945     }
5946 
5947     MemInitResult NewInit;
5948     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5949       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5950                                         TemplateArgs,
5951                                         Init->getSourceLocation(),
5952                                         New->getDeclName());
5953       if (!TInfo) {
5954         AnyErrors = true;
5955         New->setInvalidDecl();
5956         continue;
5957       }
5958 
5959       if (Init->isBaseInitializer())
5960         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5961                                        New->getParent(), EllipsisLoc);
5962       else
5963         NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5964                                   cast<CXXRecordDecl>(CurContext->getParent()));
5965     } else if (Init->isMemberInitializer()) {
5966       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5967                                                      Init->getMemberLocation(),
5968                                                      Init->getMember(),
5969                                                      TemplateArgs));
5970       if (!Member) {
5971         AnyErrors = true;
5972         New->setInvalidDecl();
5973         continue;
5974       }
5975 
5976       NewInit = BuildMemberInitializer(Member, TempInit.get(),
5977                                        Init->getSourceLocation());
5978     } else if (Init->isIndirectMemberInitializer()) {
5979       IndirectFieldDecl *IndirectMember =
5980          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5981                                  Init->getMemberLocation(),
5982                                  Init->getIndirectMember(), TemplateArgs));
5983 
5984       if (!IndirectMember) {
5985         AnyErrors = true;
5986         New->setInvalidDecl();
5987         continue;
5988       }
5989 
5990       NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5991                                        Init->getSourceLocation());
5992     }
5993 
5994     if (NewInit.isInvalid()) {
5995       AnyErrors = true;
5996       New->setInvalidDecl();
5997     } else {
5998       NewInits.push_back(NewInit.get());
5999     }
6000   }
6001 
6002   // Assign all the initializers to the new constructor.
6003   ActOnMemInitializers(New,
6004                        /*FIXME: ColonLoc */
6005                        SourceLocation(),
6006                        NewInits,
6007                        AnyErrors);
6008 }
6009 
6010 // TODO: this could be templated if the various decl types used the
6011 // same method name.
6012 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
6013                               ClassTemplateDecl *Instance) {
6014   Pattern = Pattern->getCanonicalDecl();
6015 
6016   do {
6017     Instance = Instance->getCanonicalDecl();
6018     if (Pattern == Instance) return true;
6019     Instance = Instance->getInstantiatedFromMemberTemplate();
6020   } while (Instance);
6021 
6022   return false;
6023 }
6024 
6025 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
6026                               FunctionTemplateDecl *Instance) {
6027   Pattern = Pattern->getCanonicalDecl();
6028 
6029   do {
6030     Instance = Instance->getCanonicalDecl();
6031     if (Pattern == Instance) return true;
6032     Instance = Instance->getInstantiatedFromMemberTemplate();
6033   } while (Instance);
6034 
6035   return false;
6036 }
6037 
6038 static bool
6039 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
6040                   ClassTemplatePartialSpecializationDecl *Instance) {
6041   Pattern
6042     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
6043   do {
6044     Instance = cast<ClassTemplatePartialSpecializationDecl>(
6045                                                 Instance->getCanonicalDecl());
6046     if (Pattern == Instance)
6047       return true;
6048     Instance = Instance->getInstantiatedFromMember();
6049   } while (Instance);
6050 
6051   return false;
6052 }
6053 
6054 static bool isInstantiationOf(CXXRecordDecl *Pattern,
6055                               CXXRecordDecl *Instance) {
6056   Pattern = Pattern->getCanonicalDecl();
6057 
6058   do {
6059     Instance = Instance->getCanonicalDecl();
6060     if (Pattern == Instance) return true;
6061     Instance = Instance->getInstantiatedFromMemberClass();
6062   } while (Instance);
6063 
6064   return false;
6065 }
6066 
6067 static bool isInstantiationOf(FunctionDecl *Pattern,
6068                               FunctionDecl *Instance) {
6069   Pattern = Pattern->getCanonicalDecl();
6070 
6071   do {
6072     Instance = Instance->getCanonicalDecl();
6073     if (Pattern == Instance) return true;
6074     Instance = Instance->getInstantiatedFromMemberFunction();
6075   } while (Instance);
6076 
6077   return false;
6078 }
6079 
6080 static bool isInstantiationOf(EnumDecl *Pattern,
6081                               EnumDecl *Instance) {
6082   Pattern = Pattern->getCanonicalDecl();
6083 
6084   do {
6085     Instance = Instance->getCanonicalDecl();
6086     if (Pattern == Instance) return true;
6087     Instance = Instance->getInstantiatedFromMemberEnum();
6088   } while (Instance);
6089 
6090   return false;
6091 }
6092 
6093 static bool isInstantiationOf(UsingShadowDecl *Pattern,
6094                               UsingShadowDecl *Instance,
6095                               ASTContext &C) {
6096   return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
6097                             Pattern);
6098 }
6099 
6100 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
6101                               ASTContext &C) {
6102   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
6103 }
6104 
6105 template<typename T>
6106 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
6107                                                  ASTContext &Ctx) {
6108   // An unresolved using declaration can instantiate to an unresolved using
6109   // declaration, or to a using declaration or a using declaration pack.
6110   //
6111   // Multiple declarations can claim to be instantiated from an unresolved
6112   // using declaration if it's a pack expansion. We want the UsingPackDecl
6113   // in that case, not the individual UsingDecls within the pack.
6114   bool OtherIsPackExpansion;
6115   NamedDecl *OtherFrom;
6116   if (auto *OtherUUD = dyn_cast<T>(Other)) {
6117     OtherIsPackExpansion = OtherUUD->isPackExpansion();
6118     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
6119   } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
6120     OtherIsPackExpansion = true;
6121     OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
6122   } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
6123     OtherIsPackExpansion = false;
6124     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
6125   } else {
6126     return false;
6127   }
6128   return Pattern->isPackExpansion() == OtherIsPackExpansion &&
6129          declaresSameEntity(OtherFrom, Pattern);
6130 }
6131 
6132 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
6133                                               VarDecl *Instance) {
6134   assert(Instance->isStaticDataMember());
6135 
6136   Pattern = Pattern->getCanonicalDecl();
6137 
6138   do {
6139     Instance = Instance->getCanonicalDecl();
6140     if (Pattern == Instance) return true;
6141     Instance = Instance->getInstantiatedFromStaticDataMember();
6142   } while (Instance);
6143 
6144   return false;
6145 }
6146 
6147 // Other is the prospective instantiation
6148 // D is the prospective pattern
6149 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
6150   if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6151     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
6152 
6153   if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6154     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
6155 
6156   if (D->getKind() != Other->getKind())
6157     return false;
6158 
6159   if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6160     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
6161 
6162   if (auto *Function = dyn_cast<FunctionDecl>(Other))
6163     return isInstantiationOf(cast<FunctionDecl>(D), Function);
6164 
6165   if (auto *Enum = dyn_cast<EnumDecl>(Other))
6166     return isInstantiationOf(cast<EnumDecl>(D), Enum);
6167 
6168   if (auto *Var = dyn_cast<VarDecl>(Other))
6169     if (Var->isStaticDataMember())
6170       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
6171 
6172   if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6173     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
6174 
6175   if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6176     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
6177 
6178   if (auto *PartialSpec =
6179           dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6180     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
6181                              PartialSpec);
6182 
6183   if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6184     if (!Field->getDeclName()) {
6185       // This is an unnamed field.
6186       return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
6187                                 cast<FieldDecl>(D));
6188     }
6189   }
6190 
6191   if (auto *Using = dyn_cast<UsingDecl>(Other))
6192     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6193 
6194   if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6195     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6196 
6197   return D->getDeclName() &&
6198          D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6199 }
6200 
6201 template<typename ForwardIterator>
6202 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
6203                                       NamedDecl *D,
6204                                       ForwardIterator first,
6205                                       ForwardIterator last) {
6206   for (; first != last; ++first)
6207     if (isInstantiationOf(Ctx, D, *first))
6208       return cast<NamedDecl>(*first);
6209 
6210   return nullptr;
6211 }
6212 
6213 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
6214                           const MultiLevelTemplateArgumentList &TemplateArgs) {
6215   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6216     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6217     return cast_or_null<DeclContext>(ID);
6218   } else return DC;
6219 }
6220 
6221 /// Determine whether the given context is dependent on template parameters at
6222 /// level \p Level or below.
6223 ///
6224 /// Sometimes we only substitute an inner set of template arguments and leave
6225 /// the outer templates alone. In such cases, contexts dependent only on the
6226 /// outer levels are not effectively dependent.
6227 static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6228   if (!DC->isDependentContext())
6229     return false;
6230   if (!Level)
6231     return true;
6232   return cast<Decl>(DC)->getTemplateDepth() > Level;
6233 }
6234 
6235 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6236                           const MultiLevelTemplateArgumentList &TemplateArgs,
6237                           bool FindingInstantiatedContext) {
6238   DeclContext *ParentDC = D->getDeclContext();
6239   // Determine whether our parent context depends on any of the template
6240   // arguments we're currently substituting.
6241   bool ParentDependsOnArgs = isDependentContextAtLevel(
6242       ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6243   // FIXME: Parameters of pointer to functions (y below) that are themselves
6244   // parameters (p below) can have their ParentDC set to the translation-unit
6245   // - thus we can not consistently check if the ParentDC of such a parameter
6246   // is Dependent or/and a FunctionOrMethod.
6247   // For e.g. this code, during Template argument deduction tries to
6248   // find an instantiated decl for (T y) when the ParentDC for y is
6249   // the translation unit.
6250   //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6251   //   float baz(float(*)()) { return 0.0; }
6252   //   Foo(baz);
6253   // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6254   // it gets here, always has a FunctionOrMethod as its ParentDC??
6255   // For now:
6256   //  - as long as we have a ParmVarDecl whose parent is non-dependent and
6257   //    whose type is not instantiation dependent, do nothing to the decl
6258   //  - otherwise find its instantiated decl.
6259   if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6260       !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6261     return D;
6262   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6263       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6264       (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6265                                isa<OMPDeclareReductionDecl>(ParentDC) ||
6266                                isa<OMPDeclareMapperDecl>(ParentDC))) ||
6267       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6268        cast<CXXRecordDecl>(D)->getTemplateDepth() >
6269            TemplateArgs.getNumRetainedOuterLevels())) {
6270     // D is a local of some kind. Look into the map of local
6271     // declarations to their instantiations.
6272     if (CurrentInstantiationScope) {
6273       if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6274         if (Decl *FD = Found->dyn_cast<Decl *>()) {
6275           if (auto *BD = dyn_cast<BindingDecl>(FD);
6276               BD && BD->isParameterPack() &&
6277               ArgumentPackSubstitutionIndex != -1) {
6278             auto *DRE = cast<DeclRefExpr>(
6279                 BD->getBindingPackExprs()[ArgumentPackSubstitutionIndex]);
6280             return cast<NamedDecl>(DRE->getDecl());
6281           }
6282           return cast<NamedDecl>(FD);
6283         }
6284 
6285         int PackIdx = ArgumentPackSubstitutionIndex;
6286         assert(PackIdx != -1 &&
6287                "found declaration pack but not pack expanding");
6288         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6289         return cast<NamedDecl>((*cast<DeclArgumentPack *>(*Found))[PackIdx]);
6290       }
6291     }
6292 
6293     // If we're performing a partial substitution during template argument
6294     // deduction, we may not have values for template parameters yet. They
6295     // just map to themselves.
6296     if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6297         isa<TemplateTemplateParmDecl>(D))
6298       return D;
6299 
6300     if (D->isInvalidDecl())
6301       return nullptr;
6302 
6303     // Normally this function only searches for already instantiated declaration
6304     // however we have to make an exclusion for local types used before
6305     // definition as in the code:
6306     //
6307     //   template<typename T> void f1() {
6308     //     void g1(struct x1);
6309     //     struct x1 {};
6310     //   }
6311     //
6312     // In this case instantiation of the type of 'g1' requires definition of
6313     // 'x1', which is defined later. Error recovery may produce an enum used
6314     // before definition. In these cases we need to instantiate relevant
6315     // declarations here.
6316     bool NeedInstantiate = false;
6317     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6318       NeedInstantiate = RD->isLocalClass();
6319     else if (isa<TypedefNameDecl>(D) &&
6320              isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6321       NeedInstantiate = true;
6322     else
6323       NeedInstantiate = isa<EnumDecl>(D);
6324     if (NeedInstantiate) {
6325       Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6326       CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6327       return cast<TypeDecl>(Inst);
6328     }
6329 
6330     // If we didn't find the decl, then we must have a label decl that hasn't
6331     // been found yet.  Lazily instantiate it and return it now.
6332     assert(isa<LabelDecl>(D));
6333 
6334     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6335     assert(Inst && "Failed to instantiate label??");
6336 
6337     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6338     return cast<LabelDecl>(Inst);
6339   }
6340 
6341   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6342     if (!Record->isDependentContext())
6343       return D;
6344 
6345     // Determine whether this record is the "templated" declaration describing
6346     // a class template or class template specialization.
6347     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6348     if (ClassTemplate)
6349       ClassTemplate = ClassTemplate->getCanonicalDecl();
6350     else if (ClassTemplateSpecializationDecl *Spec =
6351                  dyn_cast<ClassTemplateSpecializationDecl>(Record))
6352       ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6353 
6354     // Walk the current context to find either the record or an instantiation of
6355     // it.
6356     DeclContext *DC = CurContext;
6357     while (!DC->isFileContext()) {
6358       // If we're performing substitution while we're inside the template
6359       // definition, we'll find our own context. We're done.
6360       if (DC->Equals(Record))
6361         return Record;
6362 
6363       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6364         // Check whether we're in the process of instantiating a class template
6365         // specialization of the template we're mapping.
6366         if (ClassTemplateSpecializationDecl *InstSpec
6367                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6368           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6369           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6370             return InstRecord;
6371         }
6372 
6373         // Check whether we're in the process of instantiating a member class.
6374         if (isInstantiationOf(Record, InstRecord))
6375           return InstRecord;
6376       }
6377 
6378       // Move to the outer template scope.
6379       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6380         if (FD->getFriendObjectKind() &&
6381             FD->getNonTransparentDeclContext()->isFileContext()) {
6382           DC = FD->getLexicalDeclContext();
6383           continue;
6384         }
6385         // An implicit deduction guide acts as if it's within the class template
6386         // specialization described by its name and first N template params.
6387         auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6388         if (Guide && Guide->isImplicit()) {
6389           TemplateDecl *TD = Guide->getDeducedTemplate();
6390           // Convert the arguments to an "as-written" list.
6391           TemplateArgumentListInfo Args(Loc, Loc);
6392           for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6393                                         TD->getTemplateParameters()->size())) {
6394             ArrayRef<TemplateArgument> Unpacked(Arg);
6395             if (Arg.getKind() == TemplateArgument::Pack)
6396               Unpacked = Arg.pack_elements();
6397             for (TemplateArgument UnpackedArg : Unpacked)
6398               Args.addArgument(
6399                   getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6400           }
6401           QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
6402           // We may get a non-null type with errors, in which case
6403           // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
6404           // happens when one of the template arguments is an invalid
6405           // expression. We return early to avoid triggering the assertion
6406           // about the `CodeSynthesisContext`.
6407           if (T.isNull() || T->containsErrors())
6408             return nullptr;
6409           CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
6410 
6411           if (!SubstRecord) {
6412             // T can be a dependent TemplateSpecializationType when performing a
6413             // substitution for building a deduction guide or for template
6414             // argument deduction in the process of rebuilding immediate
6415             // expressions. (Because the default argument that involves a lambda
6416             // is untransformed and thus could be dependent at this point.)
6417             assert(SemaRef.RebuildingImmediateInvocation ||
6418                    CodeSynthesisContexts.back().Kind ==
6419                        CodeSynthesisContext::BuildingDeductionGuides);
6420             // Return a nullptr as a sentinel value, we handle it properly in
6421             // the TemplateInstantiator::TransformInjectedClassNameType
6422             // override, which we transform it to a TemplateSpecializationType.
6423             return nullptr;
6424           }
6425           // Check that this template-id names the primary template and not a
6426           // partial or explicit specialization. (In the latter cases, it's
6427           // meaningless to attempt to find an instantiation of D within the
6428           // specialization.)
6429           // FIXME: The standard doesn't say what should happen here.
6430           if (FindingInstantiatedContext &&
6431               usesPartialOrExplicitSpecialization(
6432                   Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6433             Diag(Loc, diag::err_specialization_not_primary_template)
6434               << T << (SubstRecord->getTemplateSpecializationKind() ==
6435                            TSK_ExplicitSpecialization);
6436             return nullptr;
6437           }
6438           DC = SubstRecord;
6439           continue;
6440         }
6441       }
6442 
6443       DC = DC->getParent();
6444     }
6445 
6446     // Fall through to deal with other dependent record types (e.g.,
6447     // anonymous unions in class templates).
6448   }
6449 
6450   if (!ParentDependsOnArgs)
6451     return D;
6452 
6453   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6454   if (!ParentDC)
6455     return nullptr;
6456 
6457   if (ParentDC != D->getDeclContext()) {
6458     // We performed some kind of instantiation in the parent context,
6459     // so now we need to look into the instantiated parent context to
6460     // find the instantiation of the declaration D.
6461 
6462     // If our context used to be dependent, we may need to instantiate
6463     // it before performing lookup into that context.
6464     bool IsBeingInstantiated = false;
6465     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6466       if (!Spec->isDependentContext()) {
6467         QualType T = Context.getTypeDeclType(Spec);
6468         const RecordType *Tag = T->getAs<RecordType>();
6469         assert(Tag && "type of non-dependent record is not a RecordType");
6470         if (Tag->isBeingDefined())
6471           IsBeingInstantiated = true;
6472         if (!Tag->isBeingDefined() &&
6473             RequireCompleteType(Loc, T, diag::err_incomplete_type))
6474           return nullptr;
6475 
6476         ParentDC = Tag->getDecl();
6477       }
6478     }
6479 
6480     NamedDecl *Result = nullptr;
6481     // FIXME: If the name is a dependent name, this lookup won't necessarily
6482     // find it. Does that ever matter?
6483     if (auto Name = D->getDeclName()) {
6484       DeclarationNameInfo NameInfo(Name, D->getLocation());
6485       DeclarationNameInfo NewNameInfo =
6486           SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6487       Name = NewNameInfo.getName();
6488       if (!Name)
6489         return nullptr;
6490       DeclContext::lookup_result Found = ParentDC->lookup(Name);
6491 
6492       Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6493     } else {
6494       // Since we don't have a name for the entity we're looking for,
6495       // our only option is to walk through all of the declarations to
6496       // find that name. This will occur in a few cases:
6497       //
6498       //   - anonymous struct/union within a template
6499       //   - unnamed class/struct/union/enum within a template
6500       //
6501       // FIXME: Find a better way to find these instantiations!
6502       Result = findInstantiationOf(Context, D,
6503                                    ParentDC->decls_begin(),
6504                                    ParentDC->decls_end());
6505     }
6506 
6507     if (!Result) {
6508       if (isa<UsingShadowDecl>(D)) {
6509         // UsingShadowDecls can instantiate to nothing because of using hiding.
6510       } else if (hasUncompilableErrorOccurred()) {
6511         // We've already complained about some ill-formed code, so most likely
6512         // this declaration failed to instantiate. There's no point in
6513         // complaining further, since this is normal in invalid code.
6514         // FIXME: Use more fine-grained 'invalid' tracking for this.
6515       } else if (IsBeingInstantiated) {
6516         // The class in which this member exists is currently being
6517         // instantiated, and we haven't gotten around to instantiating this
6518         // member yet. This can happen when the code uses forward declarations
6519         // of member classes, and introduces ordering dependencies via
6520         // template instantiation.
6521         Diag(Loc, diag::err_member_not_yet_instantiated)
6522           << D->getDeclName()
6523           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6524         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6525       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6526         // This enumeration constant was found when the template was defined,
6527         // but can't be found in the instantiation. This can happen if an
6528         // unscoped enumeration member is explicitly specialized.
6529         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6530         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6531                                                              TemplateArgs));
6532         assert(Spec->getTemplateSpecializationKind() ==
6533                  TSK_ExplicitSpecialization);
6534         Diag(Loc, diag::err_enumerator_does_not_exist)
6535           << D->getDeclName()
6536           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6537         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6538           << Context.getTypeDeclType(Spec);
6539       } else {
6540         // We should have found something, but didn't.
6541         llvm_unreachable("Unable to find instantiation of declaration!");
6542       }
6543     }
6544 
6545     D = Result;
6546   }
6547 
6548   return D;
6549 }
6550 
6551 void Sema::PerformPendingInstantiations(bool LocalOnly) {
6552   std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6553   while (!PendingLocalImplicitInstantiations.empty() ||
6554          (!LocalOnly && !PendingInstantiations.empty())) {
6555     PendingImplicitInstantiation Inst;
6556 
6557     if (PendingLocalImplicitInstantiations.empty()) {
6558       Inst = PendingInstantiations.front();
6559       PendingInstantiations.pop_front();
6560     } else {
6561       Inst = PendingLocalImplicitInstantiations.front();
6562       PendingLocalImplicitInstantiations.pop_front();
6563     }
6564 
6565     // Instantiate function definitions
6566     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6567       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6568                                 TSK_ExplicitInstantiationDefinition;
6569       if (Function->isMultiVersion()) {
6570         getASTContext().forEachMultiversionedFunctionVersion(
6571             Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6572               InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6573                                             DefinitionRequired, true);
6574               if (CurFD->isDefined())
6575                 CurFD->setInstantiationIsPending(false);
6576             });
6577       } else {
6578         InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6579                                       DefinitionRequired, true);
6580         if (Function->isDefined())
6581           Function->setInstantiationIsPending(false);
6582       }
6583       // Definition of a PCH-ed template declaration may be available only in the TU.
6584       if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6585           TUKind == TU_Prefix && Function->instantiationIsPending())
6586         delayedPCHInstantiations.push_back(Inst);
6587       continue;
6588     }
6589 
6590     // Instantiate variable definitions
6591     VarDecl *Var = cast<VarDecl>(Inst.first);
6592 
6593     assert((Var->isStaticDataMember() ||
6594             isa<VarTemplateSpecializationDecl>(Var)) &&
6595            "Not a static data member, nor a variable template"
6596            " specialization?");
6597 
6598     // Don't try to instantiate declarations if the most recent redeclaration
6599     // is invalid.
6600     if (Var->getMostRecentDecl()->isInvalidDecl())
6601       continue;
6602 
6603     // Check if the most recent declaration has changed the specialization kind
6604     // and removed the need for implicit instantiation.
6605     switch (Var->getMostRecentDecl()
6606                 ->getTemplateSpecializationKindForInstantiation()) {
6607     case TSK_Undeclared:
6608       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6609     case TSK_ExplicitInstantiationDeclaration:
6610     case TSK_ExplicitSpecialization:
6611       continue;  // No longer need to instantiate this type.
6612     case TSK_ExplicitInstantiationDefinition:
6613       // We only need an instantiation if the pending instantiation *is* the
6614       // explicit instantiation.
6615       if (Var != Var->getMostRecentDecl())
6616         continue;
6617       break;
6618     case TSK_ImplicitInstantiation:
6619       break;
6620     }
6621 
6622     PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
6623                                         "instantiating variable definition");
6624     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6625                               TSK_ExplicitInstantiationDefinition;
6626 
6627     // Instantiate static data member definitions or variable template
6628     // specializations.
6629     InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6630                                   DefinitionRequired, true);
6631   }
6632 
6633   if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6634     PendingInstantiations.swap(delayedPCHInstantiations);
6635 }
6636 
6637 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
6638                        const MultiLevelTemplateArgumentList &TemplateArgs) {
6639   for (auto *DD : Pattern->ddiags()) {
6640     switch (DD->getKind()) {
6641     case DependentDiagnostic::Access:
6642       HandleDependentAccessCheck(*DD, TemplateArgs);
6643       break;
6644     }
6645   }
6646 }
6647