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