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