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