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