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