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