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/Sema/Lookup.h"
14 #include "clang/Sema/PrettyDeclStackTrace.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/DependentDiagnostic.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/Lex/Preprocessor.h"
25 
26 using namespace clang;
27 
28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29                                               DeclaratorDecl *NewDecl) {
30   if (!OldDecl->getQualifierLoc())
31     return false;
32 
33   NestedNameSpecifierLoc NewQualifierLoc
34     = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
35                                           TemplateArgs);
36 
37   if (!NewQualifierLoc)
38     return true;
39 
40   NewDecl->setQualifierInfo(NewQualifierLoc);
41   return false;
42 }
43 
44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45                                               TagDecl *NewDecl) {
46   if (!OldDecl->getQualifierLoc())
47     return false;
48 
49   NestedNameSpecifierLoc NewQualifierLoc
50   = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
51                                         TemplateArgs);
52 
53   if (!NewQualifierLoc)
54     return true;
55 
56   NewDecl->setQualifierInfo(NewQualifierLoc);
57   return false;
58 }
59 
60 // Include attribute instantiation code.
61 #include "clang/Sema/AttrTemplateInstantiate.inc"
62 
63 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
64                             const Decl *Tmpl, Decl *New,
65                             LateInstantiatedAttrVec *LateAttrs,
66                             LocalInstantiationScope *OuterMostScope) {
67   for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
68        i != e; ++i) {
69     const Attr *TmplAttr = *i;
70 
71     // FIXME: This should be generalized to more than just the AlignedAttr.
72     if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
73       if (Aligned->isAlignmentDependent()) {
74         if (Aligned->isAlignmentExpr()) {
75           // The alignment expression is a constant expression.
76           EnterExpressionEvaluationContext Unevaluated(*this,
77                                                        Sema::ConstantEvaluated);
78 
79           ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
80                                         TemplateArgs);
81           if (!Result.isInvalid())
82             AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83                            Aligned->getIsMSDeclSpec());
84         } else {
85           TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
86                                              TemplateArgs,
87                                              Aligned->getLocation(),
88                                              DeclarationName());
89           if (Result)
90             AddAlignedAttr(Aligned->getLocation(), New, Result,
91                            Aligned->getIsMSDeclSpec());
92         }
93         continue;
94       }
95     }
96 
97     if (TmplAttr->isLateParsed() && LateAttrs) {
98       // Late parsed attributes must be instantiated and attached after the
99       // enclosing class has been instantiated.  See Sema::InstantiateClass.
100       LocalInstantiationScope *Saved = 0;
101       if (CurrentInstantiationScope)
102         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
103       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
104     } else {
105       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
106                                                          *this, TemplateArgs);
107       if (NewAttr)
108         New->addAttr(NewAttr);
109     }
110   }
111 }
112 
113 Decl *
114 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
115   llvm_unreachable("Translation units cannot be instantiated");
116 }
117 
118 Decl *
119 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
120   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
121                                       D->getIdentifier());
122   Owner->addDecl(Inst);
123   return Inst;
124 }
125 
126 Decl *
127 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
128   llvm_unreachable("Namespaces cannot be instantiated");
129 }
130 
131 Decl *
132 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
133   NamespaceAliasDecl *Inst
134     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
135                                  D->getNamespaceLoc(),
136                                  D->getAliasLoc(),
137                                  D->getIdentifier(),
138                                  D->getQualifierLoc(),
139                                  D->getTargetNameLoc(),
140                                  D->getNamespace());
141   Owner->addDecl(Inst);
142   return Inst;
143 }
144 
145 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
146                                                            bool IsTypeAlias) {
147   bool Invalid = false;
148   TypeSourceInfo *DI = D->getTypeSourceInfo();
149   if (DI->getType()->isInstantiationDependentType() ||
150       DI->getType()->isVariablyModifiedType()) {
151     DI = SemaRef.SubstType(DI, TemplateArgs,
152                            D->getLocation(), D->getDeclName());
153     if (!DI) {
154       Invalid = true;
155       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
156     }
157   } else {
158     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
159   }
160 
161   // Create the new typedef
162   TypedefNameDecl *Typedef;
163   if (IsTypeAlias)
164     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
165                                     D->getLocation(), D->getIdentifier(), DI);
166   else
167     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
168                                   D->getLocation(), D->getIdentifier(), DI);
169   if (Invalid)
170     Typedef->setInvalidDecl();
171 
172   // If the old typedef was the name for linkage purposes of an anonymous
173   // tag decl, re-establish that relationship for the new typedef.
174   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
175     TagDecl *oldTag = oldTagType->getDecl();
176     if (oldTag->getTypedefNameForAnonDecl() == D) {
177       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
178       assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
179       newTag->setTypedefNameForAnonDecl(Typedef);
180     }
181   }
182 
183   if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
184     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
185                                                        TemplateArgs);
186     if (!InstPrev)
187       return 0;
188 
189     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
190 
191     // If the typedef types are not identical, reject them.
192     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
193 
194     Typedef->setPreviousDeclaration(InstPrevTypedef);
195   }
196 
197   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
198 
199   Typedef->setAccess(D->getAccess());
200 
201   return Typedef;
202 }
203 
204 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
205   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
206   Owner->addDecl(Typedef);
207   return Typedef;
208 }
209 
210 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
211   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
212   Owner->addDecl(Typedef);
213   return Typedef;
214 }
215 
216 Decl *
217 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
218   // Create a local instantiation scope for this type alias template, which
219   // will contain the instantiations of the template parameters.
220   LocalInstantiationScope Scope(SemaRef);
221 
222   TemplateParameterList *TempParams = D->getTemplateParameters();
223   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
224   if (!InstParams)
225     return 0;
226 
227   TypeAliasDecl *Pattern = D->getTemplatedDecl();
228 
229   TypeAliasTemplateDecl *PrevAliasTemplate = 0;
230   if (Pattern->getPreviousDecl()) {
231     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
232     if (Found.first != Found.second) {
233       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
234     }
235   }
236 
237   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
238     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
239   if (!AliasInst)
240     return 0;
241 
242   TypeAliasTemplateDecl *Inst
243     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
244                                     D->getDeclName(), InstParams, AliasInst);
245   if (PrevAliasTemplate)
246     Inst->setPreviousDeclaration(PrevAliasTemplate);
247 
248   Inst->setAccess(D->getAccess());
249 
250   if (!PrevAliasTemplate)
251     Inst->setInstantiatedFromMemberTemplate(D);
252 
253   Owner->addDecl(Inst);
254 
255   return Inst;
256 }
257 
258 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
259   // If this is the variable for an anonymous struct or union,
260   // instantiate the anonymous struct/union type first.
261   if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
262     if (RecordTy->getDecl()->isAnonymousStructOrUnion())
263       if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
264         return 0;
265 
266   // Do substitution on the type of the declaration
267   TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
268                                          TemplateArgs,
269                                          D->getTypeSpecStartLoc(),
270                                          D->getDeclName());
271   if (!DI)
272     return 0;
273 
274   if (DI->getType()->isFunctionType()) {
275     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
276       << D->isStaticDataMember() << DI->getType();
277     return 0;
278   }
279 
280   // Build the instantiated declaration
281   VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
282                                  D->getInnerLocStart(),
283                                  D->getLocation(), D->getIdentifier(),
284                                  DI->getType(), DI,
285                                  D->getStorageClass(),
286                                  D->getStorageClassAsWritten());
287   Var->setThreadSpecified(D->isThreadSpecified());
288   Var->setInitStyle(D->getInitStyle());
289   Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
290   Var->setConstexpr(D->isConstexpr());
291 
292   // Substitute the nested name specifier, if any.
293   if (SubstQualifier(D, Var))
294     return 0;
295 
296   // If we are instantiating a static data member defined
297   // out-of-line, the instantiation will have the same lexical
298   // context (which will be a namespace scope) as the template.
299   if (D->isOutOfLine())
300     Var->setLexicalDeclContext(D->getLexicalDeclContext());
301 
302   Var->setAccess(D->getAccess());
303 
304   if (!D->isStaticDataMember()) {
305     Var->setUsed(D->isUsed(false));
306     Var->setReferenced(D->isReferenced());
307   }
308 
309   // FIXME: In theory, we could have a previous declaration for variables that
310   // are not static data members.
311   // FIXME: having to fake up a LookupResult is dumb.
312   LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
313                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
314   if (D->isStaticDataMember())
315     SemaRef.LookupQualifiedName(Previous, Owner, false);
316 
317   // In ARC, infer 'retaining' for variables of retainable type.
318   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
319       SemaRef.inferObjCARCLifetime(Var))
320     Var->setInvalidDecl();
321 
322   SemaRef.CheckVariableDeclaration(Var, Previous);
323 
324   if (D->isOutOfLine()) {
325     D->getLexicalDeclContext()->addDecl(Var);
326     Owner->makeDeclVisibleInContext(Var);
327   } else {
328     Owner->addDecl(Var);
329     if (Owner->isFunctionOrMethod())
330       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
331   }
332   SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
333 
334   // Link instantiations of static data members back to the template from
335   // which they were instantiated.
336   if (Var->isStaticDataMember())
337     SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
338                                                      TSK_ImplicitInstantiation);
339 
340   if (Var->getAnyInitializer()) {
341     // We already have an initializer in the class.
342   } else if (D->getInit()) {
343     if (Var->isStaticDataMember() && !D->isOutOfLine())
344       SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated);
345     else
346       SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
347 
348     // Instantiate the initializer.
349     ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
350                                         D->getInitStyle() == VarDecl::CallInit);
351     if (!Init.isInvalid()) {
352       bool TypeMayContainAuto = true;
353       if (Init.get()) {
354         bool DirectInit = D->isDirectInit();
355         SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
356                                      TypeMayContainAuto);
357       } else
358         SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
359     } else {
360       // FIXME: Not too happy about invalidating the declaration
361       // because of a bogus initializer.
362       Var->setInvalidDecl();
363     }
364 
365     SemaRef.PopExpressionEvaluationContext();
366   } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
367              !Var->isCXXForRangeDecl())
368     SemaRef.ActOnUninitializedDecl(Var, false);
369 
370   // Diagnose unused local variables with dependent types, where the diagnostic
371   // will have been deferred.
372   if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
373       D->getType()->isDependentType())
374     SemaRef.DiagnoseUnusedDecl(Var);
375 
376   return Var;
377 }
378 
379 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
380   AccessSpecDecl* AD
381     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
382                              D->getAccessSpecifierLoc(), D->getColonLoc());
383   Owner->addHiddenDecl(AD);
384   return AD;
385 }
386 
387 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
388   bool Invalid = false;
389   TypeSourceInfo *DI = D->getTypeSourceInfo();
390   if (DI->getType()->isInstantiationDependentType() ||
391       DI->getType()->isVariablyModifiedType())  {
392     DI = SemaRef.SubstType(DI, TemplateArgs,
393                            D->getLocation(), D->getDeclName());
394     if (!DI) {
395       DI = D->getTypeSourceInfo();
396       Invalid = true;
397     } else if (DI->getType()->isFunctionType()) {
398       // C++ [temp.arg.type]p3:
399       //   If a declaration acquires a function type through a type
400       //   dependent on a template-parameter and this causes a
401       //   declaration that does not use the syntactic form of a
402       //   function declarator to have function type, the program is
403       //   ill-formed.
404       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
405         << DI->getType();
406       Invalid = true;
407     }
408   } else {
409     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
410   }
411 
412   Expr *BitWidth = D->getBitWidth();
413   if (Invalid)
414     BitWidth = 0;
415   else if (BitWidth) {
416     // The bit-width expression is a constant expression.
417     EnterExpressionEvaluationContext Unevaluated(SemaRef,
418                                                  Sema::ConstantEvaluated);
419 
420     ExprResult InstantiatedBitWidth
421       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
422     if (InstantiatedBitWidth.isInvalid()) {
423       Invalid = true;
424       BitWidth = 0;
425     } else
426       BitWidth = InstantiatedBitWidth.takeAs<Expr>();
427   }
428 
429   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
430                                             DI->getType(), DI,
431                                             cast<RecordDecl>(Owner),
432                                             D->getLocation(),
433                                             D->isMutable(),
434                                             BitWidth,
435                                             D->getInClassInitStyle(),
436                                             D->getInnerLocStart(),
437                                             D->getAccess(),
438                                             0);
439   if (!Field) {
440     cast<Decl>(Owner)->setInvalidDecl();
441     return 0;
442   }
443 
444   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
445 
446   if (Invalid)
447     Field->setInvalidDecl();
448 
449   if (!Field->getDeclName()) {
450     // Keep track of where this decl came from.
451     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
452   }
453   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
454     if (Parent->isAnonymousStructOrUnion() &&
455         Parent->getRedeclContext()->isFunctionOrMethod())
456       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
457   }
458 
459   Field->setImplicit(D->isImplicit());
460   Field->setAccess(D->getAccess());
461   Owner->addDecl(Field);
462 
463   return Field;
464 }
465 
466 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
467   NamedDecl **NamedChain =
468     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
469 
470   int i = 0;
471   for (IndirectFieldDecl::chain_iterator PI =
472        D->chain_begin(), PE = D->chain_end();
473        PI != PE; ++PI) {
474     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
475                                               TemplateArgs);
476     if (!Next)
477       return 0;
478 
479     NamedChain[i++] = Next;
480   }
481 
482   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
483   IndirectFieldDecl* IndirectField
484     = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
485                                 D->getIdentifier(), T,
486                                 NamedChain, D->getChainingSize());
487 
488 
489   IndirectField->setImplicit(D->isImplicit());
490   IndirectField->setAccess(D->getAccess());
491   Owner->addDecl(IndirectField);
492   return IndirectField;
493 }
494 
495 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
496   // Handle friend type expressions by simply substituting template
497   // parameters into the pattern type and checking the result.
498   if (TypeSourceInfo *Ty = D->getFriendType()) {
499     TypeSourceInfo *InstTy;
500     // If this is an unsupported friend, don't bother substituting template
501     // arguments into it. The actual type referred to won't be used by any
502     // parts of Clang, and may not be valid for instantiating. Just use the
503     // same info for the instantiated friend.
504     if (D->isUnsupportedFriend()) {
505       InstTy = Ty;
506     } else {
507       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
508                                  D->getLocation(), DeclarationName());
509     }
510     if (!InstTy)
511       return 0;
512 
513     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
514                                                  D->getFriendLoc(), InstTy);
515     if (!FD)
516       return 0;
517 
518     FD->setAccess(AS_public);
519     FD->setUnsupportedFriend(D->isUnsupportedFriend());
520     Owner->addDecl(FD);
521     return FD;
522   }
523 
524   NamedDecl *ND = D->getFriendDecl();
525   assert(ND && "friend decl must be a decl or a type!");
526 
527   // All of the Visit implementations for the various potential friend
528   // declarations have to be carefully written to work for friend
529   // objects, with the most important detail being that the target
530   // decl should almost certainly not be placed in Owner.
531   Decl *NewND = Visit(ND);
532   if (!NewND) return 0;
533 
534   FriendDecl *FD =
535     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
536                        cast<NamedDecl>(NewND), D->getFriendLoc());
537   FD->setAccess(AS_public);
538   FD->setUnsupportedFriend(D->isUnsupportedFriend());
539   Owner->addDecl(FD);
540   return FD;
541 }
542 
543 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
544   Expr *AssertExpr = D->getAssertExpr();
545 
546   // The expression in a static assertion is a constant expression.
547   EnterExpressionEvaluationContext Unevaluated(SemaRef,
548                                                Sema::ConstantEvaluated);
549 
550   ExprResult InstantiatedAssertExpr
551     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
552   if (InstantiatedAssertExpr.isInvalid())
553     return 0;
554 
555   ExprResult Message(D->getMessage());
556   D->getMessage();
557   return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
558                                               InstantiatedAssertExpr.get(),
559                                               Message.get(),
560                                               D->getRParenLoc());
561 }
562 
563 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
564   EnumDecl *PrevDecl = 0;
565   if (D->getPreviousDecl()) {
566     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
567                                                    D->getPreviousDecl(),
568                                                    TemplateArgs);
569     if (!Prev) return 0;
570     PrevDecl = cast<EnumDecl>(Prev);
571   }
572 
573   EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
574                                     D->getLocation(), D->getIdentifier(),
575                                     PrevDecl, D->isScoped(),
576                                     D->isScopedUsingClassTag(), D->isFixed());
577   if (D->isFixed()) {
578     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
579       // If we have type source information for the underlying type, it means it
580       // has been explicitly set by the user. Perform substitution on it before
581       // moving on.
582       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
583       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
584                                                 DeclarationName());
585       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
586         Enum->setIntegerType(SemaRef.Context.IntTy);
587       else
588         Enum->setIntegerTypeSourceInfo(NewTI);
589     } else {
590       assert(!D->getIntegerType()->isDependentType()
591              && "Dependent type without type source info");
592       Enum->setIntegerType(D->getIntegerType());
593     }
594   }
595 
596   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
597 
598   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
599   Enum->setAccess(D->getAccess());
600   if (SubstQualifier(D, Enum)) return 0;
601   Owner->addDecl(Enum);
602 
603   EnumDecl *Def = D->getDefinition();
604   if (Def && Def != D) {
605     // If this is an out-of-line definition of an enum member template, check
606     // that the underlying types match in the instantiation of both
607     // declarations.
608     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
609       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
610       QualType DefnUnderlying =
611         SemaRef.SubstType(TI->getType(), TemplateArgs,
612                           UnderlyingLoc, DeclarationName());
613       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
614                                      DefnUnderlying, Enum);
615     }
616   }
617 
618   if (D->getDeclContext()->isFunctionOrMethod())
619     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
620 
621   // C++11 [temp.inst]p1: The implicit instantiation of a class template
622   // specialization causes the implicit instantiation of the declarations, but
623   // not the definitions of scoped member enumerations.
624   // FIXME: There appears to be no wording for what happens for an enum defined
625   // within a block scope, but we treat that much like a member template. Only
626   // instantiate the definition when visiting the definition in that case, since
627   // we will visit all redeclarations.
628   if (!Enum->isScoped() && Def &&
629       (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
630     InstantiateEnumDefinition(Enum, Def);
631 
632   return Enum;
633 }
634 
635 void TemplateDeclInstantiator::InstantiateEnumDefinition(
636     EnumDecl *Enum, EnumDecl *Pattern) {
637   Enum->startDefinition();
638 
639   // Update the location to refer to the definition.
640   Enum->setLocation(Pattern->getLocation());
641 
642   SmallVector<Decl*, 4> Enumerators;
643 
644   EnumConstantDecl *LastEnumConst = 0;
645   for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
646          ECEnd = Pattern->enumerator_end();
647        EC != ECEnd; ++EC) {
648     // The specified value for the enumerator.
649     ExprResult Value = SemaRef.Owned((Expr *)0);
650     if (Expr *UninstValue = EC->getInitExpr()) {
651       // The enumerator's value expression is a constant expression.
652       EnterExpressionEvaluationContext Unevaluated(SemaRef,
653                                                    Sema::ConstantEvaluated);
654 
655       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
656     }
657 
658     // Drop the initial value and continue.
659     bool isInvalid = false;
660     if (Value.isInvalid()) {
661       Value = SemaRef.Owned((Expr *)0);
662       isInvalid = true;
663     }
664 
665     EnumConstantDecl *EnumConst
666       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
667                                   EC->getLocation(), EC->getIdentifier(),
668                                   Value.get());
669 
670     if (isInvalid) {
671       if (EnumConst)
672         EnumConst->setInvalidDecl();
673       Enum->setInvalidDecl();
674     }
675 
676     if (EnumConst) {
677       SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
678 
679       EnumConst->setAccess(Enum->getAccess());
680       Enum->addDecl(EnumConst);
681       Enumerators.push_back(EnumConst);
682       LastEnumConst = EnumConst;
683 
684       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
685           !Enum->isScoped()) {
686         // If the enumeration is within a function or method, record the enum
687         // constant as a local.
688         SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
689       }
690     }
691   }
692 
693   // FIXME: Fixup LBraceLoc
694   SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
695                         Enum->getRBraceLoc(), Enum,
696                         Enumerators.data(), Enumerators.size(),
697                         0, 0);
698 }
699 
700 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
701   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
702 }
703 
704 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
705   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
706 
707   // Create a local instantiation scope for this class template, which
708   // will contain the instantiations of the template parameters.
709   LocalInstantiationScope Scope(SemaRef);
710   TemplateParameterList *TempParams = D->getTemplateParameters();
711   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
712   if (!InstParams)
713     return NULL;
714 
715   CXXRecordDecl *Pattern = D->getTemplatedDecl();
716 
717   // Instantiate the qualifier.  We have to do this first in case
718   // we're a friend declaration, because if we are then we need to put
719   // the new declaration in the appropriate context.
720   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
721   if (QualifierLoc) {
722     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
723                                                        TemplateArgs);
724     if (!QualifierLoc)
725       return 0;
726   }
727 
728   CXXRecordDecl *PrevDecl = 0;
729   ClassTemplateDecl *PrevClassTemplate = 0;
730 
731   if (!isFriend && Pattern->getPreviousDecl()) {
732     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
733     if (Found.first != Found.second) {
734       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
735       if (PrevClassTemplate)
736         PrevDecl = PrevClassTemplate->getTemplatedDecl();
737     }
738   }
739 
740   // If this isn't a friend, then it's a member template, in which
741   // case we just want to build the instantiation in the
742   // specialization.  If it is a friend, we want to build it in
743   // the appropriate context.
744   DeclContext *DC = Owner;
745   if (isFriend) {
746     if (QualifierLoc) {
747       CXXScopeSpec SS;
748       SS.Adopt(QualifierLoc);
749       DC = SemaRef.computeDeclContext(SS);
750       if (!DC) return 0;
751     } else {
752       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
753                                            Pattern->getDeclContext(),
754                                            TemplateArgs);
755     }
756 
757     // Look for a previous declaration of the template in the owning
758     // context.
759     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
760                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
761     SemaRef.LookupQualifiedName(R, DC);
762 
763     if (R.isSingleResult()) {
764       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
765       if (PrevClassTemplate)
766         PrevDecl = PrevClassTemplate->getTemplatedDecl();
767     }
768 
769     if (!PrevClassTemplate && QualifierLoc) {
770       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
771         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
772         << QualifierLoc.getSourceRange();
773       return 0;
774     }
775 
776     bool AdoptedPreviousTemplateParams = false;
777     if (PrevClassTemplate) {
778       bool Complain = true;
779 
780       // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
781       // template for struct std::tr1::__detail::_Map_base, where the
782       // template parameters of the friend declaration don't match the
783       // template parameters of the original declaration. In this one
784       // case, we don't complain about the ill-formed friend
785       // declaration.
786       if (isFriend && Pattern->getIdentifier() &&
787           Pattern->getIdentifier()->isStr("_Map_base") &&
788           DC->isNamespace() &&
789           cast<NamespaceDecl>(DC)->getIdentifier() &&
790           cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
791         DeclContext *DCParent = DC->getParent();
792         if (DCParent->isNamespace() &&
793             cast<NamespaceDecl>(DCParent)->getIdentifier() &&
794             cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
795           DeclContext *DCParent2 = DCParent->getParent();
796           if (DCParent2->isNamespace() &&
797               cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
798               cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
799               DCParent2->getParent()->isTranslationUnit())
800             Complain = false;
801         }
802       }
803 
804       TemplateParameterList *PrevParams
805         = PrevClassTemplate->getTemplateParameters();
806 
807       // Make sure the parameter lists match.
808       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
809                                                   Complain,
810                                                   Sema::TPL_TemplateMatch)) {
811         if (Complain)
812           return 0;
813 
814         AdoptedPreviousTemplateParams = true;
815         InstParams = PrevParams;
816       }
817 
818       // Do some additional validation, then merge default arguments
819       // from the existing declarations.
820       if (!AdoptedPreviousTemplateParams &&
821           SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
822                                              Sema::TPC_ClassTemplate))
823         return 0;
824     }
825   }
826 
827   CXXRecordDecl *RecordInst
828     = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
829                             Pattern->getLocStart(), Pattern->getLocation(),
830                             Pattern->getIdentifier(), PrevDecl,
831                             /*DelayTypeCreation=*/true);
832 
833   if (QualifierLoc)
834     RecordInst->setQualifierInfo(QualifierLoc);
835 
836   ClassTemplateDecl *Inst
837     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
838                                 D->getIdentifier(), InstParams, RecordInst,
839                                 PrevClassTemplate);
840   RecordInst->setDescribedClassTemplate(Inst);
841 
842   if (isFriend) {
843     if (PrevClassTemplate)
844       Inst->setAccess(PrevClassTemplate->getAccess());
845     else
846       Inst->setAccess(D->getAccess());
847 
848     Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
849     // TODO: do we want to track the instantiation progeny of this
850     // friend target decl?
851   } else {
852     Inst->setAccess(D->getAccess());
853     if (!PrevClassTemplate)
854       Inst->setInstantiatedFromMemberTemplate(D);
855   }
856 
857   // Trigger creation of the type for the instantiation.
858   SemaRef.Context.getInjectedClassNameType(RecordInst,
859                                     Inst->getInjectedClassNameSpecialization());
860 
861   // Finish handling of friends.
862   if (isFriend) {
863     DC->makeDeclVisibleInContext(Inst);
864     Inst->setLexicalDeclContext(Owner);
865     RecordInst->setLexicalDeclContext(Owner);
866     return Inst;
867   }
868 
869   if (D->isOutOfLine()) {
870     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
871     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
872   }
873 
874   Owner->addDecl(Inst);
875 
876   if (!PrevClassTemplate) {
877     // Queue up any out-of-line partial specializations of this member
878     // class template; the client will force their instantiation once
879     // the enclosing class has been instantiated.
880     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
881     D->getPartialSpecializations(PartialSpecs);
882     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
883       if (PartialSpecs[I]->isOutOfLine())
884         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
885   }
886 
887   return Inst;
888 }
889 
890 Decl *
891 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
892                                    ClassTemplatePartialSpecializationDecl *D) {
893   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
894 
895   // Lookup the already-instantiated declaration in the instantiation
896   // of the class template and return that.
897   DeclContext::lookup_result Found
898     = Owner->lookup(ClassTemplate->getDeclName());
899   if (Found.first == Found.second)
900     return 0;
901 
902   ClassTemplateDecl *InstClassTemplate
903     = dyn_cast<ClassTemplateDecl>(*Found.first);
904   if (!InstClassTemplate)
905     return 0;
906 
907   if (ClassTemplatePartialSpecializationDecl *Result
908         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
909     return Result;
910 
911   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
912 }
913 
914 Decl *
915 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
916   // Create a local instantiation scope for this function template, which
917   // will contain the instantiations of the template parameters and then get
918   // merged with the local instantiation scope for the function template
919   // itself.
920   LocalInstantiationScope Scope(SemaRef);
921 
922   TemplateParameterList *TempParams = D->getTemplateParameters();
923   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
924   if (!InstParams)
925     return NULL;
926 
927   FunctionDecl *Instantiated = 0;
928   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
929     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
930                                                                  InstParams));
931   else
932     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
933                                                           D->getTemplatedDecl(),
934                                                                 InstParams));
935 
936   if (!Instantiated)
937     return 0;
938 
939   Instantiated->setAccess(D->getAccess());
940 
941   // Link the instantiated function template declaration to the function
942   // template from which it was instantiated.
943   FunctionTemplateDecl *InstTemplate
944     = Instantiated->getDescribedFunctionTemplate();
945   InstTemplate->setAccess(D->getAccess());
946   assert(InstTemplate &&
947          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
948 
949   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
950 
951   // Link the instantiation back to the pattern *unless* this is a
952   // non-definition friend declaration.
953   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
954       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
955     InstTemplate->setInstantiatedFromMemberTemplate(D);
956 
957   // Make declarations visible in the appropriate context.
958   if (!isFriend)
959     Owner->addDecl(InstTemplate);
960 
961   return InstTemplate;
962 }
963 
964 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
965   CXXRecordDecl *PrevDecl = 0;
966   if (D->isInjectedClassName())
967     PrevDecl = cast<CXXRecordDecl>(Owner);
968   else if (D->getPreviousDecl()) {
969     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
970                                                    D->getPreviousDecl(),
971                                                    TemplateArgs);
972     if (!Prev) return 0;
973     PrevDecl = cast<CXXRecordDecl>(Prev);
974   }
975 
976   CXXRecordDecl *Record
977     = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
978                             D->getLocStart(), D->getLocation(),
979                             D->getIdentifier(), PrevDecl);
980 
981   // Substitute the nested name specifier, if any.
982   if (SubstQualifier(D, Record))
983     return 0;
984 
985   Record->setImplicit(D->isImplicit());
986   // FIXME: Check against AS_none is an ugly hack to work around the issue that
987   // the tag decls introduced by friend class declarations don't have an access
988   // specifier. Remove once this area of the code gets sorted out.
989   if (D->getAccess() != AS_none)
990     Record->setAccess(D->getAccess());
991   if (!D->isInjectedClassName())
992     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
993 
994   // If the original function was part of a friend declaration,
995   // inherit its namespace state.
996   if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
997     Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
998 
999   // Make sure that anonymous structs and unions are recorded.
1000   if (D->isAnonymousStructOrUnion()) {
1001     Record->setAnonymousStructOrUnion(true);
1002     if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
1003       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1004   }
1005 
1006   Owner->addDecl(Record);
1007   return Record;
1008 }
1009 
1010 /// Normal class members are of more specific types and therefore
1011 /// don't make it here.  This function serves two purposes:
1012 ///   1) instantiating function templates
1013 ///   2) substituting friend declarations
1014 /// FIXME: preserve function definitions in case #2
1015 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1016                                        TemplateParameterList *TemplateParams) {
1017   // Check whether there is already a function template specialization for
1018   // this declaration.
1019   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1020   if (FunctionTemplate && !TemplateParams) {
1021     std::pair<const TemplateArgument *, unsigned> Innermost
1022       = TemplateArgs.getInnermost();
1023 
1024     void *InsertPos = 0;
1025     FunctionDecl *SpecFunc
1026       = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1027                                              InsertPos);
1028 
1029     // If we already have a function template specialization, return it.
1030     if (SpecFunc)
1031       return SpecFunc;
1032   }
1033 
1034   bool isFriend;
1035   if (FunctionTemplate)
1036     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1037   else
1038     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1039 
1040   bool MergeWithParentScope = (TemplateParams != 0) ||
1041     Owner->isFunctionOrMethod() ||
1042     !(isa<Decl>(Owner) &&
1043       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1044   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1045 
1046   SmallVector<ParmVarDecl *, 4> Params;
1047   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1048   if (!TInfo)
1049     return 0;
1050   QualType T = TInfo->getType();
1051 
1052   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1053   if (QualifierLoc) {
1054     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1055                                                        TemplateArgs);
1056     if (!QualifierLoc)
1057       return 0;
1058   }
1059 
1060   // If we're instantiating a local function declaration, put the result
1061   // in the owner;  otherwise we need to find the instantiated context.
1062   DeclContext *DC;
1063   if (D->getDeclContext()->isFunctionOrMethod())
1064     DC = Owner;
1065   else if (isFriend && QualifierLoc) {
1066     CXXScopeSpec SS;
1067     SS.Adopt(QualifierLoc);
1068     DC = SemaRef.computeDeclContext(SS);
1069     if (!DC) return 0;
1070   } else {
1071     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1072                                          TemplateArgs);
1073   }
1074 
1075   FunctionDecl *Function =
1076       FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1077                            D->getLocation(), D->getDeclName(), T, TInfo,
1078                            D->getStorageClass(), D->getStorageClassAsWritten(),
1079                            D->isInlineSpecified(), D->hasWrittenPrototype(),
1080                            D->isConstexpr());
1081 
1082   if (QualifierLoc)
1083     Function->setQualifierInfo(QualifierLoc);
1084 
1085   DeclContext *LexicalDC = Owner;
1086   if (!isFriend && D->isOutOfLine()) {
1087     assert(D->getDeclContext()->isFileContext());
1088     LexicalDC = D->getDeclContext();
1089   }
1090 
1091   Function->setLexicalDeclContext(LexicalDC);
1092 
1093   // Attach the parameters
1094   if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
1095     // Adopt the already-instantiated parameters into our own context.
1096     for (unsigned P = 0; P < Params.size(); ++P)
1097       if (Params[P])
1098         Params[P]->setOwningFunction(Function);
1099   } else {
1100     // Since we were instantiated via a typedef of a function type, create
1101     // new parameters.
1102     const FunctionProtoType *Proto
1103       = Function->getType()->getAs<FunctionProtoType>();
1104     assert(Proto && "No function prototype in template instantiation?");
1105     for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1106          AE = Proto->arg_type_end(); AI != AE; ++AI) {
1107       ParmVarDecl *Param
1108         = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1109                                              *AI);
1110       Param->setScopeInfo(0, Params.size());
1111       Params.push_back(Param);
1112     }
1113   }
1114   Function->setParams(Params);
1115 
1116   SourceLocation InstantiateAtPOI;
1117   if (TemplateParams) {
1118     // Our resulting instantiation is actually a function template, since we
1119     // are substituting only the outer template parameters. For example, given
1120     //
1121     //   template<typename T>
1122     //   struct X {
1123     //     template<typename U> friend void f(T, U);
1124     //   };
1125     //
1126     //   X<int> x;
1127     //
1128     // We are instantiating the friend function template "f" within X<int>,
1129     // which means substituting int for T, but leaving "f" as a friend function
1130     // template.
1131     // Build the function template itself.
1132     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1133                                                     Function->getLocation(),
1134                                                     Function->getDeclName(),
1135                                                     TemplateParams, Function);
1136     Function->setDescribedFunctionTemplate(FunctionTemplate);
1137 
1138     FunctionTemplate->setLexicalDeclContext(LexicalDC);
1139 
1140     if (isFriend && D->isThisDeclarationADefinition()) {
1141       // TODO: should we remember this connection regardless of whether
1142       // the friend declaration provided a body?
1143       FunctionTemplate->setInstantiatedFromMemberTemplate(
1144                                            D->getDescribedFunctionTemplate());
1145     }
1146   } else if (FunctionTemplate) {
1147     // Record this function template specialization.
1148     std::pair<const TemplateArgument *, unsigned> Innermost
1149       = TemplateArgs.getInnermost();
1150     Function->setFunctionTemplateSpecialization(FunctionTemplate,
1151                             TemplateArgumentList::CreateCopy(SemaRef.Context,
1152                                                              Innermost.first,
1153                                                              Innermost.second),
1154                                                 /*InsertPos=*/0);
1155   } else if (isFriend) {
1156     // Note, we need this connection even if the friend doesn't have a body.
1157     // Its body may exist but not have been attached yet due to deferred
1158     // parsing.
1159     // FIXME: It might be cleaner to set this when attaching the body to the
1160     // friend function declaration, however that would require finding all the
1161     // instantiations and modifying them.
1162     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1163   }
1164 
1165   if (InitFunctionInstantiation(Function, D))
1166     Function->setInvalidDecl();
1167 
1168   bool isExplicitSpecialization = false;
1169 
1170   LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1171                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1172 
1173   if (DependentFunctionTemplateSpecializationInfo *Info
1174         = D->getDependentSpecializationInfo()) {
1175     assert(isFriend && "non-friend has dependent specialization info?");
1176 
1177     // This needs to be set now for future sanity.
1178     Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1179 
1180     // Instantiate the explicit template arguments.
1181     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1182                                           Info->getRAngleLoc());
1183     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1184                       ExplicitArgs, TemplateArgs))
1185       return 0;
1186 
1187     // Map the candidate templates to their instantiations.
1188     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1189       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1190                                                 Info->getTemplate(I),
1191                                                 TemplateArgs);
1192       if (!Temp) return 0;
1193 
1194       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1195     }
1196 
1197     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1198                                                     &ExplicitArgs,
1199                                                     Previous))
1200       Function->setInvalidDecl();
1201 
1202     isExplicitSpecialization = true;
1203 
1204   } else if (TemplateParams || !FunctionTemplate) {
1205     // Look only into the namespace where the friend would be declared to
1206     // find a previous declaration. This is the innermost enclosing namespace,
1207     // as described in ActOnFriendFunctionDecl.
1208     SemaRef.LookupQualifiedName(Previous, DC);
1209 
1210     // In C++, the previous declaration we find might be a tag type
1211     // (class or enum). In this case, the new declaration will hide the
1212     // tag type. Note that this does does not apply if we're declaring a
1213     // typedef (C++ [dcl.typedef]p4).
1214     if (Previous.isSingleTagDecl())
1215       Previous.clear();
1216   }
1217 
1218   SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1219                                    isExplicitSpecialization);
1220 
1221   NamedDecl *PrincipalDecl = (TemplateParams
1222                               ? cast<NamedDecl>(FunctionTemplate)
1223                               : Function);
1224 
1225   // If the original function was part of a friend declaration,
1226   // inherit its namespace state and add it to the owner.
1227   if (isFriend) {
1228     NamedDecl *PrevDecl;
1229     if (TemplateParams)
1230       PrevDecl = FunctionTemplate->getPreviousDecl();
1231     else
1232       PrevDecl = Function->getPreviousDecl();
1233 
1234     PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1235     DC->makeDeclVisibleInContext(PrincipalDecl);
1236 
1237     bool queuedInstantiation = false;
1238 
1239     // C++98 [temp.friend]p5: When a function is defined in a friend function
1240     //   declaration in a class template, the function is defined at each
1241     //   instantiation of the class template. The function is defined even if it
1242     //   is never used.
1243     // C++11 [temp.friend]p4: When a function is defined in a friend function
1244     //   declaration in a class template, the function is instantiated when the
1245     //   function is odr-used.
1246     //
1247     // If -Wc++98-compat is enabled, we go through the motions of checking for a
1248     // redefinition, but don't instantiate the function.
1249     if ((!SemaRef.getLangOpts().CPlusPlus0x ||
1250          SemaRef.Diags.getDiagnosticLevel(
1251              diag::warn_cxx98_compat_friend_redefinition,
1252              Function->getLocation())
1253            != DiagnosticsEngine::Ignored) &&
1254         D->isThisDeclarationADefinition()) {
1255       // Check for a function body.
1256       const FunctionDecl *Definition = 0;
1257       if (Function->isDefined(Definition) &&
1258           Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1259         SemaRef.Diag(Function->getLocation(),
1260                      SemaRef.getLangOpts().CPlusPlus0x ?
1261                        diag::warn_cxx98_compat_friend_redefinition :
1262                        diag::err_redefinition) << Function->getDeclName();
1263         SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1264         if (!SemaRef.getLangOpts().CPlusPlus0x)
1265           Function->setInvalidDecl();
1266       }
1267       // Check for redefinitions due to other instantiations of this or
1268       // a similar friend function.
1269       else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1270                                            REnd = Function->redecls_end();
1271                 R != REnd; ++R) {
1272         if (*R == Function)
1273           continue;
1274         switch (R->getFriendObjectKind()) {
1275         case Decl::FOK_None:
1276           if (!SemaRef.getLangOpts().CPlusPlus0x &&
1277               !queuedInstantiation && R->isUsed(false)) {
1278             if (MemberSpecializationInfo *MSInfo
1279                 = Function->getMemberSpecializationInfo()) {
1280               if (MSInfo->getPointOfInstantiation().isInvalid()) {
1281                 SourceLocation Loc = R->getLocation(); // FIXME
1282                 MSInfo->setPointOfInstantiation(Loc);
1283                 SemaRef.PendingLocalImplicitInstantiations.push_back(
1284                                                  std::make_pair(Function, Loc));
1285                 queuedInstantiation = true;
1286               }
1287             }
1288           }
1289           break;
1290         default:
1291           if (const FunctionDecl *RPattern
1292               = R->getTemplateInstantiationPattern())
1293             if (RPattern->isDefined(RPattern)) {
1294               SemaRef.Diag(Function->getLocation(),
1295                            SemaRef.getLangOpts().CPlusPlus0x ?
1296                              diag::warn_cxx98_compat_friend_redefinition :
1297                              diag::err_redefinition)
1298                 << Function->getDeclName();
1299               SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1300               if (!SemaRef.getLangOpts().CPlusPlus0x)
1301                 Function->setInvalidDecl();
1302               break;
1303             }
1304         }
1305       }
1306     }
1307   }
1308 
1309   if (Function->isOverloadedOperator() && !DC->isRecord() &&
1310       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1311     PrincipalDecl->setNonMemberOperator();
1312 
1313   assert(!D->isDefaulted() && "only methods should be defaulted");
1314   return Function;
1315 }
1316 
1317 Decl *
1318 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1319                                       TemplateParameterList *TemplateParams,
1320                                       bool IsClassScopeSpecialization) {
1321   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1322   if (FunctionTemplate && !TemplateParams) {
1323     // We are creating a function template specialization from a function
1324     // template. Check whether there is already a function template
1325     // specialization for this particular set of template arguments.
1326     std::pair<const TemplateArgument *, unsigned> Innermost
1327       = TemplateArgs.getInnermost();
1328 
1329     void *InsertPos = 0;
1330     FunctionDecl *SpecFunc
1331       = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1332                                              InsertPos);
1333 
1334     // If we already have a function template specialization, return it.
1335     if (SpecFunc)
1336       return SpecFunc;
1337   }
1338 
1339   bool isFriend;
1340   if (FunctionTemplate)
1341     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1342   else
1343     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1344 
1345   bool MergeWithParentScope = (TemplateParams != 0) ||
1346     !(isa<Decl>(Owner) &&
1347       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1348   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1349 
1350   // Instantiate enclosing template arguments for friends.
1351   SmallVector<TemplateParameterList *, 4> TempParamLists;
1352   unsigned NumTempParamLists = 0;
1353   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1354     TempParamLists.set_size(NumTempParamLists);
1355     for (unsigned I = 0; I != NumTempParamLists; ++I) {
1356       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1357       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1358       if (!InstParams)
1359         return NULL;
1360       TempParamLists[I] = InstParams;
1361     }
1362   }
1363 
1364   SmallVector<ParmVarDecl *, 4> Params;
1365   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1366   if (!TInfo)
1367     return 0;
1368   QualType T = TInfo->getType();
1369 
1370   // \brief If the type of this function, after ignoring parentheses,
1371   // is not *directly* a function type, then we're instantiating a function
1372   // that was declared via a typedef, e.g.,
1373   //
1374   //   typedef int functype(int, int);
1375   //   functype func;
1376   //
1377   // In this case, we'll just go instantiate the ParmVarDecls that we
1378   // synthesized in the method declaration.
1379   if (!isa<FunctionProtoType>(T.IgnoreParens())) {
1380     assert(!Params.size() && "Instantiating type could not yield parameters");
1381     SmallVector<QualType, 4> ParamTypes;
1382     if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1383                                D->getNumParams(), TemplateArgs, ParamTypes,
1384                                &Params))
1385       return 0;
1386   }
1387 
1388   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1389   if (QualifierLoc) {
1390     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1391                                                  TemplateArgs);
1392     if (!QualifierLoc)
1393       return 0;
1394   }
1395 
1396   DeclContext *DC = Owner;
1397   if (isFriend) {
1398     if (QualifierLoc) {
1399       CXXScopeSpec SS;
1400       SS.Adopt(QualifierLoc);
1401       DC = SemaRef.computeDeclContext(SS);
1402 
1403       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1404         return 0;
1405     } else {
1406       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1407                                            D->getDeclContext(),
1408                                            TemplateArgs);
1409     }
1410     if (!DC) return 0;
1411   }
1412 
1413   // Build the instantiated method declaration.
1414   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1415   CXXMethodDecl *Method = 0;
1416 
1417   SourceLocation StartLoc = D->getInnerLocStart();
1418   DeclarationNameInfo NameInfo
1419     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1420   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1421     Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1422                                         StartLoc, NameInfo, T, TInfo,
1423                                         Constructor->isExplicit(),
1424                                         Constructor->isInlineSpecified(),
1425                                         false, Constructor->isConstexpr());
1426   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1427     Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1428                                        StartLoc, NameInfo, T, TInfo,
1429                                        Destructor->isInlineSpecified(),
1430                                        false);
1431   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1432     Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1433                                        StartLoc, NameInfo, T, TInfo,
1434                                        Conversion->isInlineSpecified(),
1435                                        Conversion->isExplicit(),
1436                                        Conversion->isConstexpr(),
1437                                        Conversion->getLocEnd());
1438   } else {
1439     Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1440                                    StartLoc, NameInfo, T, TInfo,
1441                                    D->isStatic(),
1442                                    D->getStorageClassAsWritten(),
1443                                    D->isInlineSpecified(),
1444                                    D->isConstexpr(), D->getLocEnd());
1445   }
1446 
1447   if (QualifierLoc)
1448     Method->setQualifierInfo(QualifierLoc);
1449 
1450   if (TemplateParams) {
1451     // Our resulting instantiation is actually a function template, since we
1452     // are substituting only the outer template parameters. For example, given
1453     //
1454     //   template<typename T>
1455     //   struct X {
1456     //     template<typename U> void f(T, U);
1457     //   };
1458     //
1459     //   X<int> x;
1460     //
1461     // We are instantiating the member template "f" within X<int>, which means
1462     // substituting int for T, but leaving "f" as a member function template.
1463     // Build the function template itself.
1464     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1465                                                     Method->getLocation(),
1466                                                     Method->getDeclName(),
1467                                                     TemplateParams, Method);
1468     if (isFriend) {
1469       FunctionTemplate->setLexicalDeclContext(Owner);
1470       FunctionTemplate->setObjectOfFriendDecl(true);
1471     } else if (D->isOutOfLine())
1472       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1473     Method->setDescribedFunctionTemplate(FunctionTemplate);
1474   } else if (FunctionTemplate) {
1475     // Record this function template specialization.
1476     std::pair<const TemplateArgument *, unsigned> Innermost
1477       = TemplateArgs.getInnermost();
1478     Method->setFunctionTemplateSpecialization(FunctionTemplate,
1479                          TemplateArgumentList::CreateCopy(SemaRef.Context,
1480                                                           Innermost.first,
1481                                                           Innermost.second),
1482                                               /*InsertPos=*/0);
1483   } else if (!isFriend) {
1484     // Record that this is an instantiation of a member function.
1485     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1486   }
1487 
1488   // If we are instantiating a member function defined
1489   // out-of-line, the instantiation will have the same lexical
1490   // context (which will be a namespace scope) as the template.
1491   if (isFriend) {
1492     if (NumTempParamLists)
1493       Method->setTemplateParameterListsInfo(SemaRef.Context,
1494                                             NumTempParamLists,
1495                                             TempParamLists.data());
1496 
1497     Method->setLexicalDeclContext(Owner);
1498     Method->setObjectOfFriendDecl(true);
1499   } else if (D->isOutOfLine())
1500     Method->setLexicalDeclContext(D->getLexicalDeclContext());
1501 
1502   // Attach the parameters
1503   for (unsigned P = 0; P < Params.size(); ++P)
1504     Params[P]->setOwningFunction(Method);
1505   Method->setParams(Params);
1506 
1507   if (InitMethodInstantiation(Method, D))
1508     Method->setInvalidDecl();
1509 
1510   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1511                         Sema::ForRedeclaration);
1512 
1513   if (!FunctionTemplate || TemplateParams || isFriend) {
1514     SemaRef.LookupQualifiedName(Previous, Record);
1515 
1516     // In C++, the previous declaration we find might be a tag type
1517     // (class or enum). In this case, the new declaration will hide the
1518     // tag type. Note that this does does not apply if we're declaring a
1519     // typedef (C++ [dcl.typedef]p4).
1520     if (Previous.isSingleTagDecl())
1521       Previous.clear();
1522   }
1523 
1524   if (!IsClassScopeSpecialization)
1525     SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1526 
1527   if (D->isPure())
1528     SemaRef.CheckPureMethod(Method, SourceRange());
1529 
1530   Method->setAccess(D->getAccess());
1531 
1532   SemaRef.CheckOverrideControl(Method);
1533 
1534   // If a function is defined as defaulted or deleted, mark it as such now.
1535   if (D->isDefaulted())
1536     Method->setDefaulted();
1537   if (D->isDeletedAsWritten())
1538     Method->setDeletedAsWritten();
1539 
1540   if (FunctionTemplate) {
1541     // If there's a function template, let our caller handle it.
1542   } else if (Method->isInvalidDecl() && !Previous.empty()) {
1543     // Don't hide a (potentially) valid declaration with an invalid one.
1544   } else {
1545     NamedDecl *DeclToAdd = (TemplateParams
1546                             ? cast<NamedDecl>(FunctionTemplate)
1547                             : Method);
1548     if (isFriend)
1549       Record->makeDeclVisibleInContext(DeclToAdd);
1550     else if (!IsClassScopeSpecialization)
1551       Owner->addDecl(DeclToAdd);
1552   }
1553 
1554   if (D->isExplicitlyDefaulted()) {
1555     SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1556   } else {
1557     assert(!D->isDefaulted() &&
1558            "should not implicitly default uninstantiated function");
1559   }
1560 
1561   return Method;
1562 }
1563 
1564 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1565   return VisitCXXMethodDecl(D);
1566 }
1567 
1568 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1569   return VisitCXXMethodDecl(D);
1570 }
1571 
1572 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1573   return VisitCXXMethodDecl(D);
1574 }
1575 
1576 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1577   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1578                                   llvm::Optional<unsigned>(),
1579                                   /*ExpectParameterPack=*/false);
1580 }
1581 
1582 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1583                                                     TemplateTypeParmDecl *D) {
1584   // TODO: don't always clone when decls are refcounted.
1585   assert(D->getTypeForDecl()->isTemplateTypeParmType());
1586 
1587   TemplateTypeParmDecl *Inst =
1588     TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1589                                  D->getLocStart(), D->getLocation(),
1590                                  D->getDepth() - TemplateArgs.getNumLevels(),
1591                                  D->getIndex(), D->getIdentifier(),
1592                                  D->wasDeclaredWithTypename(),
1593                                  D->isParameterPack());
1594   Inst->setAccess(AS_public);
1595 
1596   if (D->hasDefaultArgument())
1597     Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1598 
1599   // Introduce this template parameter's instantiation into the instantiation
1600   // scope.
1601   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1602 
1603   return Inst;
1604 }
1605 
1606 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1607                                                  NonTypeTemplateParmDecl *D) {
1608   // Substitute into the type of the non-type template parameter.
1609   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1610   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1611   SmallVector<QualType, 4> ExpandedParameterPackTypes;
1612   bool IsExpandedParameterPack = false;
1613   TypeSourceInfo *DI;
1614   QualType T;
1615   bool Invalid = false;
1616 
1617   if (D->isExpandedParameterPack()) {
1618     // The non-type template parameter pack is an already-expanded pack
1619     // expansion of types. Substitute into each of the expanded types.
1620     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1621     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1622     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1623       TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1624                                                TemplateArgs,
1625                                                D->getLocation(),
1626                                                D->getDeclName());
1627       if (!NewDI)
1628         return 0;
1629 
1630       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1631       QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1632                                                               D->getLocation());
1633       if (NewT.isNull())
1634         return 0;
1635       ExpandedParameterPackTypes.push_back(NewT);
1636     }
1637 
1638     IsExpandedParameterPack = true;
1639     DI = D->getTypeSourceInfo();
1640     T = DI->getType();
1641   } else if (isa<PackExpansionTypeLoc>(TL)) {
1642     // The non-type template parameter pack's type is a pack expansion of types.
1643     // Determine whether we need to expand this parameter pack into separate
1644     // types.
1645     PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1646     TypeLoc Pattern = Expansion.getPatternLoc();
1647     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1648     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1649 
1650     // Determine whether the set of unexpanded parameter packs can and should
1651     // be expanded.
1652     bool Expand = true;
1653     bool RetainExpansion = false;
1654     llvm::Optional<unsigned> OrigNumExpansions
1655       = Expansion.getTypePtr()->getNumExpansions();
1656     llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1657     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1658                                                 Pattern.getSourceRange(),
1659                                                 Unexpanded,
1660                                                 TemplateArgs,
1661                                                 Expand, RetainExpansion,
1662                                                 NumExpansions))
1663       return 0;
1664 
1665     if (Expand) {
1666       for (unsigned I = 0; I != *NumExpansions; ++I) {
1667         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1668         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1669                                                   D->getLocation(),
1670                                                   D->getDeclName());
1671         if (!NewDI)
1672           return 0;
1673 
1674         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1675         QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1676                                                               NewDI->getType(),
1677                                                               D->getLocation());
1678         if (NewT.isNull())
1679           return 0;
1680         ExpandedParameterPackTypes.push_back(NewT);
1681       }
1682 
1683       // Note that we have an expanded parameter pack. The "type" of this
1684       // expanded parameter pack is the original expansion type, but callers
1685       // will end up using the expanded parameter pack types for type-checking.
1686       IsExpandedParameterPack = true;
1687       DI = D->getTypeSourceInfo();
1688       T = DI->getType();
1689     } else {
1690       // We cannot fully expand the pack expansion now, so substitute into the
1691       // pattern and create a new pack expansion type.
1692       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1693       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1694                                                      D->getLocation(),
1695                                                      D->getDeclName());
1696       if (!NewPattern)
1697         return 0;
1698 
1699       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1700                                       NumExpansions);
1701       if (!DI)
1702         return 0;
1703 
1704       T = DI->getType();
1705     }
1706   } else {
1707     // Simple case: substitution into a parameter that is not a parameter pack.
1708     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1709                            D->getLocation(), D->getDeclName());
1710     if (!DI)
1711       return 0;
1712 
1713     // Check that this type is acceptable for a non-type template parameter.
1714     T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1715                                                   D->getLocation());
1716     if (T.isNull()) {
1717       T = SemaRef.Context.IntTy;
1718       Invalid = true;
1719     }
1720   }
1721 
1722   NonTypeTemplateParmDecl *Param;
1723   if (IsExpandedParameterPack)
1724     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1725                                             D->getInnerLocStart(),
1726                                             D->getLocation(),
1727                                     D->getDepth() - TemplateArgs.getNumLevels(),
1728                                             D->getPosition(),
1729                                             D->getIdentifier(), T,
1730                                             DI,
1731                                             ExpandedParameterPackTypes.data(),
1732                                             ExpandedParameterPackTypes.size(),
1733                                     ExpandedParameterPackTypesAsWritten.data());
1734   else
1735     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1736                                             D->getInnerLocStart(),
1737                                             D->getLocation(),
1738                                     D->getDepth() - TemplateArgs.getNumLevels(),
1739                                             D->getPosition(),
1740                                             D->getIdentifier(), T,
1741                                             D->isParameterPack(), DI);
1742 
1743   Param->setAccess(AS_public);
1744   if (Invalid)
1745     Param->setInvalidDecl();
1746 
1747   Param->setDefaultArgument(D->getDefaultArgument(), false);
1748 
1749   // Introduce this template parameter's instantiation into the instantiation
1750   // scope.
1751   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1752   return Param;
1753 }
1754 
1755 Decl *
1756 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1757                                                   TemplateTemplateParmDecl *D) {
1758   // Instantiate the template parameter list of the template template parameter.
1759   TemplateParameterList *TempParams = D->getTemplateParameters();
1760   TemplateParameterList *InstParams;
1761   {
1762     // Perform the actual substitution of template parameters within a new,
1763     // local instantiation scope.
1764     LocalInstantiationScope Scope(SemaRef);
1765     InstParams = SubstTemplateParams(TempParams);
1766     if (!InstParams)
1767       return NULL;
1768   }
1769 
1770   // Build the template template parameter.
1771   TemplateTemplateParmDecl *Param
1772     = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1773                                    D->getDepth() - TemplateArgs.getNumLevels(),
1774                                        D->getPosition(), D->isParameterPack(),
1775                                        D->getIdentifier(), InstParams);
1776   Param->setDefaultArgument(D->getDefaultArgument(), false);
1777   Param->setAccess(AS_public);
1778 
1779   // Introduce this template parameter's instantiation into the instantiation
1780   // scope.
1781   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1782 
1783   return Param;
1784 }
1785 
1786 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1787   // Using directives are never dependent (and never contain any types or
1788   // expressions), so they require no explicit instantiation work.
1789 
1790   UsingDirectiveDecl *Inst
1791     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1792                                  D->getNamespaceKeyLocation(),
1793                                  D->getQualifierLoc(),
1794                                  D->getIdentLocation(),
1795                                  D->getNominatedNamespace(),
1796                                  D->getCommonAncestor());
1797   Owner->addDecl(Inst);
1798   return Inst;
1799 }
1800 
1801 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1802 
1803   // The nested name specifier may be dependent, for example
1804   //     template <typename T> struct t {
1805   //       struct s1 { T f1(); };
1806   //       struct s2 : s1 { using s1::f1; };
1807   //     };
1808   //     template struct t<int>;
1809   // Here, in using s1::f1, s1 refers to t<T>::s1;
1810   // we need to substitute for t<int>::s1.
1811   NestedNameSpecifierLoc QualifierLoc
1812     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1813                                           TemplateArgs);
1814   if (!QualifierLoc)
1815     return 0;
1816 
1817   // The name info is non-dependent, so no transformation
1818   // is required.
1819   DeclarationNameInfo NameInfo = D->getNameInfo();
1820 
1821   // We only need to do redeclaration lookups if we're in a class
1822   // scope (in fact, it's not really even possible in non-class
1823   // scopes).
1824   bool CheckRedeclaration = Owner->isRecord();
1825 
1826   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1827                     Sema::ForRedeclaration);
1828 
1829   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1830                                        D->getUsingLocation(),
1831                                        QualifierLoc,
1832                                        NameInfo,
1833                                        D->isTypeName());
1834 
1835   CXXScopeSpec SS;
1836   SS.Adopt(QualifierLoc);
1837   if (CheckRedeclaration) {
1838     Prev.setHideTags(false);
1839     SemaRef.LookupQualifiedName(Prev, Owner);
1840 
1841     // Check for invalid redeclarations.
1842     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1843                                             D->isTypeName(), SS,
1844                                             D->getLocation(), Prev))
1845       NewUD->setInvalidDecl();
1846 
1847   }
1848 
1849   if (!NewUD->isInvalidDecl() &&
1850       SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1851                                       D->getLocation()))
1852     NewUD->setInvalidDecl();
1853 
1854   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1855   NewUD->setAccess(D->getAccess());
1856   Owner->addDecl(NewUD);
1857 
1858   // Don't process the shadow decls for an invalid decl.
1859   if (NewUD->isInvalidDecl())
1860     return NewUD;
1861 
1862   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
1863     if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
1864       NewUD->setInvalidDecl();
1865     return NewUD;
1866   }
1867 
1868   bool isFunctionScope = Owner->isFunctionOrMethod();
1869 
1870   // Process the shadow decls.
1871   for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1872          I != E; ++I) {
1873     UsingShadowDecl *Shadow = *I;
1874     NamedDecl *InstTarget =
1875       cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1876                                                           Shadow->getLocation(),
1877                                                         Shadow->getTargetDecl(),
1878                                                            TemplateArgs));
1879     if (!InstTarget)
1880       return 0;
1881 
1882     if (CheckRedeclaration &&
1883         SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1884       continue;
1885 
1886     UsingShadowDecl *InstShadow
1887       = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1888     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1889 
1890     if (isFunctionScope)
1891       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
1892   }
1893 
1894   return NewUD;
1895 }
1896 
1897 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1898   // Ignore these;  we handle them in bulk when processing the UsingDecl.
1899   return 0;
1900 }
1901 
1902 Decl * TemplateDeclInstantiator
1903     ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1904   NestedNameSpecifierLoc QualifierLoc
1905     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1906                                           TemplateArgs);
1907   if (!QualifierLoc)
1908     return 0;
1909 
1910   CXXScopeSpec SS;
1911   SS.Adopt(QualifierLoc);
1912 
1913   // Since NameInfo refers to a typename, it cannot be a C++ special name.
1914   // Hence, no tranformation is required for it.
1915   DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
1916   NamedDecl *UD =
1917     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1918                                   D->getUsingLoc(), SS, NameInfo, 0,
1919                                   /*instantiation*/ true,
1920                                   /*typename*/ true, D->getTypenameLoc());
1921   if (UD)
1922     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1923 
1924   return UD;
1925 }
1926 
1927 Decl * TemplateDeclInstantiator
1928     ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1929   NestedNameSpecifierLoc QualifierLoc
1930       = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1931   if (!QualifierLoc)
1932     return 0;
1933 
1934   CXXScopeSpec SS;
1935   SS.Adopt(QualifierLoc);
1936 
1937   DeclarationNameInfo NameInfo
1938     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1939 
1940   NamedDecl *UD =
1941     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1942                                   D->getUsingLoc(), SS, NameInfo, 0,
1943                                   /*instantiation*/ true,
1944                                   /*typename*/ false, SourceLocation());
1945   if (UD)
1946     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1947 
1948   return UD;
1949 }
1950 
1951 
1952 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
1953                                      ClassScopeFunctionSpecializationDecl *Decl) {
1954   CXXMethodDecl *OldFD = Decl->getSpecialization();
1955   CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
1956                                                                 0, true));
1957 
1958   LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
1959                         Sema::ForRedeclaration);
1960 
1961   TemplateArgumentListInfo TemplateArgs;
1962   TemplateArgumentListInfo* TemplateArgsPtr = 0;
1963   if (Decl->hasExplicitTemplateArgs()) {
1964     TemplateArgs = Decl->templateArgs();
1965     TemplateArgsPtr = &TemplateArgs;
1966   }
1967 
1968   SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
1969   if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
1970                                                   Previous)) {
1971     NewFD->setInvalidDecl();
1972     return NewFD;
1973   }
1974 
1975   // Associate the specialization with the pattern.
1976   FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
1977   assert(Specialization && "Class scope Specialization is null");
1978   SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
1979 
1980   return NewFD;
1981 }
1982 
1983 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1984                       const MultiLevelTemplateArgumentList &TemplateArgs) {
1985   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1986   if (D->isInvalidDecl())
1987     return 0;
1988 
1989   return Instantiator.Visit(D);
1990 }
1991 
1992 /// \brief Instantiates a nested template parameter list in the current
1993 /// instantiation context.
1994 ///
1995 /// \param L The parameter list to instantiate
1996 ///
1997 /// \returns NULL if there was an error
1998 TemplateParameterList *
1999 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2000   // Get errors for all the parameters before bailing out.
2001   bool Invalid = false;
2002 
2003   unsigned N = L->size();
2004   typedef SmallVector<NamedDecl *, 8> ParamVector;
2005   ParamVector Params;
2006   Params.reserve(N);
2007   for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2008        PI != PE; ++PI) {
2009     NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2010     Params.push_back(D);
2011     Invalid = Invalid || !D || D->isInvalidDecl();
2012   }
2013 
2014   // Clean up if we had an error.
2015   if (Invalid)
2016     return NULL;
2017 
2018   TemplateParameterList *InstL
2019     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2020                                     L->getLAngleLoc(), &Params.front(), N,
2021                                     L->getRAngleLoc());
2022   return InstL;
2023 }
2024 
2025 /// \brief Instantiate the declaration of a class template partial
2026 /// specialization.
2027 ///
2028 /// \param ClassTemplate the (instantiated) class template that is partially
2029 // specialized by the instantiation of \p PartialSpec.
2030 ///
2031 /// \param PartialSpec the (uninstantiated) class template partial
2032 /// specialization that we are instantiating.
2033 ///
2034 /// \returns The instantiated partial specialization, if successful; otherwise,
2035 /// NULL to indicate an error.
2036 ClassTemplatePartialSpecializationDecl *
2037 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2038                                             ClassTemplateDecl *ClassTemplate,
2039                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
2040   // Create a local instantiation scope for this class template partial
2041   // specialization, which will contain the instantiations of the template
2042   // parameters.
2043   LocalInstantiationScope Scope(SemaRef);
2044 
2045   // Substitute into the template parameters of the class template partial
2046   // specialization.
2047   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2048   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2049   if (!InstParams)
2050     return 0;
2051 
2052   // Substitute into the template arguments of the class template partial
2053   // specialization.
2054   TemplateArgumentListInfo InstTemplateArgs; // no angle locations
2055   if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2056                     PartialSpec->getNumTemplateArgsAsWritten(),
2057                     InstTemplateArgs, TemplateArgs))
2058     return 0;
2059 
2060   // Check that the template argument list is well-formed for this
2061   // class template.
2062   SmallVector<TemplateArgument, 4> Converted;
2063   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2064                                         PartialSpec->getLocation(),
2065                                         InstTemplateArgs,
2066                                         false,
2067                                         Converted))
2068     return 0;
2069 
2070   // Figure out where to insert this class template partial specialization
2071   // in the member template's set of class template partial specializations.
2072   void *InsertPos = 0;
2073   ClassTemplateSpecializationDecl *PrevDecl
2074     = ClassTemplate->findPartialSpecialization(Converted.data(),
2075                                                Converted.size(), InsertPos);
2076 
2077   // Build the canonical type that describes the converted template
2078   // arguments of the class template partial specialization.
2079   QualType CanonType
2080     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2081                                                     Converted.data(),
2082                                                     Converted.size());
2083 
2084   // Build the fully-sugared type for this class template
2085   // specialization as the user wrote in the specialization
2086   // itself. This means that we'll pretty-print the type retrieved
2087   // from the specialization's declaration the way that the user
2088   // actually wrote the specialization, rather than formatting the
2089   // name based on the "canonical" representation used to store the
2090   // template arguments in the specialization.
2091   TypeSourceInfo *WrittenTy
2092     = SemaRef.Context.getTemplateSpecializationTypeInfo(
2093                                                     TemplateName(ClassTemplate),
2094                                                     PartialSpec->getLocation(),
2095                                                     InstTemplateArgs,
2096                                                     CanonType);
2097 
2098   if (PrevDecl) {
2099     // We've already seen a partial specialization with the same template
2100     // parameters and template arguments. This can happen, for example, when
2101     // substituting the outer template arguments ends up causing two
2102     // class template partial specializations of a member class template
2103     // to have identical forms, e.g.,
2104     //
2105     //   template<typename T, typename U>
2106     //   struct Outer {
2107     //     template<typename X, typename Y> struct Inner;
2108     //     template<typename Y> struct Inner<T, Y>;
2109     //     template<typename Y> struct Inner<U, Y>;
2110     //   };
2111     //
2112     //   Outer<int, int> outer; // error: the partial specializations of Inner
2113     //                          // have the same signature.
2114     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2115       << WrittenTy->getType();
2116     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2117       << SemaRef.Context.getTypeDeclType(PrevDecl);
2118     return 0;
2119   }
2120 
2121 
2122   // Create the class template partial specialization declaration.
2123   ClassTemplatePartialSpecializationDecl *InstPartialSpec
2124     = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2125                                                      PartialSpec->getTagKind(),
2126                                                      Owner,
2127                                                      PartialSpec->getLocStart(),
2128                                                      PartialSpec->getLocation(),
2129                                                      InstParams,
2130                                                      ClassTemplate,
2131                                                      Converted.data(),
2132                                                      Converted.size(),
2133                                                      InstTemplateArgs,
2134                                                      CanonType,
2135                                                      0,
2136                              ClassTemplate->getNextPartialSpecSequenceNumber());
2137   // Substitute the nested name specifier, if any.
2138   if (SubstQualifier(PartialSpec, InstPartialSpec))
2139     return 0;
2140 
2141   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2142   InstPartialSpec->setTypeAsWritten(WrittenTy);
2143 
2144   // Add this partial specialization to the set of class template partial
2145   // specializations.
2146   ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2147   return InstPartialSpec;
2148 }
2149 
2150 TypeSourceInfo*
2151 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2152                               SmallVectorImpl<ParmVarDecl *> &Params) {
2153   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2154   assert(OldTInfo && "substituting function without type source info");
2155   assert(Params.empty() && "parameter vector is non-empty at start");
2156 
2157   CXXRecordDecl *ThisContext = 0;
2158   unsigned ThisTypeQuals = 0;
2159   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2160     ThisContext = Method->getParent();
2161     ThisTypeQuals = Method->getTypeQualifiers();
2162   }
2163 
2164   TypeSourceInfo *NewTInfo
2165     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2166                                     D->getTypeSpecStartLoc(),
2167                                     D->getDeclName(),
2168                                     ThisContext, ThisTypeQuals);
2169   if (!NewTInfo)
2170     return 0;
2171 
2172   if (NewTInfo != OldTInfo) {
2173     // Get parameters from the new type info.
2174     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2175     if (FunctionProtoTypeLoc *OldProtoLoc
2176                                   = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2177       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2178       FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2179       assert(NewProtoLoc && "Missing prototype?");
2180       unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2181       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2182            OldIdx != NumOldParams; ++OldIdx) {
2183         ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2184         if (!OldParam->isParameterPack() ||
2185             // FIXME: Is this right? OldParam could expand to an empty parameter
2186             // pack and the next parameter could be an unexpanded parameter pack
2187             (NewIdx < NumNewParams &&
2188              NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2189           // Simple case: normal parameter, or a parameter pack that's
2190           // instantiated to a (still-dependent) parameter pack.
2191           ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2192           Params.push_back(NewParam);
2193           SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2194                                                                NewParam);
2195           continue;
2196         }
2197 
2198         // Parameter pack: make the instantiation an argument pack.
2199         SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2200                                                                       OldParam);
2201         unsigned NumArgumentsInExpansion
2202           = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2203                                                TemplateArgs);
2204         while (NumArgumentsInExpansion--) {
2205           ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2206           Params.push_back(NewParam);
2207           SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2208                                                                       NewParam);
2209         }
2210       }
2211     }
2212   } else {
2213     // The function type itself was not dependent and therefore no
2214     // substitution occurred. However, we still need to instantiate
2215     // the function parameters themselves.
2216     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2217     if (FunctionProtoTypeLoc *OldProtoLoc
2218                                     = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2219       for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2220         ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2221         if (!Parm)
2222           return 0;
2223         Params.push_back(Parm);
2224       }
2225     }
2226   }
2227   return NewTInfo;
2228 }
2229 
2230 /// Introduce the instantiated function parameters into the local
2231 /// instantiation scope, and set the parameter names to those used
2232 /// in the template.
2233 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2234                                              const FunctionDecl *PatternDecl,
2235                                              LocalInstantiationScope &Scope,
2236                            const MultiLevelTemplateArgumentList &TemplateArgs) {
2237   unsigned FParamIdx = 0;
2238   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2239     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2240     if (!PatternParam->isParameterPack()) {
2241       // Simple case: not a parameter pack.
2242       assert(FParamIdx < Function->getNumParams());
2243       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2244       FunctionParam->setDeclName(PatternParam->getDeclName());
2245       Scope.InstantiatedLocal(PatternParam, FunctionParam);
2246       ++FParamIdx;
2247       continue;
2248     }
2249 
2250     // Expand the parameter pack.
2251     Scope.MakeInstantiatedLocalArgPack(PatternParam);
2252     unsigned NumArgumentsInExpansion
2253       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
2254     for (unsigned Arg = 0; Arg < NumArgumentsInExpansion; ++Arg) {
2255       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2256       FunctionParam->setDeclName(PatternParam->getDeclName());
2257       Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2258       ++FParamIdx;
2259     }
2260   }
2261 }
2262 
2263 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2264                                      const FunctionProtoType *Proto,
2265                            const MultiLevelTemplateArgumentList &TemplateArgs) {
2266   assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2267 
2268   // C++11 [expr.prim.general]p3:
2269   //   If a declaration declares a member function or member function
2270   //   template of a class X, the expression this is a prvalue of type
2271   //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2272   //   and the end of the function-definition, member-declarator, or
2273   //   declarator.
2274   CXXRecordDecl *ThisContext = 0;
2275   unsigned ThisTypeQuals = 0;
2276   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2277     ThisContext = Method->getParent();
2278     ThisTypeQuals = Method->getTypeQualifiers();
2279   }
2280   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
2281                                    SemaRef.getLangOpts().CPlusPlus0x);
2282 
2283   // The function has an exception specification or a "noreturn"
2284   // attribute. Substitute into each of the exception types.
2285   SmallVector<QualType, 4> Exceptions;
2286   for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2287     // FIXME: Poor location information!
2288     if (const PackExpansionType *PackExpansion
2289           = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2290       // We have a pack expansion. Instantiate it.
2291       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2292       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2293                                               Unexpanded);
2294       assert(!Unexpanded.empty() &&
2295              "Pack expansion without parameter packs?");
2296 
2297       bool Expand = false;
2298       bool RetainExpansion = false;
2299       llvm::Optional<unsigned> NumExpansions
2300                                         = PackExpansion->getNumExpansions();
2301       if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2302                                                   SourceRange(),
2303                                                   Unexpanded,
2304                                                   TemplateArgs,
2305                                                   Expand,
2306                                                   RetainExpansion,
2307                                                   NumExpansions))
2308         break;
2309 
2310       if (!Expand) {
2311         // We can't expand this pack expansion into separate arguments yet;
2312         // just substitute into the pattern and create a new pack expansion
2313         // type.
2314         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2315         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2316                                        TemplateArgs,
2317                                      New->getLocation(), New->getDeclName());
2318         if (T.isNull())
2319           break;
2320 
2321         T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2322         Exceptions.push_back(T);
2323         continue;
2324       }
2325 
2326       // Substitute into the pack expansion pattern for each template
2327       bool Invalid = false;
2328       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2329         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2330 
2331         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2332                                        TemplateArgs,
2333                                      New->getLocation(), New->getDeclName());
2334         if (T.isNull()) {
2335           Invalid = true;
2336           break;
2337         }
2338 
2339         Exceptions.push_back(T);
2340       }
2341 
2342       if (Invalid)
2343         break;
2344 
2345       continue;
2346     }
2347 
2348     QualType T
2349       = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2350                           New->getLocation(), New->getDeclName());
2351     if (T.isNull() ||
2352         SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2353       continue;
2354 
2355     Exceptions.push_back(T);
2356   }
2357   Expr *NoexceptExpr = 0;
2358   if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2359     EnterExpressionEvaluationContext Unevaluated(SemaRef,
2360                                                  Sema::ConstantEvaluated);
2361     ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2362     if (E.isUsable())
2363       E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2364 
2365     if (E.isUsable()) {
2366       NoexceptExpr = E.take();
2367       if (!NoexceptExpr->isTypeDependent() &&
2368           !NoexceptExpr->isValueDependent())
2369         NoexceptExpr
2370           = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2371               0, diag::err_noexcept_needs_constant_expression,
2372               /*AllowFold*/ false).take();
2373     }
2374   }
2375 
2376   // Rebuild the function type
2377   const FunctionProtoType *NewProto
2378     = New->getType()->getAs<FunctionProtoType>();
2379   assert(NewProto && "Template instantiation without function prototype?");
2380 
2381   FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2382   EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2383   EPI.NumExceptions = Exceptions.size();
2384   EPI.Exceptions = Exceptions.data();
2385   EPI.NoexceptExpr = NoexceptExpr;
2386 
2387   New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2388                                                NewProto->arg_type_begin(),
2389                                                NewProto->getNumArgs(),
2390                                                EPI));
2391 }
2392 
2393 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2394                                     FunctionDecl *Decl) {
2395   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2396   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
2397     return;
2398 
2399   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2400                              InstantiatingTemplate::ExceptionSpecification());
2401   if (Inst)
2402     return;
2403 
2404   // Enter the scope of this instantiation. We don't use
2405   // PushDeclContext because we don't have a scope.
2406   Sema::ContextRAII savedContext(*this, Decl);
2407   LocalInstantiationScope Scope(*this);
2408 
2409   MultiLevelTemplateArgumentList TemplateArgs =
2410     getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2411 
2412   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2413   addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
2414 
2415   ::InstantiateExceptionSpec(*this, Decl,
2416                              Template->getType()->castAs<FunctionProtoType>(),
2417                              TemplateArgs);
2418 }
2419 
2420 /// \brief Initializes the common fields of an instantiation function
2421 /// declaration (New) from the corresponding fields of its template (Tmpl).
2422 ///
2423 /// \returns true if there was an error
2424 bool
2425 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
2426                                                     FunctionDecl *Tmpl) {
2427   if (Tmpl->isDeletedAsWritten())
2428     New->setDeletedAsWritten();
2429 
2430   // If we are performing substituting explicitly-specified template arguments
2431   // or deduced template arguments into a function template and we reach this
2432   // point, we are now past the point where SFINAE applies and have committed
2433   // to keeping the new function template specialization. We therefore
2434   // convert the active template instantiation for the function template
2435   // into a template instantiation for this specific function template
2436   // specialization, which is not a SFINAE context, so that we diagnose any
2437   // further errors in the declaration itself.
2438   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2439   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2440   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2441       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
2442     if (FunctionTemplateDecl *FunTmpl
2443           = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
2444       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
2445              "Deduction from the wrong function template?");
2446       (void) FunTmpl;
2447       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2448       ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
2449       --SemaRef.NonInstantiationEntries;
2450     }
2451   }
2452 
2453   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2454   assert(Proto && "Function template without prototype?");
2455 
2456   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
2457     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2458 
2459     // DR1330: In C++11, defer instantiation of a non-trivial
2460     // exception specification.
2461     if (SemaRef.getLangOpts().CPlusPlus0x &&
2462         EPI.ExceptionSpecType != EST_None &&
2463         EPI.ExceptionSpecType != EST_DynamicNone &&
2464         EPI.ExceptionSpecType != EST_BasicNoexcept) {
2465       FunctionDecl *ExceptionSpecTemplate = Tmpl;
2466       if (EPI.ExceptionSpecType == EST_Uninstantiated)
2467         ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
2468 
2469       // Mark the function has having an uninstantiated exception specification.
2470       const FunctionProtoType *NewProto
2471         = New->getType()->getAs<FunctionProtoType>();
2472       assert(NewProto && "Template instantiation without function prototype?");
2473       EPI = NewProto->getExtProtoInfo();
2474       EPI.ExceptionSpecType = EST_Uninstantiated;
2475       EPI.ExceptionSpecDecl = New;
2476       EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
2477       New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2478                                                    NewProto->arg_type_begin(),
2479                                                    NewProto->getNumArgs(),
2480                                                    EPI));
2481     } else {
2482       ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2483     }
2484   }
2485 
2486   // Get the definition. Leaves the variable unchanged if undefined.
2487   const FunctionDecl *Definition = Tmpl;
2488   Tmpl->isDefined(Definition);
2489 
2490   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2491                            LateAttrs, StartingScope);
2492 
2493   return false;
2494 }
2495 
2496 /// \brief Initializes common fields of an instantiated method
2497 /// declaration (New) from the corresponding fields of its template
2498 /// (Tmpl).
2499 ///
2500 /// \returns true if there was an error
2501 bool
2502 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
2503                                                   CXXMethodDecl *Tmpl) {
2504   if (InitFunctionInstantiation(New, Tmpl))
2505     return true;
2506 
2507   New->setAccess(Tmpl->getAccess());
2508   if (Tmpl->isVirtualAsWritten())
2509     New->setVirtualAsWritten(true);
2510 
2511   // FIXME: attributes
2512   // FIXME: New needs a pointer to Tmpl
2513   return false;
2514 }
2515 
2516 /// \brief Instantiate the definition of the given function from its
2517 /// template.
2518 ///
2519 /// \param PointOfInstantiation the point at which the instantiation was
2520 /// required. Note that this is not precisely a "point of instantiation"
2521 /// for the function, but it's close.
2522 ///
2523 /// \param Function the already-instantiated declaration of a
2524 /// function template specialization or member function of a class template
2525 /// specialization.
2526 ///
2527 /// \param Recursive if true, recursively instantiates any functions that
2528 /// are required by this instantiation.
2529 ///
2530 /// \param DefinitionRequired if true, then we are performing an explicit
2531 /// instantiation where the body of the function is required. Complain if
2532 /// there is no such body.
2533 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
2534                                          FunctionDecl *Function,
2535                                          bool Recursive,
2536                                          bool DefinitionRequired) {
2537   if (Function->isInvalidDecl() || Function->isDefined())
2538     return;
2539 
2540   // Never instantiate an explicit specialization except if it is a class scope
2541   // explicit specialization.
2542   if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2543       !Function->getClassScopeSpecializationPattern())
2544     return;
2545 
2546   // Find the function body that we'll be substituting.
2547   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
2548   assert(PatternDecl && "instantiating a non-template");
2549 
2550   Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2551   assert(PatternDecl && "template definition is not a template");
2552   if (!Pattern) {
2553     // Try to find a defaulted definition
2554     PatternDecl->isDefined(PatternDecl);
2555   }
2556   assert(PatternDecl && "template definition is not a template");
2557 
2558   // Postpone late parsed template instantiations.
2559   if (PatternDecl->isLateTemplateParsed() &&
2560       !LateTemplateParser) {
2561     PendingInstantiations.push_back(
2562       std::make_pair(Function, PointOfInstantiation));
2563     return;
2564   }
2565 
2566   // Call the LateTemplateParser callback if there a need to late parse
2567   // a templated function definition.
2568   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
2569       LateTemplateParser) {
2570     LateTemplateParser(OpaqueParser, PatternDecl);
2571     Pattern = PatternDecl->getBody(PatternDecl);
2572   }
2573 
2574   if (!Pattern && !PatternDecl->isDefaulted()) {
2575     if (DefinitionRequired) {
2576       if (Function->getPrimaryTemplate())
2577         Diag(PointOfInstantiation,
2578              diag::err_explicit_instantiation_undefined_func_template)
2579           << Function->getPrimaryTemplate();
2580       else
2581         Diag(PointOfInstantiation,
2582              diag::err_explicit_instantiation_undefined_member)
2583           << 1 << Function->getDeclName() << Function->getDeclContext();
2584 
2585       if (PatternDecl)
2586         Diag(PatternDecl->getLocation(),
2587              diag::note_explicit_instantiation_here);
2588       Function->setInvalidDecl();
2589     } else if (Function->getTemplateSpecializationKind()
2590                  == TSK_ExplicitInstantiationDefinition) {
2591       PendingInstantiations.push_back(
2592         std::make_pair(Function, PointOfInstantiation));
2593     }
2594 
2595     return;
2596   }
2597 
2598   // C++0x [temp.explicit]p9:
2599   //   Except for inline functions, other explicit instantiation declarations
2600   //   have the effect of suppressing the implicit instantiation of the entity
2601   //   to which they refer.
2602   if (Function->getTemplateSpecializationKind()
2603         == TSK_ExplicitInstantiationDeclaration &&
2604       !PatternDecl->isInlined())
2605     return;
2606 
2607   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2608   if (Inst)
2609     return;
2610 
2611   // Copy the inner loc start from the pattern.
2612   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2613 
2614   // If we're performing recursive template instantiation, create our own
2615   // queue of pending implicit instantiations that we will instantiate later,
2616   // while we're still within our own instantiation context.
2617   SmallVector<VTableUse, 16> SavedVTableUses;
2618   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2619   if (Recursive) {
2620     VTableUses.swap(SavedVTableUses);
2621     PendingInstantiations.swap(SavedPendingInstantiations);
2622   }
2623 
2624   EnterExpressionEvaluationContext EvalContext(*this,
2625                                                Sema::PotentiallyEvaluated);
2626   ActOnStartOfFunctionDef(0, Function);
2627 
2628   // Introduce a new scope where local variable instantiations will be
2629   // recorded, unless we're actually a member function within a local
2630   // class, in which case we need to merge our results with the parent
2631   // scope (of the enclosing function).
2632   bool MergeWithParentScope = false;
2633   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2634     MergeWithParentScope = Rec->isLocalClass();
2635 
2636   LocalInstantiationScope Scope(*this, MergeWithParentScope);
2637 
2638   // Enter the scope of this instantiation. We don't use
2639   // PushDeclContext because we don't have a scope.
2640   Sema::ContextRAII savedContext(*this, Function);
2641 
2642   MultiLevelTemplateArgumentList TemplateArgs =
2643     getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2644 
2645   addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2646                                    TemplateArgs);
2647 
2648   if (PatternDecl->isDefaulted()) {
2649     ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
2650 
2651     SetDeclDefaulted(Function, PatternDecl->getLocation());
2652   } else {
2653     // If this is a constructor, instantiate the member initializers.
2654     if (const CXXConstructorDecl *Ctor =
2655           dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2656       InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2657                                  TemplateArgs);
2658     }
2659 
2660     // Instantiate the function body.
2661     StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2662 
2663     if (Body.isInvalid())
2664       Function->setInvalidDecl();
2665 
2666     ActOnFinishFunctionBody(Function, Body.get(),
2667                             /*IsInstantiation=*/true);
2668   }
2669 
2670   PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2671 
2672   savedContext.pop();
2673 
2674   DeclGroupRef DG(Function);
2675   Consumer.HandleTopLevelDecl(DG);
2676 
2677   // This class may have local implicit instantiations that need to be
2678   // instantiation within this scope.
2679   PerformPendingInstantiations(/*LocalOnly=*/true);
2680   Scope.Exit();
2681 
2682   if (Recursive) {
2683     // Define any pending vtables.
2684     DefineUsedVTables();
2685 
2686     // Instantiate any pending implicit instantiations found during the
2687     // instantiation of this template.
2688     PerformPendingInstantiations();
2689 
2690     // Restore the set of pending vtables.
2691     assert(VTableUses.empty() &&
2692            "VTableUses should be empty before it is discarded.");
2693     VTableUses.swap(SavedVTableUses);
2694 
2695     // Restore the set of pending implicit instantiations.
2696     assert(PendingInstantiations.empty() &&
2697            "PendingInstantiations should be empty before it is discarded.");
2698     PendingInstantiations.swap(SavedPendingInstantiations);
2699   }
2700 }
2701 
2702 /// \brief Instantiate the definition of the given variable from its
2703 /// template.
2704 ///
2705 /// \param PointOfInstantiation the point at which the instantiation was
2706 /// required. Note that this is not precisely a "point of instantiation"
2707 /// for the function, but it's close.
2708 ///
2709 /// \param Var the already-instantiated declaration of a static member
2710 /// variable of a class template specialization.
2711 ///
2712 /// \param Recursive if true, recursively instantiates any functions that
2713 /// are required by this instantiation.
2714 ///
2715 /// \param DefinitionRequired if true, then we are performing an explicit
2716 /// instantiation where an out-of-line definition of the member variable
2717 /// is required. Complain if there is no such definition.
2718 void Sema::InstantiateStaticDataMemberDefinition(
2719                                           SourceLocation PointOfInstantiation,
2720                                                  VarDecl *Var,
2721                                                  bool Recursive,
2722                                                  bool DefinitionRequired) {
2723   if (Var->isInvalidDecl())
2724     return;
2725 
2726   // Find the out-of-line definition of this static data member.
2727   VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
2728   assert(Def && "This data member was not instantiated from a template?");
2729   assert(Def->isStaticDataMember() && "Not a static data member?");
2730   Def = Def->getOutOfLineDefinition();
2731 
2732   if (!Def) {
2733     // We did not find an out-of-line definition of this static data member,
2734     // so we won't perform any instantiation. Rather, we rely on the user to
2735     // instantiate this definition (or provide a specialization for it) in
2736     // another translation unit.
2737     if (DefinitionRequired) {
2738       Def = Var->getInstantiatedFromStaticDataMember();
2739       Diag(PointOfInstantiation,
2740            diag::err_explicit_instantiation_undefined_member)
2741         << 2 << Var->getDeclName() << Var->getDeclContext();
2742       Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2743     } else if (Var->getTemplateSpecializationKind()
2744                  == TSK_ExplicitInstantiationDefinition) {
2745       PendingInstantiations.push_back(
2746         std::make_pair(Var, PointOfInstantiation));
2747     }
2748 
2749     return;
2750   }
2751 
2752   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
2753 
2754   // Never instantiate an explicit specialization.
2755   if (TSK == TSK_ExplicitSpecialization)
2756     return;
2757 
2758   // C++0x [temp.explicit]p9:
2759   //   Except for inline functions, other explicit instantiation declarations
2760   //   have the effect of suppressing the implicit instantiation of the entity
2761   //   to which they refer.
2762   if (TSK == TSK_ExplicitInstantiationDeclaration)
2763     return;
2764 
2765   Consumer.HandleCXXStaticMemberVarInstantiation(Var);
2766 
2767   // If we already have a definition, we're done.
2768   if (VarDecl *Def = Var->getDefinition()) {
2769     // We may be explicitly instantiating something we've already implicitly
2770     // instantiated.
2771     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
2772                                        PointOfInstantiation);
2773     return;
2774   }
2775 
2776   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2777   if (Inst)
2778     return;
2779 
2780   // If we're performing recursive template instantiation, create our own
2781   // queue of pending implicit instantiations that we will instantiate later,
2782   // while we're still within our own instantiation context.
2783   SmallVector<VTableUse, 16> SavedVTableUses;
2784   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2785   if (Recursive) {
2786     VTableUses.swap(SavedVTableUses);
2787     PendingInstantiations.swap(SavedPendingInstantiations);
2788   }
2789 
2790   // Enter the scope of this instantiation. We don't use
2791   // PushDeclContext because we don't have a scope.
2792   ContextRAII previousContext(*this, Var->getDeclContext());
2793   LocalInstantiationScope Local(*this);
2794 
2795   VarDecl *OldVar = Var;
2796   Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
2797                                         getTemplateInstantiationArgs(Var)));
2798 
2799   previousContext.pop();
2800 
2801   if (Var) {
2802     MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2803     assert(MSInfo && "Missing member specialization information?");
2804     Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2805                                        MSInfo->getPointOfInstantiation());
2806     DeclGroupRef DG(Var);
2807     Consumer.HandleTopLevelDecl(DG);
2808   }
2809   Local.Exit();
2810 
2811   if (Recursive) {
2812     // Define any newly required vtables.
2813     DefineUsedVTables();
2814 
2815     // Instantiate any pending implicit instantiations found during the
2816     // instantiation of this template.
2817     PerformPendingInstantiations();
2818 
2819     // Restore the set of pending vtables.
2820     assert(VTableUses.empty() &&
2821            "VTableUses should be empty before it is discarded, "
2822            "while instantiating static data member.");
2823     VTableUses.swap(SavedVTableUses);
2824 
2825     // Restore the set of pending implicit instantiations.
2826     assert(PendingInstantiations.empty() &&
2827            "PendingInstantiations should be empty before it is discarded, "
2828            "while instantiating static data member.");
2829     PendingInstantiations.swap(SavedPendingInstantiations);
2830   }
2831 }
2832 
2833 void
2834 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2835                                  const CXXConstructorDecl *Tmpl,
2836                            const MultiLevelTemplateArgumentList &TemplateArgs) {
2837 
2838   SmallVector<CXXCtorInitializer*, 4> NewInits;
2839   bool AnyErrors = false;
2840 
2841   // Instantiate all the initializers.
2842   for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
2843                                             InitsEnd = Tmpl->init_end();
2844        Inits != InitsEnd; ++Inits) {
2845     CXXCtorInitializer *Init = *Inits;
2846 
2847     // Only instantiate written initializers, let Sema re-construct implicit
2848     // ones.
2849     if (!Init->isWritten())
2850       continue;
2851 
2852     SourceLocation EllipsisLoc;
2853 
2854     if (Init->isPackExpansion()) {
2855       // This is a pack expansion. We should expand it now.
2856       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
2857       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2858       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2859       bool ShouldExpand = false;
2860       bool RetainExpansion = false;
2861       llvm::Optional<unsigned> NumExpansions;
2862       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2863                                           BaseTL.getSourceRange(),
2864                                           Unexpanded,
2865                                           TemplateArgs, ShouldExpand,
2866                                           RetainExpansion,
2867                                           NumExpansions)) {
2868         AnyErrors = true;
2869         New->setInvalidDecl();
2870         continue;
2871       }
2872       assert(ShouldExpand && "Partial instantiation of base initializer?");
2873 
2874       // Loop over all of the arguments in the argument pack(s),
2875       for (unsigned I = 0; I != *NumExpansions; ++I) {
2876         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2877 
2878         // Instantiate the initializer.
2879         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
2880                                                /*CXXDirectInit=*/true);
2881         if (TempInit.isInvalid()) {
2882           AnyErrors = true;
2883           break;
2884         }
2885 
2886         // Instantiate the base type.
2887         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
2888                                               TemplateArgs,
2889                                               Init->getSourceLocation(),
2890                                               New->getDeclName());
2891         if (!BaseTInfo) {
2892           AnyErrors = true;
2893           break;
2894         }
2895 
2896         // Build the initializer.
2897         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2898                                                      BaseTInfo, TempInit.take(),
2899                                                      New->getParent(),
2900                                                      SourceLocation());
2901         if (NewInit.isInvalid()) {
2902           AnyErrors = true;
2903           break;
2904         }
2905 
2906         NewInits.push_back(NewInit.get());
2907       }
2908 
2909       continue;
2910     }
2911 
2912     // Instantiate the initializer.
2913     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
2914                                            /*CXXDirectInit=*/true);
2915     if (TempInit.isInvalid()) {
2916       AnyErrors = true;
2917       continue;
2918     }
2919 
2920     MemInitResult NewInit;
2921     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
2922       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
2923                                         TemplateArgs,
2924                                         Init->getSourceLocation(),
2925                                         New->getDeclName());
2926       if (!TInfo) {
2927         AnyErrors = true;
2928         New->setInvalidDecl();
2929         continue;
2930       }
2931 
2932       if (Init->isBaseInitializer())
2933         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
2934                                        New->getParent(), EllipsisLoc);
2935       else
2936         NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
2937                                   cast<CXXRecordDecl>(CurContext->getParent()));
2938     } else if (Init->isMemberInitializer()) {
2939       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
2940                                                      Init->getMemberLocation(),
2941                                                      Init->getMember(),
2942                                                      TemplateArgs));
2943       if (!Member) {
2944         AnyErrors = true;
2945         New->setInvalidDecl();
2946         continue;
2947       }
2948 
2949       NewInit = BuildMemberInitializer(Member, TempInit.take(),
2950                                        Init->getSourceLocation());
2951     } else if (Init->isIndirectMemberInitializer()) {
2952       IndirectFieldDecl *IndirectMember =
2953          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
2954                                  Init->getMemberLocation(),
2955                                  Init->getIndirectMember(), TemplateArgs));
2956 
2957       if (!IndirectMember) {
2958         AnyErrors = true;
2959         New->setInvalidDecl();
2960         continue;
2961       }
2962 
2963       NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
2964                                        Init->getSourceLocation());
2965     }
2966 
2967     if (NewInit.isInvalid()) {
2968       AnyErrors = true;
2969       New->setInvalidDecl();
2970     } else {
2971       NewInits.push_back(NewInit.get());
2972     }
2973   }
2974 
2975   // Assign all the initializers to the new constructor.
2976   ActOnMemInitializers(New,
2977                        /*FIXME: ColonLoc */
2978                        SourceLocation(),
2979                        NewInits.data(), NewInits.size(),
2980                        AnyErrors);
2981 }
2982 
2983 ExprResult Sema::SubstInitializer(Expr *Init,
2984                           const MultiLevelTemplateArgumentList &TemplateArgs,
2985                           bool CXXDirectInit) {
2986   // Initializers are instantiated like expressions, except that various outer
2987   // layers are stripped.
2988   if (!Init)
2989     return Owned(Init);
2990 
2991   if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
2992     Init = ExprTemp->getSubExpr();
2993 
2994   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
2995     Init = Binder->getSubExpr();
2996 
2997   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
2998     Init = ICE->getSubExprAsWritten();
2999 
3000   // If this is a direct-initializer, we take apart CXXConstructExprs.
3001   // Everything else is passed through.
3002   CXXConstructExpr *Construct;
3003   if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) ||
3004       isa<CXXTemporaryObjectExpr>(Construct))
3005     return SubstExpr(Init, TemplateArgs);
3006 
3007   ASTOwningVector<Expr*> NewArgs(*this);
3008   if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
3009                  TemplateArgs, NewArgs))
3010     return ExprError();
3011 
3012   // Treat an empty initializer like none.
3013   if (NewArgs.empty())
3014     return Owned((Expr*)0);
3015 
3016   // Build a ParenListExpr to represent anything else.
3017   // FIXME: Fake locations!
3018   SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart());
3019   return ActOnParenListExpr(Loc, Loc, move_arg(NewArgs));
3020 }
3021 
3022 // TODO: this could be templated if the various decl types used the
3023 // same method name.
3024 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3025                               ClassTemplateDecl *Instance) {
3026   Pattern = Pattern->getCanonicalDecl();
3027 
3028   do {
3029     Instance = Instance->getCanonicalDecl();
3030     if (Pattern == Instance) return true;
3031     Instance = Instance->getInstantiatedFromMemberTemplate();
3032   } while (Instance);
3033 
3034   return false;
3035 }
3036 
3037 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3038                               FunctionTemplateDecl *Instance) {
3039   Pattern = Pattern->getCanonicalDecl();
3040 
3041   do {
3042     Instance = Instance->getCanonicalDecl();
3043     if (Pattern == Instance) return true;
3044     Instance = Instance->getInstantiatedFromMemberTemplate();
3045   } while (Instance);
3046 
3047   return false;
3048 }
3049 
3050 static bool
3051 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3052                   ClassTemplatePartialSpecializationDecl *Instance) {
3053   Pattern
3054     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3055   do {
3056     Instance = cast<ClassTemplatePartialSpecializationDecl>(
3057                                                 Instance->getCanonicalDecl());
3058     if (Pattern == Instance)
3059       return true;
3060     Instance = Instance->getInstantiatedFromMember();
3061   } while (Instance);
3062 
3063   return false;
3064 }
3065 
3066 static bool isInstantiationOf(CXXRecordDecl *Pattern,
3067                               CXXRecordDecl *Instance) {
3068   Pattern = Pattern->getCanonicalDecl();
3069 
3070   do {
3071     Instance = Instance->getCanonicalDecl();
3072     if (Pattern == Instance) return true;
3073     Instance = Instance->getInstantiatedFromMemberClass();
3074   } while (Instance);
3075 
3076   return false;
3077 }
3078 
3079 static bool isInstantiationOf(FunctionDecl *Pattern,
3080                               FunctionDecl *Instance) {
3081   Pattern = Pattern->getCanonicalDecl();
3082 
3083   do {
3084     Instance = Instance->getCanonicalDecl();
3085     if (Pattern == Instance) return true;
3086     Instance = Instance->getInstantiatedFromMemberFunction();
3087   } while (Instance);
3088 
3089   return false;
3090 }
3091 
3092 static bool isInstantiationOf(EnumDecl *Pattern,
3093                               EnumDecl *Instance) {
3094   Pattern = Pattern->getCanonicalDecl();
3095 
3096   do {
3097     Instance = Instance->getCanonicalDecl();
3098     if (Pattern == Instance) return true;
3099     Instance = Instance->getInstantiatedFromMemberEnum();
3100   } while (Instance);
3101 
3102   return false;
3103 }
3104 
3105 static bool isInstantiationOf(UsingShadowDecl *Pattern,
3106                               UsingShadowDecl *Instance,
3107                               ASTContext &C) {
3108   return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3109 }
3110 
3111 static bool isInstantiationOf(UsingDecl *Pattern,
3112                               UsingDecl *Instance,
3113                               ASTContext &C) {
3114   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3115 }
3116 
3117 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3118                               UsingDecl *Instance,
3119                               ASTContext &C) {
3120   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3121 }
3122 
3123 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
3124                               UsingDecl *Instance,
3125                               ASTContext &C) {
3126   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3127 }
3128 
3129 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3130                                               VarDecl *Instance) {
3131   assert(Instance->isStaticDataMember());
3132 
3133   Pattern = Pattern->getCanonicalDecl();
3134 
3135   do {
3136     Instance = Instance->getCanonicalDecl();
3137     if (Pattern == Instance) return true;
3138     Instance = Instance->getInstantiatedFromStaticDataMember();
3139   } while (Instance);
3140 
3141   return false;
3142 }
3143 
3144 // Other is the prospective instantiation
3145 // D is the prospective pattern
3146 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
3147   if (D->getKind() != Other->getKind()) {
3148     if (UnresolvedUsingTypenameDecl *UUD
3149           = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3150       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3151         return isInstantiationOf(UUD, UD, Ctx);
3152       }
3153     }
3154 
3155     if (UnresolvedUsingValueDecl *UUD
3156           = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3157       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3158         return isInstantiationOf(UUD, UD, Ctx);
3159       }
3160     }
3161 
3162     return false;
3163   }
3164 
3165   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3166     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
3167 
3168   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3169     return isInstantiationOf(cast<FunctionDecl>(D), Function);
3170 
3171   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3172     return isInstantiationOf(cast<EnumDecl>(D), Enum);
3173 
3174   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
3175     if (Var->isStaticDataMember())
3176       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3177 
3178   if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3179     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
3180 
3181   if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3182     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3183 
3184   if (ClassTemplatePartialSpecializationDecl *PartialSpec
3185         = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3186     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3187                              PartialSpec);
3188 
3189   if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3190     if (!Field->getDeclName()) {
3191       // This is an unnamed field.
3192       return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
3193         cast<FieldDecl>(D);
3194     }
3195   }
3196 
3197   if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3198     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3199 
3200   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3201     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3202 
3203   return D->getDeclName() && isa<NamedDecl>(Other) &&
3204     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3205 }
3206 
3207 template<typename ForwardIterator>
3208 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
3209                                       NamedDecl *D,
3210                                       ForwardIterator first,
3211                                       ForwardIterator last) {
3212   for (; first != last; ++first)
3213     if (isInstantiationOf(Ctx, D, *first))
3214       return cast<NamedDecl>(*first);
3215 
3216   return 0;
3217 }
3218 
3219 /// \brief Finds the instantiation of the given declaration context
3220 /// within the current instantiation.
3221 ///
3222 /// \returns NULL if there was an error
3223 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
3224                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3225   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
3226     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
3227     return cast_or_null<DeclContext>(ID);
3228   } else return DC;
3229 }
3230 
3231 /// \brief Find the instantiation of the given declaration within the
3232 /// current instantiation.
3233 ///
3234 /// This routine is intended to be used when \p D is a declaration
3235 /// referenced from within a template, that needs to mapped into the
3236 /// corresponding declaration within an instantiation. For example,
3237 /// given:
3238 ///
3239 /// \code
3240 /// template<typename T>
3241 /// struct X {
3242 ///   enum Kind {
3243 ///     KnownValue = sizeof(T)
3244 ///   };
3245 ///
3246 ///   bool getKind() const { return KnownValue; }
3247 /// };
3248 ///
3249 /// template struct X<int>;
3250 /// \endcode
3251 ///
3252 /// In the instantiation of X<int>::getKind(), we need to map the
3253 /// EnumConstantDecl for KnownValue (which refers to
3254 /// X<T>::\<Kind>\::KnownValue) to its instantiation
3255 /// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
3256 /// this mapping from within the instantiation of X<int>.
3257 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
3258                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3259   DeclContext *ParentDC = D->getDeclContext();
3260   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
3261       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
3262       (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3263       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
3264     // D is a local of some kind. Look into the map of local
3265     // declarations to their instantiations.
3266     typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3267     llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3268       = CurrentInstantiationScope->findInstantiationOf(D);
3269 
3270     if (Found) {
3271       if (Decl *FD = Found->dyn_cast<Decl *>())
3272         return cast<NamedDecl>(FD);
3273 
3274       unsigned PackIdx = ArgumentPackSubstitutionIndex;
3275       return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3276     }
3277 
3278     // If we didn't find the decl, then we must have a label decl that hasn't
3279     // been found yet.  Lazily instantiate it and return it now.
3280     assert(isa<LabelDecl>(D));
3281 
3282     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3283     assert(Inst && "Failed to instantiate label??");
3284 
3285     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3286     return cast<LabelDecl>(Inst);
3287   }
3288 
3289   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3290     if (!Record->isDependentContext())
3291       return D;
3292 
3293     // Determine whether this record is the "templated" declaration describing
3294     // a class template or class template partial specialization.
3295     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3296     if (ClassTemplate)
3297       ClassTemplate = ClassTemplate->getCanonicalDecl();
3298     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3299                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3300       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3301 
3302     // Walk the current context to find either the record or an instantiation of
3303     // it.
3304     DeclContext *DC = CurContext;
3305     while (!DC->isFileContext()) {
3306       // If we're performing substitution while we're inside the template
3307       // definition, we'll find our own context. We're done.
3308       if (DC->Equals(Record))
3309         return Record;
3310 
3311       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3312         // Check whether we're in the process of instantiating a class template
3313         // specialization of the template we're mapping.
3314         if (ClassTemplateSpecializationDecl *InstSpec
3315                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3316           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3317           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3318             return InstRecord;
3319         }
3320 
3321         // Check whether we're in the process of instantiating a member class.
3322         if (isInstantiationOf(Record, InstRecord))
3323           return InstRecord;
3324       }
3325 
3326 
3327       // Move to the outer template scope.
3328       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3329         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3330           DC = FD->getLexicalDeclContext();
3331           continue;
3332         }
3333       }
3334 
3335       DC = DC->getParent();
3336     }
3337 
3338     // Fall through to deal with other dependent record types (e.g.,
3339     // anonymous unions in class templates).
3340   }
3341 
3342   if (!ParentDC->isDependentContext())
3343     return D;
3344 
3345   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
3346   if (!ParentDC)
3347     return 0;
3348 
3349   if (ParentDC != D->getDeclContext()) {
3350     // We performed some kind of instantiation in the parent context,
3351     // so now we need to look into the instantiated parent context to
3352     // find the instantiation of the declaration D.
3353 
3354     // If our context used to be dependent, we may need to instantiate
3355     // it before performing lookup into that context.
3356     bool IsBeingInstantiated = false;
3357     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
3358       if (!Spec->isDependentContext()) {
3359         QualType T = Context.getTypeDeclType(Spec);
3360         const RecordType *Tag = T->getAs<RecordType>();
3361         assert(Tag && "type of non-dependent record is not a RecordType");
3362         if (Tag->isBeingDefined())
3363           IsBeingInstantiated = true;
3364         if (!Tag->isBeingDefined() &&
3365             RequireCompleteType(Loc, T, diag::err_incomplete_type))
3366           return 0;
3367 
3368         ParentDC = Tag->getDecl();
3369       }
3370     }
3371 
3372     NamedDecl *Result = 0;
3373     if (D->getDeclName()) {
3374       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
3375       Result = findInstantiationOf(Context, D, Found.first, Found.second);
3376     } else {
3377       // Since we don't have a name for the entity we're looking for,
3378       // our only option is to walk through all of the declarations to
3379       // find that name. This will occur in a few cases:
3380       //
3381       //   - anonymous struct/union within a template
3382       //   - unnamed class/struct/union/enum within a template
3383       //
3384       // FIXME: Find a better way to find these instantiations!
3385       Result = findInstantiationOf(Context, D,
3386                                    ParentDC->decls_begin(),
3387                                    ParentDC->decls_end());
3388     }
3389 
3390     if (!Result) {
3391       if (isa<UsingShadowDecl>(D)) {
3392         // UsingShadowDecls can instantiate to nothing because of using hiding.
3393       } else if (Diags.hasErrorOccurred()) {
3394         // We've already complained about something, so most likely this
3395         // declaration failed to instantiate. There's no point in complaining
3396         // further, since this is normal in invalid code.
3397       } else if (IsBeingInstantiated) {
3398         // The class in which this member exists is currently being
3399         // instantiated, and we haven't gotten around to instantiating this
3400         // member yet. This can happen when the code uses forward declarations
3401         // of member classes, and introduces ordering dependencies via
3402         // template instantiation.
3403         Diag(Loc, diag::err_member_not_yet_instantiated)
3404           << D->getDeclName()
3405           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3406         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3407       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3408         // This enumeration constant was found when the template was defined,
3409         // but can't be found in the instantiation. This can happen if an
3410         // unscoped enumeration member is explicitly specialized.
3411         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3412         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3413                                                              TemplateArgs));
3414         assert(Spec->getTemplateSpecializationKind() ==
3415                  TSK_ExplicitSpecialization);
3416         Diag(Loc, diag::err_enumerator_does_not_exist)
3417           << D->getDeclName()
3418           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3419         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3420           << Context.getTypeDeclType(Spec);
3421       } else {
3422         // We should have found something, but didn't.
3423         llvm_unreachable("Unable to find instantiation of declaration!");
3424       }
3425     }
3426 
3427     D = Result;
3428   }
3429 
3430   return D;
3431 }
3432 
3433 /// \brief Performs template instantiation for all implicit template
3434 /// instantiations we have seen until this point.
3435 void Sema::PerformPendingInstantiations(bool LocalOnly) {
3436   // Load pending instantiations from the external source.
3437   if (!LocalOnly && ExternalSource) {
3438     SmallVector<std::pair<ValueDecl *, SourceLocation>, 4> Pending;
3439     ExternalSource->ReadPendingInstantiations(Pending);
3440     PendingInstantiations.insert(PendingInstantiations.begin(),
3441                                  Pending.begin(), Pending.end());
3442   }
3443 
3444   while (!PendingLocalImplicitInstantiations.empty() ||
3445          (!LocalOnly && !PendingInstantiations.empty())) {
3446     PendingImplicitInstantiation Inst;
3447 
3448     if (PendingLocalImplicitInstantiations.empty()) {
3449       Inst = PendingInstantiations.front();
3450       PendingInstantiations.pop_front();
3451     } else {
3452       Inst = PendingLocalImplicitInstantiations.front();
3453       PendingLocalImplicitInstantiations.pop_front();
3454     }
3455 
3456     // Instantiate function definitions
3457     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
3458       PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3459                                           "instantiating function definition");
3460       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3461                                 TSK_ExplicitInstantiationDefinition;
3462       InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3463                                     DefinitionRequired);
3464       continue;
3465     }
3466 
3467     // Instantiate static data member definitions.
3468     VarDecl *Var = cast<VarDecl>(Inst.first);
3469     assert(Var->isStaticDataMember() && "Not a static data member?");
3470 
3471     // Don't try to instantiate declarations if the most recent redeclaration
3472     // is invalid.
3473     if (Var->getMostRecentDecl()->isInvalidDecl())
3474       continue;
3475 
3476     // Check if the most recent declaration has changed the specialization kind
3477     // and removed the need for implicit instantiation.
3478     switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
3479     case TSK_Undeclared:
3480       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
3481     case TSK_ExplicitInstantiationDeclaration:
3482     case TSK_ExplicitSpecialization:
3483       continue;  // No longer need to instantiate this type.
3484     case TSK_ExplicitInstantiationDefinition:
3485       // We only need an instantiation if the pending instantiation *is* the
3486       // explicit instantiation.
3487       if (Var != Var->getMostRecentDecl()) continue;
3488     case TSK_ImplicitInstantiation:
3489       break;
3490     }
3491 
3492     PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3493                                         "instantiating static data member "
3494                                         "definition");
3495 
3496     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3497                               TSK_ExplicitInstantiationDefinition;
3498     InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3499                                           DefinitionRequired);
3500   }
3501 }
3502 
3503 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3504                        const MultiLevelTemplateArgumentList &TemplateArgs) {
3505   for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3506          E = Pattern->ddiag_end(); I != E; ++I) {
3507     DependentDiagnostic *DD = *I;
3508 
3509     switch (DD->getKind()) {
3510     case DependentDiagnostic::Access:
3511       HandleDependentAccessCheck(*DD, TemplateArgs);
3512       break;
3513     }
3514   }
3515 }
3516