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