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