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