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