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