SemaTemplateInstantiateDecl.cpp revision 0ca20ac8cea99c43d89510f29cf3dc876f9c9111
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 "llvm/Support/Compiler.h"
19
20using namespace clang;
21
22namespace {
23  class VISIBILITY_HIDDEN TemplateDeclInstantiator
24    : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
25    Sema &SemaRef;
26    DeclContext *Owner;
27    const TemplateArgumentList &TemplateArgs;
28
29  public:
30    typedef Sema::OwningExprResult OwningExprResult;
31
32    TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
33                             const TemplateArgumentList &TemplateArgs)
34      : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
35
36    // FIXME: Once we get closer to completion, replace these manually-written
37    // declarations with automatically-generated ones from
38    // clang/AST/DeclNodes.def.
39    Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
40    Decl *VisitNamespaceDecl(NamespaceDecl *D);
41    Decl *VisitTypedefDecl(TypedefDecl *D);
42    Decl *VisitVarDecl(VarDecl *D);
43    Decl *VisitFieldDecl(FieldDecl *D);
44    Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
45    Decl *VisitEnumDecl(EnumDecl *D);
46    Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
47    Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
48    Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
49    Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
50    Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
51    Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
52    ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
53    Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
54
55    // Base case. FIXME: Remove once we can instantiate everything.
56    Decl *VisitDecl(Decl *) {
57      assert(false && "Template instantiation of unknown declaration kind!");
58      return 0;
59    }
60
61    // Helper functions for instantiating methods.
62    QualType InstantiateFunctionType(FunctionDecl *D,
63                             llvm::SmallVectorImpl<ParmVarDecl *> &Params);
64    bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
65  };
66}
67
68Decl *
69TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
70  assert(false && "Translation units cannot be instantiated");
71  return D;
72}
73
74Decl *
75TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
76  assert(false && "Namespaces cannot be instantiated");
77  return D;
78}
79
80Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
81  bool Invalid = false;
82  QualType T = D->getUnderlyingType();
83  if (T->isDependentType()) {
84    T = SemaRef.InstantiateType(T, TemplateArgs,
85                                D->getLocation(), D->getDeclName());
86    if (T.isNull()) {
87      Invalid = true;
88      T = SemaRef.Context.IntTy;
89    }
90  }
91
92  // Create the new typedef
93  TypedefDecl *Typedef
94    = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
95                          D->getIdentifier(), T);
96  if (Invalid)
97    Typedef->setInvalidDecl();
98
99  Owner->addDecl(SemaRef.Context, Typedef);
100
101  return Typedef;
102}
103
104Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
105  // Instantiate the type of the declaration
106  QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
107                                       D->getTypeSpecStartLoc(),
108                                       D->getDeclName());
109  if (T.isNull())
110    return 0;
111
112  // Build the instantiated declaration
113  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
114                                 D->getLocation(), D->getIdentifier(),
115                                 T, D->getStorageClass(),
116                                 D->getTypeSpecStartLoc());
117  Var->setThreadSpecified(D->isThreadSpecified());
118  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
119  Var->setDeclaredInCondition(D->isDeclaredInCondition());
120
121  // FIXME: In theory, we could have a previous declaration for variables that
122  // are not static data members.
123  bool Redeclaration = false;
124  SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
125  Owner->addDecl(SemaRef.Context, Var);
126
127  if (D->getInit()) {
128    OwningExprResult Init
129      = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
130    if (Init.isInvalid())
131      Var->setInvalidDecl();
132    else
133      SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
134                                   D->hasCXXDirectInitializer());
135  } else {
136    // FIXME: Call ActOnUninitializedDecl? (Not always)
137  }
138
139  return Var;
140}
141
142Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
143  bool Invalid = false;
144  QualType T = D->getType();
145  if (T->isDependentType())  {
146    T = SemaRef.InstantiateType(T, TemplateArgs,
147                                D->getLocation(), D->getDeclName());
148    if (!T.isNull() && T->isFunctionType()) {
149      // C++ [temp.arg.type]p3:
150      //   If a declaration acquires a function type through a type
151      //   dependent on a template-parameter and this causes a
152      //   declaration that does not use the syntactic form of a
153      //   function declarator to have function type, the program is
154      //   ill-formed.
155      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
156        << T;
157      T = QualType();
158      Invalid = true;
159    }
160  }
161
162  Expr *BitWidth = D->getBitWidth();
163  if (Invalid)
164    BitWidth = 0;
165  else if (BitWidth) {
166    OwningExprResult InstantiatedBitWidth
167      = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
168    if (InstantiatedBitWidth.isInvalid()) {
169      Invalid = true;
170      BitWidth = 0;
171    } else
172      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
173  }
174
175  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
176                                            cast<RecordDecl>(Owner),
177                                            D->getLocation(),
178                                            D->isMutable(),
179                                            BitWidth,
180                                            D->getAccess(),
181                                            0);
182  if (Field) {
183    if (Invalid)
184      Field->setInvalidDecl();
185
186    Owner->addDecl(SemaRef.Context, Field);
187  }
188
189  return Field;
190}
191
192Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
193  Expr *AssertExpr = D->getAssertExpr();
194
195  OwningExprResult InstantiatedAssertExpr
196    = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
197  if (InstantiatedAssertExpr.isInvalid())
198    return 0;
199
200  OwningExprResult Message = SemaRef.Clone(D->getMessage());
201  Decl *StaticAssert
202    = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
203                                           move(InstantiatedAssertExpr),
204                                           move(Message)).getAs<Decl>();
205  return StaticAssert;
206}
207
208Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
209  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
210                                    D->getLocation(), D->getIdentifier(),
211                                    /*PrevDecl=*/0);
212  Enum->setInstantiationOfMemberEnum(D);
213  Enum->setAccess(D->getAccess());
214  Owner->addDecl(SemaRef.Context, Enum);
215  Enum->startDefinition();
216
217  llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
218
219  EnumConstantDecl *LastEnumConst = 0;
220  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(SemaRef.Context),
221         ECEnd = D->enumerator_end(SemaRef.Context);
222       EC != ECEnd; ++EC) {
223    // The specified value for the enumerator.
224    OwningExprResult Value = SemaRef.Owned((Expr *)0);
225    if (Expr *UninstValue = EC->getInitExpr())
226      Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
227
228    // Drop the initial value and continue.
229    bool isInvalid = false;
230    if (Value.isInvalid()) {
231      Value = SemaRef.Owned((Expr *)0);
232      isInvalid = true;
233    }
234
235    EnumConstantDecl *EnumConst
236      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
237                                  EC->getLocation(), EC->getIdentifier(),
238                                  move(Value));
239
240    if (isInvalid) {
241      if (EnumConst)
242        EnumConst->setInvalidDecl();
243      Enum->setInvalidDecl();
244    }
245
246    if (EnumConst) {
247      Enum->addDecl(SemaRef.Context, EnumConst);
248      Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
249      LastEnumConst = EnumConst;
250    }
251  }
252
253  // FIXME: Fixup LBraceLoc and RBraceLoc
254  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
255                        Sema::DeclPtrTy::make(Enum),
256                        &Enumerators[0], Enumerators.size());
257
258  return Enum;
259}
260
261Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
262  assert(false && "EnumConstantDecls can only occur within EnumDecls.");
263  return 0;
264}
265
266Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
267  CXXRecordDecl *PrevDecl = 0;
268  if (D->isInjectedClassName())
269    PrevDecl = cast<CXXRecordDecl>(Owner);
270
271  CXXRecordDecl *Record
272    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
273                            D->getLocation(), D->getIdentifier(), PrevDecl);
274  Record->setImplicit(D->isImplicit());
275  Record->setAccess(D->getAccess());
276  if (!D->isInjectedClassName())
277    Record->setInstantiationOfMemberClass(D);
278
279  Owner->addDecl(SemaRef.Context, Record);
280  return Record;
281}
282
283Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
284  // Only handle actual methods; we'll deal with constructors,
285  // destructors, etc. separately.
286  if (D->getKind() != Decl::CXXMethod)
287    return 0;
288
289  Sema::LocalInstantiationScope Scope(SemaRef);
290
291  llvm::SmallVector<ParmVarDecl *, 4> Params;
292  QualType T = InstantiateFunctionType(D, Params);
293  if (T.isNull())
294    return 0;
295
296  // Build the instantiated method declaration.
297  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
298  CXXMethodDecl *Method
299    = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
300                            D->getDeclName(), T, D->isStatic(),
301                            D->isInline());
302  Method->setInstantiationOfMemberFunction(D);
303
304  // Attach the parameters
305  for (unsigned P = 0; P < Params.size(); ++P)
306    Params[P]->setOwningFunction(Method);
307  Method->setParams(SemaRef.Context, Params.data(), Params.size());
308
309  if (InitMethodInstantiation(Method, D))
310    Method->setInvalidDecl();
311
312  NamedDecl *PrevDecl
313    = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
314                                  Sema::LookupOrdinaryName, true);
315  // In C++, the previous declaration we find might be a tag type
316  // (class or enum). In this case, the new declaration will hide the
317  // tag type. Note that this does does not apply if we're declaring a
318  // typedef (C++ [dcl.typedef]p4).
319  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
320    PrevDecl = 0;
321  bool Redeclaration = false;
322  bool OverloadableAttrRequired = false;
323  SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
324                                   /*FIXME:*/OverloadableAttrRequired);
325
326  if (!Method->isInvalidDecl() || !PrevDecl)
327    Owner->addDecl(SemaRef.Context, Method);
328  return Method;
329}
330
331Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
332  Sema::LocalInstantiationScope Scope(SemaRef);
333
334  llvm::SmallVector<ParmVarDecl *, 4> Params;
335  QualType T = InstantiateFunctionType(D, Params);
336  if (T.isNull())
337    return 0;
338
339  // Build the instantiated method declaration.
340  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
341  QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
342  DeclarationName Name
343    = SemaRef.Context.DeclarationNames.getCXXConstructorName(
344                                 SemaRef.Context.getCanonicalType(ClassTy));
345  CXXConstructorDecl *Constructor
346    = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
347                                 Name, T, D->isExplicit(), D->isInline(),
348                                 false);
349  Constructor->setInstantiationOfMemberFunction(D);
350
351  // Attach the parameters
352  for (unsigned P = 0; P < Params.size(); ++P)
353    Params[P]->setOwningFunction(Constructor);
354  Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
355
356  if (InitMethodInstantiation(Constructor, D))
357    Constructor->setInvalidDecl();
358
359  NamedDecl *PrevDecl
360    = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
361
362  // In C++, the previous declaration we find might be a tag type
363  // (class or enum). In this case, the new declaration will hide the
364  // tag type. Note that this does does not apply if we're declaring a
365  // typedef (C++ [dcl.typedef]p4).
366  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
367    PrevDecl = 0;
368  bool Redeclaration = false;
369  bool OverloadableAttrRequired = false;
370  SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
371                                   /*FIXME:*/OverloadableAttrRequired);
372
373  Record->addedConstructor(SemaRef.Context, Constructor);
374  Owner->addDecl(SemaRef.Context, Constructor);
375  return Constructor;
376}
377
378Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
379  Sema::LocalInstantiationScope Scope(SemaRef);
380
381  llvm::SmallVector<ParmVarDecl *, 4> Params;
382  QualType T = InstantiateFunctionType(D, Params);
383  if (T.isNull())
384    return 0;
385  assert(Params.size() == 0 && "Destructor with parameters?");
386
387  // Build the instantiated destructor declaration.
388  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
389  QualType ClassTy =
390    SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
391  CXXDestructorDecl *Destructor
392    = CXXDestructorDecl::Create(SemaRef.Context, Record,
393                                D->getLocation(),
394             SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
395                                T, D->isInline(), false);
396  Destructor->setInstantiationOfMemberFunction(D);
397  if (InitMethodInstantiation(Destructor, D))
398    Destructor->setInvalidDecl();
399
400  bool Redeclaration = false;
401  bool OverloadableAttrRequired = false;
402  NamedDecl *PrevDecl = 0;
403  SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
404                                   /*FIXME:*/OverloadableAttrRequired);
405  Owner->addDecl(SemaRef.Context, Destructor);
406  return Destructor;
407}
408
409Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
410  Sema::LocalInstantiationScope Scope(SemaRef);
411
412  llvm::SmallVector<ParmVarDecl *, 4> Params;
413  QualType T = InstantiateFunctionType(D, Params);
414  if (T.isNull())
415    return 0;
416  assert(Params.size() == 0 && "Destructor with parameters?");
417
418  // Build the instantiated conversion declaration.
419  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
420  QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
421  QualType ConvTy
422    = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
423  CXXConversionDecl *Conversion
424    = CXXConversionDecl::Create(SemaRef.Context, Record,
425                                D->getLocation(),
426         SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
427                                T, D->isInline(), D->isExplicit());
428  Conversion->setInstantiationOfMemberFunction(D);
429  if (InitMethodInstantiation(Conversion, D))
430    Conversion->setInvalidDecl();
431
432  bool Redeclaration = false;
433  bool OverloadableAttrRequired = false;
434  NamedDecl *PrevDecl = 0;
435  SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
436                                   /*FIXME:*/OverloadableAttrRequired);
437  Owner->addDecl(SemaRef.Context, Conversion);
438  return Conversion;
439}
440
441ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
442  QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
443                                           D->getLocation(), D->getDeclName());
444  if (OrigT.isNull())
445    return 0;
446
447  QualType T = SemaRef.adjustParameterType(OrigT);
448
449  if (D->getDefaultArg()) {
450    // FIXME: Leave a marker for "uninstantiated" default
451    // arguments. They only get instantiated on demand at the call
452    // site.
453    unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
454        "sorry, dropping default argument during template instantiation");
455    SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
456      << D->getDefaultArg()->getSourceRange();
457  }
458
459  // Allocate the parameter
460  ParmVarDecl *Param = 0;
461  if (T == OrigT)
462    Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
463                                D->getIdentifier(), T, D->getStorageClass(),
464                                0);
465  else
466    Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
467                                        D->getLocation(), D->getIdentifier(),
468                                        T, OrigT, D->getStorageClass(), 0);
469
470  // Note: we don't try to instantiate function parameters until after
471  // we've instantiated the function's type. Therefore, we don't have
472  // to check for 'void' parameter types here.
473  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
474  return Param;
475}
476
477Decl *
478TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
479  // Since parameter types can decay either before or after
480  // instantiation, we simply treat OriginalParmVarDecls as
481  // ParmVarDecls the same way, and create one or the other depending
482  // on what happens after template instantiation.
483  return VisitParmVarDecl(D);
484}
485
486Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
487                            const TemplateArgumentList &TemplateArgs) {
488  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
489  return Instantiator.Visit(D);
490}
491
492/// \brief Instantiates the type of the given function, including
493/// instantiating all of the function parameters.
494///
495/// \param D The function that we will be instantiated
496///
497/// \param Params the instantiated parameter declarations
498
499/// \returns the instantiated function's type if successfull, a NULL
500/// type if there was an error.
501QualType
502TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
503                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
504  bool InvalidDecl = false;
505
506  // Instantiate the function parameters
507  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
508  llvm::SmallVector<QualType, 4> ParamTys;
509  for (FunctionDecl::param_iterator P = D->param_begin(),
510                                 PEnd = D->param_end();
511       P != PEnd; ++P) {
512    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
513      if (PInst->getType()->isVoidType()) {
514        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
515        PInst->setInvalidDecl();
516      }
517      else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
518                                              PInst->getType(),
519                                              diag::err_abstract_type_in_decl,
520                                              Sema::AbstractParamType))
521        PInst->setInvalidDecl();
522
523      Params.push_back(PInst);
524      ParamTys.push_back(PInst->getType());
525
526      if (PInst->isInvalidDecl())
527        InvalidDecl = true;
528    } else
529      InvalidDecl = true;
530  }
531
532  // FIXME: Deallocate dead declarations.
533  if (InvalidDecl)
534    return QualType();
535
536  const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
537  assert(Proto && "Missing prototype?");
538  QualType ResultType
539    = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
540                              D->getLocation(), D->getDeclName());
541  if (ResultType.isNull())
542    return QualType();
543
544  return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
545                                   Proto->isVariadic(), Proto->getTypeQuals(),
546                                   D->getLocation(), D->getDeclName());
547}
548
549/// \brief Initializes common fields of an instantiated method
550/// declaration (New) from the corresponding fields of its template
551/// (Tmpl).
552///
553/// \returns true if there was an error
554bool
555TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
556                                                  CXXMethodDecl *Tmpl) {
557  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
558  New->setAccess(Tmpl->getAccess());
559  if (Tmpl->isVirtualAsWritten()) {
560    New->setVirtualAsWritten(true);
561    Record->setAggregate(false);
562    Record->setPOD(false);
563    Record->setPolymorphic(true);
564  }
565  if (Tmpl->isDeleted())
566    New->setDeleted();
567  if (Tmpl->isPure()) {
568    New->setPure();
569    Record->setAbstract(true);
570  }
571
572  // FIXME: attributes
573  // FIXME: New needs a pointer to Tmpl
574  return false;
575}
576
577/// \brief Instantiate the definition of the given function from its
578/// template.
579///
580/// \param Function the already-instantiated declaration of a
581/// function.
582void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
583                                         FunctionDecl *Function) {
584  // FIXME: make this work for function template specializations, too.
585
586  if (Function->isInvalidDecl())
587    return;
588
589  // Find the function body that we'll be substituting.
590  const FunctionDecl *PatternDecl
591    = Function->getInstantiatedFromMemberFunction();
592  Stmt *Pattern = 0;
593  if (PatternDecl)
594    Pattern = PatternDecl->getBody(Context, PatternDecl);
595
596  if (!Pattern)
597    return;
598
599  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
600  if (Inst)
601    return;
602
603  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
604
605  // Introduce a new scope where local variable instantiations will be
606  // recorded.
607  LocalInstantiationScope Scope(*this);
608
609  // Introduce the instantiated function parameters into the local
610  // instantiation scope.
611  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
612    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
613                            Function->getParamDecl(I));
614
615  // Enter the scope of this instantiation. We don't use
616  // PushDeclContext because we don't have a scope.
617  DeclContext *PreviousContext = CurContext;
618  CurContext = Function;
619
620  // Instantiate the function body.
621  OwningStmtResult Body
622    = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
623
624  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
625                          /*IsInstantiation=*/true);
626
627  CurContext = PreviousContext;
628
629  DeclGroupRef DG(Function);
630  Consumer.HandleTopLevelDecl(DG);
631}
632
633/// \brief Instantiate the definition of the given variable from its
634/// template.
635///
636/// \param Var the already-instantiated declaration of a variable.
637void Sema::InstantiateVariableDefinition(VarDecl *Var) {
638  // FIXME: Implement this!
639}
640
641static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
642  if (D->getKind() != Other->getKind())
643    return false;
644
645  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
646    return Ctx.getCanonicalDecl(Record->getInstantiatedFromMemberClass())
647             == Ctx.getCanonicalDecl(D);
648
649  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
650    return Ctx.getCanonicalDecl(Function->getInstantiatedFromMemberFunction())
651             == Ctx.getCanonicalDecl(D);
652
653  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
654    return Ctx.getCanonicalDecl(Enum->getInstantiatedFromMemberEnum())
655             == Ctx.getCanonicalDecl(D);
656
657  // FIXME: How can we find instantiations of anonymous unions?
658
659  return D->getDeclName() && isa<NamedDecl>(Other) &&
660    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
661}
662
663template<typename ForwardIterator>
664static NamedDecl *findInstantiationOf(ASTContext &Ctx,
665                                      NamedDecl *D,
666                                      ForwardIterator first,
667                                      ForwardIterator last) {
668  for (; first != last; ++first)
669    if (isInstantiationOf(Ctx, D, *first))
670      return cast<NamedDecl>(*first);
671
672  return 0;
673}
674
675/// \brief Find the instantiation of the given declaration within the
676/// current instantiation.
677///
678/// This routine is intended to be used when \p D is a declaration
679/// referenced from within a template, that needs to mapped into the
680/// corresponding declaration within an instantiation. For example,
681/// given:
682///
683/// \code
684/// template<typename T>
685/// struct X {
686///   enum Kind {
687///     KnownValue = sizeof(T)
688///   };
689///
690///   bool getKind() const { return KnownValue; }
691/// };
692///
693/// template struct X<int>;
694/// \endcode
695///
696/// In the instantiation of X<int>::getKind(), we need to map the
697/// EnumConstantDecl for KnownValue (which refers to
698/// X<T>::<Kind>::KnownValue) to its instantiation
699/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
700/// this mapping from within the instantiation of X<int>.
701NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
702  DeclContext *ParentDC = D->getDeclContext();
703  if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
704    // D is a local of some kind. Look into the map of local
705    // declarations to their instantiations.
706    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
707  }
708
709  if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
710    ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
711    if (!ParentDecl)
712      return 0;
713
714    ParentDC = cast<DeclContext>(ParentDecl);
715  }
716
717  if (ParentDC != D->getDeclContext()) {
718    // We performed some kind of instantiation in the parent context,
719    // so now we need to look into the instantiated parent context to
720    // find the instantiation of the declaration D.
721    NamedDecl *Result = 0;
722    if (D->getDeclName()) {
723      DeclContext::lookup_result Found
724        = ParentDC->lookup(Context, D->getDeclName());
725      Result = findInstantiationOf(Context, D, Found.first, Found.second);
726    } else {
727      // Since we don't have a name for the entity we're looking for,
728      // our only option is to walk through all of the declarations to
729      // find that name. This will occur in a few cases:
730      //
731      //   - anonymous struct/union within a template
732      //   - unnamed class/struct/union/enum within a template
733      //
734      // FIXME: Find a better way to find these instantiations!
735      Result = findInstantiationOf(Context, D,
736                                   ParentDC->decls_begin(Context),
737                                   ParentDC->decls_end(Context));
738    }
739    assert(Result && "Unable to find instantiation of declaration!");
740    D = Result;
741  }
742
743  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
744    if (ClassTemplateDecl *ClassTemplate
745          = Record->getDescribedClassTemplate()) {
746      // When the declaration D was parsed, it referred to the current
747      // instantiation. Therefore, look through the current context,
748      // which contains actual instantiations, to find the
749      // instantiation of the "current instantiation" that D refers
750      // to. Alternatively, we could just instantiate the
751      // injected-class-name with the current template arguments, but
752      // such an instantiation is far more expensive.
753      for (DeclContext *DC = CurContext; !DC->isFileContext();
754           DC = DC->getParent()) {
755        if (ClassTemplateSpecializationDecl *Spec
756              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
757          if (Context.getCanonicalDecl(Spec->getSpecializedTemplate())
758              == Context.getCanonicalDecl(ClassTemplate))
759            return Spec;
760      }
761
762      assert(false &&
763             "Unable to find declaration for the current instantiation");
764    }
765
766  return D;
767}
768