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