SemaTemplateInstantiateDecl.cpp revision 251b4ff2578e26959a4c036140ccd61c5e9292f2
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 "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
17#include "clang/AST/Expr.h"
18#include "clang/Basic/PrettyStackTrace.h"
19#include "clang/Lex/Preprocessor.h"
20#include "llvm/Support/Compiler.h"
21
22using namespace clang;
23
24namespace {
25  class VISIBILITY_HIDDEN TemplateDeclInstantiator
26    : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
27    Sema &SemaRef;
28    DeclContext *Owner;
29    const MultiLevelTemplateArgumentList &TemplateArgs;
30
31  public:
32    typedef Sema::OwningExprResult OwningExprResult;
33
34    TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
35                             const MultiLevelTemplateArgumentList &TemplateArgs)
36      : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
37
38    // FIXME: Once we get closer to completion, replace these manually-written
39    // declarations with automatically-generated ones from
40    // clang/AST/DeclNodes.def.
41    Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
42    Decl *VisitNamespaceDecl(NamespaceDecl *D);
43    Decl *VisitTypedefDecl(TypedefDecl *D);
44    Decl *VisitVarDecl(VarDecl *D);
45    Decl *VisitFieldDecl(FieldDecl *D);
46    Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
47    Decl *VisitEnumDecl(EnumDecl *D);
48    Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
49    Decl *VisitFriendDecl(FriendDecl *D);
50    Decl *VisitFunctionDecl(FunctionDecl *D);
51    Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
52    Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
53                             TemplateParameterList *TemplateParams = 0);
54    Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
55    Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
56    Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
57    ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
58    Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
59    Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
60    Decl *VisitClassTemplatePartialSpecializationDecl(
61                                    ClassTemplatePartialSpecializationDecl *D);
62    Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
63    Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
64    Decl *VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D);
65
66    // Base case. FIXME: Remove once we can instantiate everything.
67    Decl *VisitDecl(Decl *) {
68      assert(false && "Template instantiation of unknown declaration kind!");
69      return 0;
70    }
71
72    const LangOptions &getLangOptions() {
73      return SemaRef.getLangOptions();
74    }
75
76    // Helper functions for instantiating methods.
77    QualType SubstFunctionType(FunctionDecl *D,
78                             llvm::SmallVectorImpl<ParmVarDecl *> &Params);
79    bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
80    bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
81
82    TemplateParameterList *
83      SubstTemplateParams(TemplateParameterList *List);
84  };
85}
86
87Decl *
88TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
89  assert(false && "Translation units cannot be instantiated");
90  return D;
91}
92
93Decl *
94TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
95  assert(false && "Namespaces cannot be instantiated");
96  return D;
97}
98
99Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
100  bool Invalid = false;
101  QualType T = D->getUnderlyingType();
102  if (T->isDependentType()) {
103    T = SemaRef.SubstType(T, TemplateArgs,
104                          D->getLocation(), D->getDeclName());
105    if (T.isNull()) {
106      Invalid = true;
107      T = SemaRef.Context.IntTy;
108    }
109  }
110
111  // Create the new typedef
112  TypedefDecl *Typedef
113    = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
114                          D->getIdentifier(), T);
115  if (Invalid)
116    Typedef->setInvalidDecl();
117
118  Owner->addDecl(Typedef);
119
120  return Typedef;
121}
122
123Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
124  // Do substitution on the type of the declaration
125  QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
126                                 D->getTypeSpecStartLoc(),
127                                 D->getDeclName());
128  if (T.isNull())
129    return 0;
130
131  // Build the instantiated declaration
132  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
133                                 D->getLocation(), D->getIdentifier(),
134                                 T, D->getDeclaratorInfo(),
135                                 D->getStorageClass());
136  Var->setThreadSpecified(D->isThreadSpecified());
137  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
138  Var->setDeclaredInCondition(D->isDeclaredInCondition());
139
140  // If we are instantiating a static data member defined
141  // out-of-line, the instantiation will have the same lexical
142  // context (which will be a namespace scope) as the template.
143  if (D->isOutOfLine())
144    Var->setLexicalDeclContext(D->getLexicalDeclContext());
145
146  // FIXME: In theory, we could have a previous declaration for variables that
147  // are not static data members.
148  bool Redeclaration = false;
149  SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
150
151  if (D->isOutOfLine()) {
152    D->getLexicalDeclContext()->addDecl(Var);
153    Owner->makeDeclVisibleInContext(Var);
154  } else {
155    Owner->addDecl(Var);
156  }
157
158  // Link instantiations of static data members back to the template from
159  // which they were instantiated.
160  if (Var->isStaticDataMember())
161    SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
162                                                        TSK_ImplicitInstantiation);
163
164  if (D->getInit()) {
165    OwningExprResult Init
166      = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
167    if (Init.isInvalid())
168      Var->setInvalidDecl();
169    else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
170      // FIXME: We're faking all of the comma locations, which is suboptimal.
171      // Do we even need these comma locations?
172      llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
173      if (PLE->getNumExprs() > 0) {
174        FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
175        for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
176          Expr *E = PLE->getExpr(I)->Retain();
177          FakeCommaLocs.push_back(
178                                SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
179        }
180        PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
181      }
182
183      // Add the direct initializer to the declaration.
184      SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
185                                            PLE->getLParenLoc(),
186                                            Sema::MultiExprArg(SemaRef,
187                                                       (void**)PLE->getExprs(),
188                                                           PLE->getNumExprs()),
189                                            FakeCommaLocs.data(),
190                                            PLE->getRParenLoc());
191
192      // When Init is destroyed, it will destroy the instantiated ParenListExpr;
193      // we've explicitly retained all of its subexpressions already.
194    } else
195      SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
196                                   D->hasCXXDirectInitializer());
197  } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
198    SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
199
200  return Var;
201}
202
203Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
204  bool Invalid = false;
205  QualType T = D->getType();
206  if (T->isDependentType())  {
207    T = SemaRef.SubstType(T, TemplateArgs,
208                          D->getLocation(), D->getDeclName());
209    if (!T.isNull() && T->isFunctionType()) {
210      // C++ [temp.arg.type]p3:
211      //   If a declaration acquires a function type through a type
212      //   dependent on a template-parameter and this causes a
213      //   declaration that does not use the syntactic form of a
214      //   function declarator to have function type, the program is
215      //   ill-formed.
216      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
217        << T;
218      T = QualType();
219      Invalid = true;
220    }
221  }
222
223  Expr *BitWidth = D->getBitWidth();
224  if (Invalid)
225    BitWidth = 0;
226  else if (BitWidth) {
227    // The bit-width expression is not potentially evaluated.
228    EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
229
230    OwningExprResult InstantiatedBitWidth
231      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
232    if (InstantiatedBitWidth.isInvalid()) {
233      Invalid = true;
234      BitWidth = 0;
235    } else
236      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
237  }
238
239  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
240                                            D->getDeclaratorInfo(),
241                                            cast<RecordDecl>(Owner),
242                                            D->getLocation(),
243                                            D->isMutable(),
244                                            BitWidth,
245                                            D->getTypeSpecStartLoc(),
246                                            D->getAccess(),
247                                            0);
248  if (!Field)
249    return 0;
250
251  if (Invalid)
252    Field->setInvalidDecl();
253
254  if (!Field->getDeclName()) {
255    // Keep track of where this decl came from.
256    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
257  }
258
259  Field->setImplicit(D->isImplicit());
260  Owner->addDecl(Field);
261
262  return Field;
263}
264
265Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
266  FriendDecl::FriendUnion FU;
267
268  // Handle friend type expressions by simply substituting template
269  // parameters into the pattern type.
270  if (Type *Ty = D->getFriendType()) {
271    QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
272                                   D->getLocation(), DeclarationName());
273    if (T.isNull()) return 0;
274
275    assert(getLangOptions().CPlusPlus0x || T->isRecordType());
276    FU = T.getTypePtr();
277
278  // Handle everything else by appropriate substitution.
279  } else {
280    NamedDecl *ND = D->getFriendDecl();
281    assert(ND && "friend decl must be a decl or a type!");
282
283    Decl *NewND = Visit(ND);
284    if (!NewND) return 0;
285
286    FU = cast<NamedDecl>(NewND);
287  }
288
289  FriendDecl *FD =
290    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
291                       D->getFriendLoc());
292  FD->setAccess(AS_public);
293  Owner->addDecl(FD);
294  return FD;
295}
296
297Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
298  Expr *AssertExpr = D->getAssertExpr();
299
300  // The expression in a static assertion is not potentially evaluated.
301  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
302
303  OwningExprResult InstantiatedAssertExpr
304    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
305  if (InstantiatedAssertExpr.isInvalid())
306    return 0;
307
308  OwningExprResult Message(SemaRef, D->getMessage());
309  D->getMessage()->Retain();
310  Decl *StaticAssert
311    = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
312                                           move(InstantiatedAssertExpr),
313                                           move(Message)).getAs<Decl>();
314  return StaticAssert;
315}
316
317Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
318  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
319                                    D->getLocation(), D->getIdentifier(),
320                                    D->getTagKeywordLoc(),
321                                    /*PrevDecl=*/0);
322  Enum->setInstantiationOfMemberEnum(D);
323  Enum->setAccess(D->getAccess());
324  Owner->addDecl(Enum);
325  Enum->startDefinition();
326
327  llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
328
329  EnumConstantDecl *LastEnumConst = 0;
330  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
331         ECEnd = D->enumerator_end();
332       EC != ECEnd; ++EC) {
333    // The specified value for the enumerator.
334    OwningExprResult Value = SemaRef.Owned((Expr *)0);
335    if (Expr *UninstValue = EC->getInitExpr()) {
336      // The enumerator's value expression is not potentially evaluated.
337      EnterExpressionEvaluationContext Unevaluated(SemaRef,
338                                                   Action::Unevaluated);
339
340      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
341    }
342
343    // Drop the initial value and continue.
344    bool isInvalid = false;
345    if (Value.isInvalid()) {
346      Value = SemaRef.Owned((Expr *)0);
347      isInvalid = true;
348    }
349
350    EnumConstantDecl *EnumConst
351      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
352                                  EC->getLocation(), EC->getIdentifier(),
353                                  move(Value));
354
355    if (isInvalid) {
356      if (EnumConst)
357        EnumConst->setInvalidDecl();
358      Enum->setInvalidDecl();
359    }
360
361    if (EnumConst) {
362      Enum->addDecl(EnumConst);
363      Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
364      LastEnumConst = EnumConst;
365    }
366  }
367
368  // FIXME: Fixup LBraceLoc and RBraceLoc
369  // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
370  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
371                        Sema::DeclPtrTy::make(Enum),
372                        &Enumerators[0], Enumerators.size(),
373                        0, 0);
374
375  return Enum;
376}
377
378Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
379  assert(false && "EnumConstantDecls can only occur within EnumDecls.");
380  return 0;
381}
382
383Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
384  TemplateParameterList *TempParams = D->getTemplateParameters();
385  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
386  if (!InstParams)
387    return NULL;
388
389  CXXRecordDecl *Pattern = D->getTemplatedDecl();
390  CXXRecordDecl *RecordInst
391    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
392                            Pattern->getLocation(), Pattern->getIdentifier(),
393                            Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
394
395  ClassTemplateDecl *Inst
396    = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
397                                D->getIdentifier(), InstParams, RecordInst, 0);
398  RecordInst->setDescribedClassTemplate(Inst);
399  Inst->setAccess(D->getAccess());
400  Inst->setInstantiatedFromMemberTemplate(D);
401
402  Owner->addDecl(Inst);
403  return Inst;
404}
405
406Decl *
407TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
408                                   ClassTemplatePartialSpecializationDecl *D) {
409  assert(false &&"Partial specializations of member templates are unsupported");
410  return 0;
411}
412
413Decl *
414TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
415  // FIXME: Dig out the out-of-line definition of this function template?
416
417  TemplateParameterList *TempParams = D->getTemplateParameters();
418  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
419  if (!InstParams)
420    return NULL;
421
422  // FIXME: Handle instantiation of nested function templates that aren't
423  // member function templates. This could happen inside a FriendDecl.
424  assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
425  CXXMethodDecl *InstMethod
426    = cast_or_null<CXXMethodDecl>(
427                 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
428                                    InstParams));
429  if (!InstMethod)
430    return 0;
431
432  // Link the instantiated function template declaration to the function
433  // template from which it was instantiated.
434  FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
435  assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
436  InstTemplate->setInstantiatedFromMemberTemplate(D);
437  Owner->addDecl(InstTemplate);
438  return InstTemplate;
439}
440
441Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
442  CXXRecordDecl *PrevDecl = 0;
443  if (D->isInjectedClassName())
444    PrevDecl = cast<CXXRecordDecl>(Owner);
445
446  CXXRecordDecl *Record
447    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
448                            D->getLocation(), D->getIdentifier(),
449                            D->getTagKeywordLoc(), PrevDecl);
450  Record->setImplicit(D->isImplicit());
451  // FIXME: Check against AS_none is an ugly hack to work around the issue that
452  // the tag decls introduced by friend class declarations don't have an access
453  // specifier. Remove once this area of the code gets sorted out.
454  if (D->getAccess() != AS_none)
455    Record->setAccess(D->getAccess());
456  if (!D->isInjectedClassName())
457    Record->setInstantiationOfMemberClass(D);
458
459  // If the original function was part of a friend declaration,
460  // inherit its namespace state.
461  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
462    Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
463
464  Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
465
466  Owner->addDecl(Record);
467  return Record;
468}
469
470/// Normal class members are of more specific types and therefore
471/// don't make it here.  This function serves two purposes:
472///   1) instantiating function templates
473///   2) substituting friend declarations
474/// FIXME: preserve function definitions in case #2
475Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
476  // Check whether there is already a function template specialization for
477  // this declaration.
478  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
479  void *InsertPos = 0;
480  if (FunctionTemplate) {
481    llvm::FoldingSetNodeID ID;
482    FunctionTemplateSpecializationInfo::Profile(ID,
483                             TemplateArgs.getInnermost().getFlatArgumentList(),
484                                       TemplateArgs.getInnermost().flat_size(),
485                                                SemaRef.Context);
486
487    FunctionTemplateSpecializationInfo *Info
488      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
489                                                                   InsertPos);
490
491    // If we already have a function template specialization, return it.
492    if (Info)
493      return Info->Function;
494  }
495
496  Sema::LocalInstantiationScope Scope(SemaRef);
497
498  llvm::SmallVector<ParmVarDecl *, 4> Params;
499  QualType T = SubstFunctionType(D, Params);
500  if (T.isNull())
501    return 0;
502
503  // Build the instantiated method declaration.
504  DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
505                                                    TemplateArgs);
506  FunctionDecl *Function =
507      FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
508                           D->getDeclName(), T, D->getDeclaratorInfo(),
509                           D->getStorageClass(),
510                           D->isInline(), D->hasWrittenPrototype());
511  Function->setLexicalDeclContext(Owner);
512
513  // Attach the parameters
514  for (unsigned P = 0; P < Params.size(); ++P)
515    Params[P]->setOwningFunction(Function);
516  Function->setParams(SemaRef.Context, Params.data(), Params.size());
517
518  // If the original function was part of a friend declaration,
519  // inherit its namespace state and add it to the owner.
520  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) {
521    bool WasDeclared = (FOK == Decl::FOK_Declared);
522    Function->setObjectOfFriendDecl(WasDeclared);
523    if (!Owner->isDependentContext())
524      DC->makeDeclVisibleInContext(Function, /* Recoverable = */ false);
525
526    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
527  }
528
529  if (InitFunctionInstantiation(Function, D))
530    Function->setInvalidDecl();
531
532  bool Redeclaration = false;
533  bool OverloadableAttrRequired = false;
534  NamedDecl *PrevDecl = 0;
535  SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
536                                   /*FIXME:*/OverloadableAttrRequired);
537
538  if (FunctionTemplate) {
539    // Record this function template specialization.
540    Function->setFunctionTemplateSpecialization(SemaRef.Context,
541                                                FunctionTemplate,
542                                                &TemplateArgs.getInnermost(),
543                                                InsertPos);
544  }
545
546  return Function;
547}
548
549Decl *
550TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
551                                      TemplateParameterList *TemplateParams) {
552  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
553  void *InsertPos = 0;
554  if (FunctionTemplate && !TemplateParams) {
555    // We are creating a function template specialization from a function
556    // template. Check whether there is already a function template
557    // specialization for this particular set of template arguments.
558    llvm::FoldingSetNodeID ID;
559    FunctionTemplateSpecializationInfo::Profile(ID,
560                            TemplateArgs.getInnermost().getFlatArgumentList(),
561                                      TemplateArgs.getInnermost().flat_size(),
562                                                SemaRef.Context);
563
564    FunctionTemplateSpecializationInfo *Info
565      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
566                                                                   InsertPos);
567
568    // If we already have a function template specialization, return it.
569    if (Info)
570      return Info->Function;
571  }
572
573  Sema::LocalInstantiationScope Scope(SemaRef);
574
575  llvm::SmallVector<ParmVarDecl *, 4> Params;
576  QualType T = SubstFunctionType(D, Params);
577  if (T.isNull())
578    return 0;
579
580  // Build the instantiated method declaration.
581  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
582  CXXMethodDecl *Method = 0;
583
584  DeclarationName Name = D->getDeclName();
585  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
586    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
587    Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
588                                    SemaRef.Context.getCanonicalType(ClassTy));
589    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
590                                        Constructor->getLocation(),
591                                        Name, T,
592                                        Constructor->getDeclaratorInfo(),
593                                        Constructor->isExplicit(),
594                                        Constructor->isInline(), false);
595  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
596    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
597    Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
598                                   SemaRef.Context.getCanonicalType(ClassTy));
599    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
600                                       Destructor->getLocation(), Name,
601                                       T, Destructor->isInline(), false);
602  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
603    CanQualType ConvTy
604      = SemaRef.Context.getCanonicalType(
605                                      T->getAs<FunctionType>()->getResultType());
606    Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
607                                                                      ConvTy);
608    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
609                                       Conversion->getLocation(), Name,
610                                       T, Conversion->getDeclaratorInfo(),
611                                       Conversion->isInline(),
612                                       Conversion->isExplicit());
613  } else {
614    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
615                                   D->getDeclName(), T, D->getDeclaratorInfo(),
616                                   D->isStatic(), D->isInline());
617  }
618
619  if (TemplateParams) {
620    // Our resulting instantiation is actually a function template, since we
621    // are substituting only the outer template parameters. For example, given
622    //
623    //   template<typename T>
624    //   struct X {
625    //     template<typename U> void f(T, U);
626    //   };
627    //
628    //   X<int> x;
629    //
630    // We are instantiating the member template "f" within X<int>, which means
631    // substituting int for T, but leaving "f" as a member function template.
632    // Build the function template itself.
633    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
634                                                    Method->getLocation(),
635                                                    Method->getDeclName(),
636                                                    TemplateParams, Method);
637    if (D->isOutOfLine())
638      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
639    Method->setDescribedFunctionTemplate(FunctionTemplate);
640  } else if (!FunctionTemplate)
641    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
642
643  // If we are instantiating a member function defined
644  // out-of-line, the instantiation will have the same lexical
645  // context (which will be a namespace scope) as the template.
646  if (D->isOutOfLine())
647    Method->setLexicalDeclContext(D->getLexicalDeclContext());
648
649  // Attach the parameters
650  for (unsigned P = 0; P < Params.size(); ++P)
651    Params[P]->setOwningFunction(Method);
652  Method->setParams(SemaRef.Context, Params.data(), Params.size());
653
654  if (InitMethodInstantiation(Method, D))
655    Method->setInvalidDecl();
656
657  NamedDecl *PrevDecl = 0;
658
659  if (!FunctionTemplate || TemplateParams) {
660    PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
661                                           Sema::LookupOrdinaryName, true);
662
663    // In C++, the previous declaration we find might be a tag type
664    // (class or enum). In this case, the new declaration will hide the
665    // tag type. Note that this does does not apply if we're declaring a
666    // typedef (C++ [dcl.typedef]p4).
667    if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
668      PrevDecl = 0;
669  }
670
671  if (FunctionTemplate && !TemplateParams)
672    // Record this function template specialization.
673    Method->setFunctionTemplateSpecialization(SemaRef.Context,
674                                              FunctionTemplate,
675                                              &TemplateArgs.getInnermost(),
676                                              InsertPos);
677
678  bool Redeclaration = false;
679  bool OverloadableAttrRequired = false;
680  SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
681                                   /*FIXME:*/OverloadableAttrRequired);
682
683  if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
684    Owner->addDecl(Method);
685
686  return Method;
687}
688
689Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
690  return VisitCXXMethodDecl(D);
691}
692
693Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
694  return VisitCXXMethodDecl(D);
695}
696
697Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
698  return VisitCXXMethodDecl(D);
699}
700
701ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
702  QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
703                                           D->getLocation(), D->getDeclName());
704  if (OrigT.isNull())
705    return 0;
706
707  QualType T = SemaRef.adjustParameterType(OrigT);
708
709  // Allocate the parameter
710  ParmVarDecl *Param = 0;
711  if (T == OrigT)
712    Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
713                                D->getIdentifier(), T, D->getDeclaratorInfo(),
714                                D->getStorageClass(), 0);
715  else
716    Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
717                                        D->getLocation(), D->getIdentifier(),
718                                        T, D->getDeclaratorInfo(), OrigT,
719                                        D->getStorageClass(), 0);
720
721  // Mark the default argument as being uninstantiated.
722  if (D->hasUninstantiatedDefaultArg())
723    Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
724  else if (Expr *Arg = D->getDefaultArg())
725    Param->setUninstantiatedDefaultArg(Arg);
726
727  // Note: we don't try to instantiate function parameters until after
728  // we've instantiated the function's type. Therefore, we don't have
729  // to check for 'void' parameter types here.
730  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
731  return Param;
732}
733
734Decl *
735TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
736  // Since parameter types can decay either before or after
737  // instantiation, we simply treat OriginalParmVarDecls as
738  // ParmVarDecls the same way, and create one or the other depending
739  // on what happens after template instantiation.
740  return VisitParmVarDecl(D);
741}
742
743Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
744                                                    TemplateTypeParmDecl *D) {
745  // TODO: don't always clone when decls are refcounted.
746  const Type* T = D->getTypeForDecl();
747  assert(T->isTemplateTypeParmType());
748  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
749
750  TemplateTypeParmDecl *Inst =
751    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
752                                 TTPT->getDepth(), TTPT->getIndex(),
753                                 TTPT->getName(),
754                                 D->wasDeclaredWithTypename(),
755                                 D->isParameterPack());
756
757  if (D->hasDefaultArgument()) {
758    QualType DefaultPattern = D->getDefaultArgument();
759    QualType DefaultInst
760      = SemaRef.SubstType(DefaultPattern, TemplateArgs,
761                          D->getDefaultArgumentLoc(),
762                          D->getDeclName());
763
764    Inst->setDefaultArgument(DefaultInst,
765                             D->getDefaultArgumentLoc(),
766                             D->defaultArgumentWasInherited() /* preserve? */);
767  }
768
769  return Inst;
770}
771
772Decl *
773TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
774  NestedNameSpecifier *NNS =
775    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
776                                     D->getTargetNestedNameRange(),
777                                     TemplateArgs);
778  if (!NNS)
779    return 0;
780
781  CXXScopeSpec SS;
782  SS.setRange(D->getTargetNestedNameRange());
783  SS.setScopeRep(NNS);
784
785  NamedDecl *UD =
786    SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
787                                  D->getTargetNameLocation(),
788                                  D->getTargetName(), 0, D->isTypeName());
789  if (UD)
790    SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
791                                                           D);
792  return UD;
793}
794
795Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
796                      const MultiLevelTemplateArgumentList &TemplateArgs) {
797  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
798  return Instantiator.Visit(D);
799}
800
801/// \brief Instantiates a nested template parameter list in the current
802/// instantiation context.
803///
804/// \param L The parameter list to instantiate
805///
806/// \returns NULL if there was an error
807TemplateParameterList *
808TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
809  // Get errors for all the parameters before bailing out.
810  bool Invalid = false;
811
812  unsigned N = L->size();
813  typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
814  ParamVector Params;
815  Params.reserve(N);
816  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
817       PI != PE; ++PI) {
818    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
819    Params.push_back(D);
820    Invalid = Invalid || !D;
821  }
822
823  // Clean up if we had an error.
824  if (Invalid) {
825    for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
826         PI != PE; ++PI)
827      if (*PI)
828        (*PI)->Destroy(SemaRef.Context);
829    return NULL;
830  }
831
832  TemplateParameterList *InstL
833    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
834                                    L->getLAngleLoc(), &Params.front(), N,
835                                    L->getRAngleLoc());
836  return InstL;
837}
838
839/// \brief Does substitution on the type of the given function, including
840/// all of the function parameters.
841///
842/// \param D The function whose type will be the basis of the substitution
843///
844/// \param Params the instantiated parameter declarations
845
846/// \returns the instantiated function's type if successful, a NULL
847/// type if there was an error.
848QualType
849TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
850                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
851  bool InvalidDecl = false;
852
853  // Substitute all of the function's formal parameter types.
854  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
855  llvm::SmallVector<QualType, 4> ParamTys;
856  for (FunctionDecl::param_iterator P = D->param_begin(),
857                                 PEnd = D->param_end();
858       P != PEnd; ++P) {
859    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
860      if (PInst->getType()->isVoidType()) {
861        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
862        PInst->setInvalidDecl();
863      } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
864                                                PInst->getType(),
865                                                diag::err_abstract_type_in_decl,
866                                                Sema::AbstractParamType))
867        PInst->setInvalidDecl();
868
869      Params.push_back(PInst);
870      ParamTys.push_back(PInst->getType());
871
872      if (PInst->isInvalidDecl())
873        InvalidDecl = true;
874    } else
875      InvalidDecl = true;
876  }
877
878  // FIXME: Deallocate dead declarations.
879  if (InvalidDecl)
880    return QualType();
881
882  const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
883  assert(Proto && "Missing prototype?");
884  QualType ResultType
885    = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
886                        D->getLocation(), D->getDeclName());
887  if (ResultType.isNull())
888    return QualType();
889
890  return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
891                                   Proto->isVariadic(), Proto->getTypeQuals(),
892                                   D->getLocation(), D->getDeclName());
893}
894
895/// \brief Initializes the common fields of an instantiation function
896/// declaration (New) from the corresponding fields of its template (Tmpl).
897///
898/// \returns true if there was an error
899bool
900TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
901                                                    FunctionDecl *Tmpl) {
902  if (Tmpl->isDeleted())
903    New->setDeleted();
904
905  // If we are performing substituting explicitly-specified template arguments
906  // or deduced template arguments into a function template and we reach this
907  // point, we are now past the point where SFINAE applies and have committed
908  // to keeping the new function template specialization. We therefore
909  // convert the active template instantiation for the function template
910  // into a template instantiation for this specific function template
911  // specialization, which is not a SFINAE context, so that we diagnose any
912  // further errors in the declaration itself.
913  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
914  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
915  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
916      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
917    if (FunctionTemplateDecl *FunTmpl
918          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
919      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
920             "Deduction from the wrong function template?");
921      (void) FunTmpl;
922      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
923      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
924    }
925  }
926
927  return false;
928}
929
930/// \brief Initializes common fields of an instantiated method
931/// declaration (New) from the corresponding fields of its template
932/// (Tmpl).
933///
934/// \returns true if there was an error
935bool
936TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
937                                                  CXXMethodDecl *Tmpl) {
938  if (InitFunctionInstantiation(New, Tmpl))
939    return true;
940
941  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
942  New->setAccess(Tmpl->getAccess());
943  if (Tmpl->isVirtualAsWritten()) {
944    New->setVirtualAsWritten(true);
945    Record->setAggregate(false);
946    Record->setPOD(false);
947    Record->setEmpty(false);
948    Record->setPolymorphic(true);
949  }
950  if (Tmpl->isPure()) {
951    New->setPure();
952    Record->setAbstract(true);
953  }
954
955  // FIXME: attributes
956  // FIXME: New needs a pointer to Tmpl
957  return false;
958}
959
960/// \brief Instantiate the definition of the given function from its
961/// template.
962///
963/// \param PointOfInstantiation the point at which the instantiation was
964/// required. Note that this is not precisely a "point of instantiation"
965/// for the function, but it's close.
966///
967/// \param Function the already-instantiated declaration of a
968/// function template specialization or member function of a class template
969/// specialization.
970///
971/// \param Recursive if true, recursively instantiates any functions that
972/// are required by this instantiation.
973void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
974                                         FunctionDecl *Function,
975                                         bool Recursive) {
976  if (Function->isInvalidDecl())
977    return;
978
979  assert(!Function->getBody() && "Already instantiated!");
980
981  // Never instantiate an explicit specialization.
982  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
983    return;
984
985  // Find the function body that we'll be substituting.
986  const FunctionDecl *PatternDecl = 0;
987  if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
988    while (Primary->getInstantiatedFromMemberTemplate())
989      Primary = Primary->getInstantiatedFromMemberTemplate();
990
991    PatternDecl = Primary->getTemplatedDecl();
992  } else
993    PatternDecl = Function->getInstantiatedFromMemberFunction();
994  Stmt *Pattern = 0;
995  if (PatternDecl)
996    Pattern = PatternDecl->getBody(PatternDecl);
997
998  if (!Pattern)
999    return;
1000
1001  // C++0x [temp.explicit]p9:
1002  //   Except for inline functions, other explicit instantiation declarations
1003  //   have the effect of suppressing the implicit instantiation of the entity
1004  //   to which they refer.
1005  if (Function->getTemplateSpecializationKind()
1006        == TSK_ExplicitInstantiationDeclaration &&
1007      PatternDecl->isOutOfLine() && !PatternDecl->isInline())
1008    return;
1009
1010  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1011  if (Inst)
1012    return;
1013
1014  // If we're performing recursive template instantiation, create our own
1015  // queue of pending implicit instantiations that we will instantiate later,
1016  // while we're still within our own instantiation context.
1017  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1018  if (Recursive)
1019    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1020
1021  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1022
1023  // Introduce a new scope where local variable instantiations will be
1024  // recorded.
1025  LocalInstantiationScope Scope(*this);
1026
1027  // Introduce the instantiated function parameters into the local
1028  // instantiation scope.
1029  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1030    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1031                            Function->getParamDecl(I));
1032
1033  // Enter the scope of this instantiation. We don't use
1034  // PushDeclContext because we don't have a scope.
1035  DeclContext *PreviousContext = CurContext;
1036  CurContext = Function;
1037
1038  MultiLevelTemplateArgumentList TemplateArgs =
1039    getTemplateInstantiationArgs(Function);
1040
1041  // If this is a constructor, instantiate the member initializers.
1042  if (const CXXConstructorDecl *Ctor =
1043        dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1044    InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1045                               TemplateArgs);
1046  }
1047
1048  // Instantiate the function body.
1049  OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
1050
1051  if (Body.isInvalid())
1052    Function->setInvalidDecl();
1053
1054  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1055                          /*IsInstantiation=*/true);
1056
1057  CurContext = PreviousContext;
1058
1059  DeclGroupRef DG(Function);
1060  Consumer.HandleTopLevelDecl(DG);
1061
1062  if (Recursive) {
1063    // Instantiate any pending implicit instantiations found during the
1064    // instantiation of this template.
1065    PerformPendingImplicitInstantiations();
1066
1067    // Restore the set of pending implicit instantiations.
1068    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1069  }
1070}
1071
1072/// \brief Instantiate the definition of the given variable from its
1073/// template.
1074///
1075/// \param PointOfInstantiation the point at which the instantiation was
1076/// required. Note that this is not precisely a "point of instantiation"
1077/// for the function, but it's close.
1078///
1079/// \param Var the already-instantiated declaration of a static member
1080/// variable of a class template specialization.
1081///
1082/// \param Recursive if true, recursively instantiates any functions that
1083/// are required by this instantiation.
1084void Sema::InstantiateStaticDataMemberDefinition(
1085                                          SourceLocation PointOfInstantiation,
1086                                                 VarDecl *Var,
1087                                                 bool Recursive) {
1088  if (Var->isInvalidDecl())
1089    return;
1090
1091  // Find the out-of-line definition of this static data member.
1092  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1093  bool FoundOutOfLineDef = false;
1094  assert(Def && "This data member was not instantiated from a template?");
1095  assert(Def->isStaticDataMember() && "Not a static data member?");
1096  for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1097                             RDEnd = Def->redecls_end();
1098       RD != RDEnd; ++RD) {
1099    if (RD->getLexicalDeclContext()->isFileContext()) {
1100      Def = *RD;
1101      FoundOutOfLineDef = true;
1102    }
1103  }
1104
1105  if (!FoundOutOfLineDef) {
1106    // We did not find an out-of-line definition of this static data member,
1107    // so we won't perform any instantiation. Rather, we rely on the user to
1108    // instantiate this definition (or provide a specialization for it) in
1109    // another translation unit.
1110    return;
1111  }
1112
1113  // Never instantiate an explicit specialization.
1114  if (Def->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1115    return;
1116
1117  // C++0x [temp.explicit]p9:
1118  //   Except for inline functions, other explicit instantiation declarations
1119  //   have the effect of suppressing the implicit instantiation of the entity
1120  //   to which they refer.
1121  if (Def->getTemplateSpecializationKind()
1122        == TSK_ExplicitInstantiationDeclaration)
1123    return;
1124
1125  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1126  if (Inst)
1127    return;
1128
1129  // If we're performing recursive template instantiation, create our own
1130  // queue of pending implicit instantiations that we will instantiate later,
1131  // while we're still within our own instantiation context.
1132  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1133  if (Recursive)
1134    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1135
1136  // Enter the scope of this instantiation. We don't use
1137  // PushDeclContext because we don't have a scope.
1138  DeclContext *PreviousContext = CurContext;
1139  CurContext = Var->getDeclContext();
1140
1141  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
1142                                          getTemplateInstantiationArgs(Var)));
1143
1144  CurContext = PreviousContext;
1145
1146  if (Var) {
1147    DeclGroupRef DG(Var);
1148    Consumer.HandleTopLevelDecl(DG);
1149  }
1150
1151  if (Recursive) {
1152    // Instantiate any pending implicit instantiations found during the
1153    // instantiation of this template.
1154    PerformPendingImplicitInstantiations();
1155
1156    // Restore the set of pending implicit instantiations.
1157    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1158  }
1159}
1160
1161void
1162Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1163                                 const CXXConstructorDecl *Tmpl,
1164                           const MultiLevelTemplateArgumentList &TemplateArgs) {
1165
1166  llvm::SmallVector<MemInitTy*, 4> NewInits;
1167
1168  // Instantiate all the initializers.
1169  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1170                                            InitsEnd = Tmpl->init_end();
1171       Inits != InitsEnd; ++Inits) {
1172    CXXBaseOrMemberInitializer *Init = *Inits;
1173
1174    ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1175
1176    // Instantiate all the arguments.
1177    for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1178         Args != ArgsEnd; ++Args) {
1179      OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1180
1181      if (NewArg.isInvalid())
1182        New->setInvalidDecl();
1183      else
1184        NewArgs.push_back(NewArg.takeAs<Expr>());
1185    }
1186
1187    MemInitResult NewInit;
1188
1189    if (Init->isBaseInitializer()) {
1190      QualType BaseType(Init->getBaseClass(), 0);
1191      BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1192                           New->getDeclName());
1193
1194      NewInit = BuildBaseInitializer(BaseType,
1195                                     (Expr **)NewArgs.data(),
1196                                     NewArgs.size(),
1197                                     Init->getSourceLocation(),
1198                                     Init->getRParenLoc(),
1199                                     New->getParent());
1200    } else if (Init->isMemberInitializer()) {
1201      FieldDecl *Member;
1202
1203      // Is this an anonymous union?
1204      if (FieldDecl *UnionInit = Init->getAnonUnionMember())
1205        Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
1206      else
1207        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1208                                                      TemplateArgs));
1209
1210      NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1211                                       NewArgs.size(),
1212                                       Init->getSourceLocation(),
1213                                       Init->getRParenLoc());
1214    }
1215
1216    if (NewInit.isInvalid())
1217      New->setInvalidDecl();
1218    else {
1219      // FIXME: It would be nice if ASTOwningVector had a release function.
1220      NewArgs.take();
1221
1222      NewInits.push_back((MemInitTy *)NewInit.get());
1223    }
1224  }
1225
1226  // Assign all the initializers to the new constructor.
1227  ActOnMemInitializers(DeclPtrTy::make(New),
1228                       /*FIXME: ColonLoc */
1229                       SourceLocation(),
1230                       NewInits.data(), NewInits.size());
1231}
1232
1233// TODO: this could be templated if the various decl types used the
1234// same method name.
1235static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1236                              ClassTemplateDecl *Instance) {
1237  Pattern = Pattern->getCanonicalDecl();
1238
1239  do {
1240    Instance = Instance->getCanonicalDecl();
1241    if (Pattern == Instance) return true;
1242    Instance = Instance->getInstantiatedFromMemberTemplate();
1243  } while (Instance);
1244
1245  return false;
1246}
1247
1248static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1249                              FunctionTemplateDecl *Instance) {
1250  Pattern = Pattern->getCanonicalDecl();
1251
1252  do {
1253    Instance = Instance->getCanonicalDecl();
1254    if (Pattern == Instance) return true;
1255    Instance = Instance->getInstantiatedFromMemberTemplate();
1256  } while (Instance);
1257
1258  return false;
1259}
1260
1261static bool isInstantiationOf(CXXRecordDecl *Pattern,
1262                              CXXRecordDecl *Instance) {
1263  Pattern = Pattern->getCanonicalDecl();
1264
1265  do {
1266    Instance = Instance->getCanonicalDecl();
1267    if (Pattern == Instance) return true;
1268    Instance = Instance->getInstantiatedFromMemberClass();
1269  } while (Instance);
1270
1271  return false;
1272}
1273
1274static bool isInstantiationOf(FunctionDecl *Pattern,
1275                              FunctionDecl *Instance) {
1276  Pattern = Pattern->getCanonicalDecl();
1277
1278  do {
1279    Instance = Instance->getCanonicalDecl();
1280    if (Pattern == Instance) return true;
1281    Instance = Instance->getInstantiatedFromMemberFunction();
1282  } while (Instance);
1283
1284  return false;
1285}
1286
1287static bool isInstantiationOf(EnumDecl *Pattern,
1288                              EnumDecl *Instance) {
1289  Pattern = Pattern->getCanonicalDecl();
1290
1291  do {
1292    Instance = Instance->getCanonicalDecl();
1293    if (Pattern == Instance) return true;
1294    Instance = Instance->getInstantiatedFromMemberEnum();
1295  } while (Instance);
1296
1297  return false;
1298}
1299
1300static bool isInstantiationOf(UnresolvedUsingDecl *Pattern,
1301                              UsingDecl *Instance,
1302                              ASTContext &C) {
1303  return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1304}
1305
1306static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1307                                              VarDecl *Instance) {
1308  assert(Instance->isStaticDataMember());
1309
1310  Pattern = Pattern->getCanonicalDecl();
1311
1312  do {
1313    Instance = Instance->getCanonicalDecl();
1314    if (Pattern == Instance) return true;
1315    Instance = Instance->getInstantiatedFromStaticDataMember();
1316  } while (Instance);
1317
1318  return false;
1319}
1320
1321static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1322  if (D->getKind() != Other->getKind()) {
1323    if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) {
1324      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1325        return isInstantiationOf(UUD, UD, Ctx);
1326      }
1327    }
1328
1329    return false;
1330  }
1331
1332  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1333    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
1334
1335  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1336    return isInstantiationOf(cast<FunctionDecl>(D), Function);
1337
1338  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1339    return isInstantiationOf(cast<EnumDecl>(D), Enum);
1340
1341  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1342    if (Var->isStaticDataMember())
1343      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1344
1345  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1346    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
1347
1348  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
1349    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
1350
1351  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1352    if (!Field->getDeclName()) {
1353      // This is an unnamed field.
1354      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
1355        cast<FieldDecl>(D);
1356    }
1357  }
1358
1359  return D->getDeclName() && isa<NamedDecl>(Other) &&
1360    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1361}
1362
1363template<typename ForwardIterator>
1364static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1365                                      NamedDecl *D,
1366                                      ForwardIterator first,
1367                                      ForwardIterator last) {
1368  for (; first != last; ++first)
1369    if (isInstantiationOf(Ctx, D, *first))
1370      return cast<NamedDecl>(*first);
1371
1372  return 0;
1373}
1374
1375/// \brief Finds the instantiation of the given declaration context
1376/// within the current instantiation.
1377///
1378/// \returns NULL if there was an error
1379DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1380                          const MultiLevelTemplateArgumentList &TemplateArgs) {
1381  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1382    Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
1383    return cast_or_null<DeclContext>(ID);
1384  } else return DC;
1385}
1386
1387/// \brief Find the instantiation of the given declaration within the
1388/// current instantiation.
1389///
1390/// This routine is intended to be used when \p D is a declaration
1391/// referenced from within a template, that needs to mapped into the
1392/// corresponding declaration within an instantiation. For example,
1393/// given:
1394///
1395/// \code
1396/// template<typename T>
1397/// struct X {
1398///   enum Kind {
1399///     KnownValue = sizeof(T)
1400///   };
1401///
1402///   bool getKind() const { return KnownValue; }
1403/// };
1404///
1405/// template struct X<int>;
1406/// \endcode
1407///
1408/// In the instantiation of X<int>::getKind(), we need to map the
1409/// EnumConstantDecl for KnownValue (which refers to
1410/// X<T>::<Kind>::KnownValue) to its instantiation
1411/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1412/// this mapping from within the instantiation of X<int>.
1413NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1414                          const MultiLevelTemplateArgumentList &TemplateArgs) {
1415  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1416    // Transform all of the elements of the overloaded function set.
1417    OverloadedFunctionDecl *Result
1418      = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
1419
1420    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1421                                                FEnd = Ovl->function_end();
1422         F != FEnd; ++F) {
1423      Result->addOverload(
1424        AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F,
1425                                                               TemplateArgs)));
1426    }
1427
1428    return Result;
1429  }
1430
1431  DeclContext *ParentDC = D->getDeclContext();
1432  if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1433    // D is a local of some kind. Look into the map of local
1434    // declarations to their instantiations.
1435    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1436  }
1437
1438  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1439    if (!Record->isDependentContext())
1440      return D;
1441
1442    // If the RecordDecl is actually the injected-class-name or a "templated"
1443    // declaration for a class template or class template partial
1444    // specialization, substitute into the injected-class-name of the
1445    // class template or partial specialization to find the new DeclContext.
1446    QualType T;
1447    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1448
1449    if (ClassTemplate) {
1450      T = ClassTemplate->getInjectedClassNameType(Context);
1451    } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1452                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1453      T = Context.getTypeDeclType(Record);
1454      ClassTemplate = PartialSpec->getSpecializedTemplate();
1455    }
1456
1457    if (!T.isNull()) {
1458      // Substitute into the injected-class-name to get the type corresponding
1459      // to the instantiation we want. This substitution should never fail,
1460      // since we know we can instantiate the injected-class-name or we wouldn't
1461      // have gotten to the injected-class-name!
1462      // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1463      // instantiation in the common case?
1464      T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1465      assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1466
1467      if (!T->isDependentType()) {
1468        assert(T->isRecordType() && "Instantiation must produce a record type");
1469        return T->getAs<RecordType>()->getDecl();
1470      }
1471
1472      // We are performing "partial" template instantiation to create the
1473      // member declarations for the members of a class template
1474      // specialization. Therefore, D is actually referring to something in
1475      // the current instantiation. Look through the current context,
1476      // which contains actual instantiations, to find the instantiation of
1477      // the "current instantiation" that D refers to.
1478      for (DeclContext *DC = CurContext; !DC->isFileContext();
1479           DC = DC->getParent()) {
1480        if (ClassTemplateSpecializationDecl *Spec
1481              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1482          if (isInstantiationOf(ClassTemplate,
1483                                Spec->getSpecializedTemplate()))
1484            return Spec;
1485      }
1486
1487      assert(false &&
1488             "Unable to find declaration for the current instantiation");
1489      return Record;
1490    }
1491
1492    // Fall through to deal with other dependent record types (e.g.,
1493    // anonymous unions in class templates).
1494  }
1495
1496  if (!ParentDC->isDependentContext())
1497    return D;
1498
1499  ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
1500  if (!ParentDC)
1501    return 0;
1502
1503  if (ParentDC != D->getDeclContext()) {
1504    // We performed some kind of instantiation in the parent context,
1505    // so now we need to look into the instantiated parent context to
1506    // find the instantiation of the declaration D.
1507    NamedDecl *Result = 0;
1508    if (D->getDeclName()) {
1509      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
1510      Result = findInstantiationOf(Context, D, Found.first, Found.second);
1511    } else {
1512      // Since we don't have a name for the entity we're looking for,
1513      // our only option is to walk through all of the declarations to
1514      // find that name. This will occur in a few cases:
1515      //
1516      //   - anonymous struct/union within a template
1517      //   - unnamed class/struct/union/enum within a template
1518      //
1519      // FIXME: Find a better way to find these instantiations!
1520      Result = findInstantiationOf(Context, D,
1521                                   ParentDC->decls_begin(),
1522                                   ParentDC->decls_end());
1523    }
1524
1525    assert(Result && "Unable to find instantiation of declaration!");
1526    D = Result;
1527  }
1528
1529  return D;
1530}
1531
1532/// \brief Performs template instantiation for all implicit template
1533/// instantiations we have seen until this point.
1534void Sema::PerformPendingImplicitInstantiations() {
1535  while (!PendingImplicitInstantiations.empty()) {
1536    PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
1537    PendingImplicitInstantiations.pop_front();
1538
1539    // Instantiate function definitions
1540    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
1541      PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
1542                                            Function->getLocation(), *this,
1543                                            Context.getSourceManager(),
1544                                           "instantiating function definition");
1545
1546      if (!Function->getBody())
1547        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
1548      continue;
1549    }
1550
1551    // Instantiate static data member definitions.
1552    VarDecl *Var = cast<VarDecl>(Inst.first);
1553    assert(Var->isStaticDataMember() && "Not a static data member?");
1554
1555    PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
1556                                          Var->getLocation(), *this,
1557                                          Context.getSourceManager(),
1558                                          "instantiating static data member "
1559                                          "definition");
1560
1561    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
1562  }
1563}
1564