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