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