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