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