SemaTemplateInstantiateDecl.cpp revision 9054f9878dbe2b1b8384c951ad07759d9de9dc8c
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/ASTContext.h"
14#include "clang/AST/DeclTemplate.h"
15#include "clang/AST/DeclVisitor.h"
16#include "clang/AST/Expr.h"
17#include "llvm/Support/Compiler.h"
18
19using namespace clang;
20
21namespace {
22  class VISIBILITY_HIDDEN TemplateDeclInstantiator
23    : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
24    Sema &SemaRef;
25    DeclContext *Owner;
26    const TemplateArgument *TemplateArgs;
27    unsigned NumTemplateArgs;
28
29  public:
30    typedef Sema::OwningExprResult OwningExprResult;
31
32    TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
33                             const TemplateArgument *TemplateArgs,
34                             unsigned NumTemplateArgs)
35      : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs),
36        NumTemplateArgs(NumTemplateArgs) { }
37
38    // FIXME: Once we get closer to completion, replace these
39    // manually-written declarations with automatically-generated ones
40    // from 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 *VisitCXXRecordDecl(CXXRecordDecl *D);
50    Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
51    Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
52    Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
53    Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
54    ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
55    Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
56
57    // Base case. FIXME: Remove once we can instantiate everything.
58    Decl *VisitDecl(Decl *) {
59      assert(false && "Template instantiation of unknown declaration kind!");
60      return 0;
61    }
62
63    // Helper functions for instantiating methods.
64    QualType InstantiateFunctionType(FunctionDecl *D,
65                             llvm::SmallVectorImpl<ParmVarDecl *> &Params);
66    bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
67  };
68}
69
70Decl *
71TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
72  assert(false && "Translation units cannot be instantiated");
73  return D;
74}
75
76Decl *
77TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
78  assert(false && "Namespaces cannot be instantiated");
79  return D;
80}
81
82Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
83  bool Invalid = false;
84  QualType T = D->getUnderlyingType();
85  if (T->isDependentType()) {
86    T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
87                                D->getLocation(),
88                                D->getDeclName());
89    if (T.isNull()) {
90      Invalid = true;
91      T = SemaRef.Context.IntTy;
92    }
93  }
94
95  // Create the new typedef
96  TypedefDecl *Typedef
97    = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
98                          D->getIdentifier(), T);
99  if (Invalid)
100    Typedef->setInvalidDecl();
101
102  Owner->addDecl(SemaRef.Context, Typedef);
103  return Typedef;
104}
105
106Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
107  // Instantiate the type of the declaration
108  QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
109                                       NumTemplateArgs,
110                                       D->getTypeSpecStartLoc(),
111                                       D->getDeclName());
112  if (T.isNull())
113    return 0;
114
115  // Build the instantiataed declaration
116  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
117                                 D->getLocation(), D->getIdentifier(),
118                                 T, D->getStorageClass(),
119                                 D->getTypeSpecStartLoc());
120  Var->setThreadSpecified(D->isThreadSpecified());
121  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
122  Var->setDeclaredInCondition(D->isDeclaredInCondition());
123
124  // FIXME: In theory, we could have a previous declaration for
125  // variables that are not static data members.
126  bool Redeclaration = false;
127  SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
128  Owner->addDecl(SemaRef.Context, Var);
129
130  if (D->getInit()) {
131    OwningExprResult Init
132      = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs, NumTemplateArgs);
133    if (Init.isInvalid())
134      Var->setInvalidDecl();
135    else
136      SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
137                                   D->hasCXXDirectInitializer());
138  }
139
140  return Var;
141}
142
143Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
144  bool Invalid = false;
145  QualType T = D->getType();
146  if (T->isDependentType())  {
147    T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
148                                D->getLocation(),
149                                D->getDeclName());
150    if (!T.isNull() && T->isFunctionType()) {
151      // C++ [temp.arg.type]p3:
152      //   If a declaration acquires a function type through a type
153      //   dependent on a template-parameter and this causes a
154      //   declaration that does not use the syntactic form of a
155      //   function declarator to have function type, the program is
156      //   ill-formed.
157      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
158        << T;
159      T = QualType();
160      Invalid = true;
161    }
162  }
163
164  Expr *BitWidth = D->getBitWidth();
165  if (Invalid)
166    BitWidth = 0;
167  else if (BitWidth) {
168    OwningExprResult InstantiatedBitWidth
169      = SemaRef.InstantiateExpr(BitWidth, TemplateArgs, NumTemplateArgs);
170    if (InstantiatedBitWidth.isInvalid()) {
171      Invalid = true;
172      BitWidth = 0;
173    } else
174      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
175  }
176
177  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
178                                            cast<RecordDecl>(Owner),
179                                            D->getLocation(),
180                                            D->isMutable(),
181                                            BitWidth,
182                                            D->getAccess(),
183                                            0);
184  if (Field) {
185    if (Invalid)
186      Field->setInvalidDecl();
187
188    Owner->addDecl(SemaRef.Context, Field);
189  }
190
191  return Field;
192}
193
194Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
195  Expr *AssertExpr = D->getAssertExpr();
196
197  OwningExprResult InstantiatedAssertExpr
198    = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs, NumTemplateArgs);
199  if (InstantiatedAssertExpr.isInvalid())
200    return 0;
201
202  OwningExprResult Message = SemaRef.Clone(D->getMessage());
203  Decl *StaticAssert
204    = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
205                                           move(InstantiatedAssertExpr),
206                                           move(Message)).getAs<Decl>();
207  return StaticAssert;
208}
209
210Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
211  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
212                                    D->getLocation(), D->getIdentifier(),
213                                    /*PrevDecl=*/0);
214  Enum->setAccess(D->getAccess());
215  Owner->addDecl(SemaRef.Context, Enum);
216  Enum->startDefinition();
217
218  llvm::SmallVector<Sema::DeclPtrTy, 16> Enumerators;
219
220  EnumConstantDecl *LastEnumConst = 0;
221  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(SemaRef.Context),
222         ECEnd = D->enumerator_end(SemaRef.Context);
223       EC != ECEnd; ++EC) {
224    // The specified value for the enumerator.
225    OwningExprResult Value = SemaRef.Owned((Expr *)0);
226    if (Expr *UninstValue = EC->getInitExpr())
227      Value = SemaRef.InstantiateExpr(UninstValue,
228                                      TemplateArgs, NumTemplateArgs);
229
230    // Drop the initial value and continue.
231    bool isInvalid = false;
232    if (Value.isInvalid()) {
233      Value = SemaRef.Owned((Expr *)0);
234      isInvalid = true;
235    }
236
237    EnumConstantDecl *EnumConst
238      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
239                                  EC->getLocation(), EC->getIdentifier(),
240                                  move(Value));
241
242    if (isInvalid) {
243      if (EnumConst)
244        EnumConst->setInvalidDecl();
245      Enum->setInvalidDecl();
246    }
247
248    if (EnumConst) {
249      Enum->addDecl(SemaRef.Context, EnumConst);
250      Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
251      LastEnumConst = EnumConst;
252    }
253  }
254
255  SemaRef.ActOnEnumBody(Enum->getLocation(), 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  llvm::SmallVector<ParmVarDecl *, 16> Params;
290  QualType T = InstantiateFunctionType(D, Params);
291  if (T.isNull())
292    return 0;
293
294  // Build the instantiated method declaration.
295  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
296  CXXMethodDecl *Method
297    = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
298                            D->getDeclName(), T, D->isStatic(),
299                            D->isInline());
300
301  // Attach the parameters
302  for (unsigned P = 0; P < Params.size(); ++P)
303    Params[P]->setOwningFunction(Method);
304  Method->setParams(SemaRef.Context, &Params[0], Params.size());
305
306  if (InitMethodInstantiation(Method, D))
307    Method->setInvalidDecl();
308
309  NamedDecl *PrevDecl
310    = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
311                                  Sema::LookupOrdinaryName, true);
312  // In C++, the previous declaration we find might be a tag type
313  // (class or enum). In this case, the new declaration will hide the
314  // tag type. Note that this does does not apply if we're declaring a
315  // typedef (C++ [dcl.typedef]p4).
316  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
317    PrevDecl = 0;
318  bool Redeclaration = false;
319  bool OverloadableAttrRequired = false;
320  SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
321                                   /*FIXME:*/OverloadableAttrRequired);
322
323  if (!Method->isInvalidDecl() || !PrevDecl)
324    Owner->addDecl(SemaRef.Context, Method);
325  return Method;
326}
327
328Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
329  llvm::SmallVector<ParmVarDecl *, 16> Params;
330  QualType T = InstantiateFunctionType(D, Params);
331  if (T.isNull())
332    return 0;
333
334  // Build the instantiated method declaration.
335  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
336  QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
337  DeclarationName Name
338    = SemaRef.Context.DeclarationNames.getCXXConstructorName(ClassTy);
339  CXXConstructorDecl *Constructor
340    = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
341                                 Name, T, D->isExplicit(), D->isInline(),
342                                 false);
343
344  // Attach the parameters
345  for (unsigned P = 0; P < Params.size(); ++P)
346    Params[P]->setOwningFunction(Constructor);
347  Constructor->setParams(SemaRef.Context, &Params[0], Params.size());
348
349  if (InitMethodInstantiation(Constructor, D))
350    Constructor->setInvalidDecl();
351
352  NamedDecl *PrevDecl
353    = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
354
355  // In C++, the previous declaration we find might be a tag type
356  // (class or enum). In this case, the new declaration will hide the
357  // tag type. Note that this does does not apply if we're declaring a
358  // typedef (C++ [dcl.typedef]p4).
359  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
360    PrevDecl = 0;
361  bool Redeclaration = false;
362  bool OverloadableAttrRequired = false;
363  SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
364                                   /*FIXME:*/OverloadableAttrRequired);
365
366  Owner->addDecl(SemaRef.Context, Constructor);
367  return Constructor;
368}
369
370Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
371  llvm::SmallVector<ParmVarDecl *, 16> Params;
372  QualType T = InstantiateFunctionType(D, Params);
373  if (T.isNull())
374    return 0;
375  assert(Params.size() == 0 && "Destructor with parameters?");
376
377  // Build the instantiated destructor declaration.
378  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
379  QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
380  CXXDestructorDecl *Destructor
381    = CXXDestructorDecl::Create(SemaRef.Context, Record,
382                                D->getLocation(),
383             SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
384                                T, D->isInline(), false);
385  if (InitMethodInstantiation(Destructor, D))
386    Destructor->setInvalidDecl();
387
388  bool Redeclaration = false;
389  bool OverloadableAttrRequired = false;
390  NamedDecl *PrevDecl = 0;
391  SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
392                                   /*FIXME:*/OverloadableAttrRequired);
393  Owner->addDecl(SemaRef.Context, Destructor);
394  return Destructor;
395}
396
397Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
398  llvm::SmallVector<ParmVarDecl *, 16> Params;
399  QualType T = InstantiateFunctionType(D, Params);
400  if (T.isNull())
401    return 0;
402  assert(Params.size() == 0 && "Destructor with parameters?");
403
404  // Build the instantiated conversion declaration.
405  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
406  QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
407  QualType ConvTy
408    = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
409  CXXConversionDecl *Conversion
410    = CXXConversionDecl::Create(SemaRef.Context, Record,
411                                D->getLocation(),
412         SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
413                                T, D->isInline(), D->isExplicit());
414  if (InitMethodInstantiation(Conversion, D))
415    Conversion->setInvalidDecl();
416
417  bool Redeclaration = false;
418  bool OverloadableAttrRequired = false;
419  NamedDecl *PrevDecl = 0;
420  SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
421                                   /*FIXME:*/OverloadableAttrRequired);
422  Owner->addDecl(SemaRef.Context, Conversion);
423  return Conversion;
424}
425
426ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
427  QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
428                                           NumTemplateArgs, D->getLocation(),
429                                           D->getDeclName());
430  if (OrigT.isNull())
431    return 0;
432
433  QualType T = SemaRef.adjustParameterType(OrigT);
434
435  if (D->getDefaultArg()) {
436    // FIXME: Leave a marker for "uninstantiated" default
437    // arguments. They only get instantiated on demand at the call
438    // site.
439    unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
440        "sorry, dropping default argument during template instantiation");
441    SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
442      << D->getDefaultArg()->getSourceRange();
443  }
444
445  // Allocate the parameter
446  ParmVarDecl *Param = 0;
447  if (T == OrigT)
448    Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
449                                D->getIdentifier(), T, D->getStorageClass(),
450                                0);
451  else
452    Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
453                                        D->getLocation(), D->getIdentifier(),
454                                        T, OrigT, D->getStorageClass(), 0);
455
456  // Note: we don't try to instantiate function parameters until after
457  // we've instantiated the function's type. Therefore, we don't have
458  // to check for 'void' parameter types here.
459  return Param;
460}
461
462Decl *
463TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
464  // Since parameter types can decay either before or after
465  // instantiation, we simply treat OriginalParmVarDecls as
466  // ParmVarDecls the same way, and create one or the other depending
467  // on what happens after template instantiation.
468  return VisitParmVarDecl(D);
469}
470
471Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
472                            const TemplateArgument *TemplateArgs,
473                            unsigned NumTemplateArgs) {
474  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs,
475                                        NumTemplateArgs);
476  return Instantiator.Visit(D);
477}
478
479/// \brief Instantiates the type of the given function, including
480/// instantiating all of the function parameters.
481///
482/// \param D The function that we will be instantiated
483///
484/// \param Params the instantiated parameter declarations
485
486/// \returns the instantiated function's type if successfull, a NULL
487/// type if there was an error.
488QualType
489TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
490                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
491  bool InvalidDecl = false;
492
493  // Instantiate the function parameters
494  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0,
495                                             TemplateArgs, NumTemplateArgs);
496  llvm::SmallVector<QualType, 16> ParamTys;
497  for (FunctionDecl::param_iterator P = D->param_begin(),
498                                 PEnd = D->param_end();
499       P != PEnd; ++P) {
500    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
501      if (PInst->getType()->isVoidType()) {
502        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
503        PInst->setInvalidDecl();
504      }
505      else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
506                                              PInst->getType(),
507                                              diag::err_abstract_type_in_decl,
508                                              Sema::AbstractParamType))
509        PInst->setInvalidDecl();
510
511      Params.push_back(PInst);
512      ParamTys.push_back(PInst->getType());
513
514      if (PInst->isInvalidDecl())
515        InvalidDecl = true;
516    } else
517      InvalidDecl = true;
518  }
519
520  // FIXME: Deallocate dead declarations.
521  if (InvalidDecl)
522    return QualType();
523
524  const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
525  assert(Proto && "Missing prototype?");
526  QualType ResultType
527    = SemaRef.InstantiateType(Proto->getResultType(),
528                              TemplateArgs, NumTemplateArgs,
529                              D->getLocation(), D->getDeclName());
530  if (ResultType.isNull())
531    return QualType();
532
533  return SemaRef.BuildFunctionType(ResultType, &ParamTys[0], ParamTys.size(),
534                                   Proto->isVariadic(), Proto->getTypeQuals(),
535                                   D->getLocation(), D->getDeclName());
536}
537
538/// \brief Initializes common fields of an instantiated method
539/// declaration (New) from the corresponding fields of its template
540/// (Tmpl).
541///
542/// \returns true if there was an error
543bool
544TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
545                                                  CXXMethodDecl *Tmpl) {
546  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
547  New->setAccess(Tmpl->getAccess());
548  if (Tmpl->isVirtual()) {
549    New->setVirtual();
550    Record->setAggregate(false);
551    Record->setPOD(false);
552    Record->setPolymorphic(true);
553  }
554  if (Tmpl->isDeleted())
555    New->setDeleted();
556  if (Tmpl->isPure()) {
557    New->setPure();
558    Record->setAbstract(true);
559  }
560
561  // FIXME: attributes
562  // FIXME: New needs a pointer to Tmpl
563  return false;
564}
565