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