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