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