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