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