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