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