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