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