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