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