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