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