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