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