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