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