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