CGCXX.cpp revision ccd5259d33cbbdd6f5fbf7ccab4cb4a2702309ea
1//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
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//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CGCXXABI.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Mangle.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/Frontend/CodeGenOptions.h"
27#include "llvm/ADT/StringExtras.h"
28using namespace clang;
29using namespace CodeGen;
30
31/// Determines whether the given function has a trivial body that does
32/// not require any specific codegen.
33static bool HasTrivialBody(const FunctionDecl *FD) {
34  Stmt *S = FD->getBody();
35  if (!S)
36    return true;
37  if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
38    return true;
39  return false;
40}
41
42/// Try to emit a base destructor as an alias to its primary
43/// base-class destructor.
44bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
45  if (!getCodeGenOpts().CXXCtorDtorAliases)
46    return true;
47
48  // If the destructor doesn't have a trivial body, we have to emit it
49  // separately.
50  if (!HasTrivialBody(D))
51    return true;
52
53  const CXXRecordDecl *Class = D->getParent();
54
55  // If we need to manipulate a VTT parameter, give up.
56  if (Class->getNumVBases()) {
57    // Extra Credit:  passing extra parameters is perfectly safe
58    // in many calling conventions, so only bail out if the ctor's
59    // calling convention is nonstandard.
60    return true;
61  }
62
63  // If any fields have a non-trivial destructor, we have to emit it
64  // separately.
65  for (CXXRecordDecl::field_iterator I = Class->field_begin(),
66         E = Class->field_end(); I != E; ++I)
67    if (const RecordType *RT = (*I)->getType()->getAs<RecordType>())
68      if (!cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor())
69        return true;
70
71  // Try to find a unique base class with a non-trivial destructor.
72  const CXXRecordDecl *UniqueBase = 0;
73  for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
74         E = Class->bases_end(); I != E; ++I) {
75
76    // We're in the base destructor, so skip virtual bases.
77    if (I->isVirtual()) continue;
78
79    // Skip base classes with trivial destructors.
80    const CXXRecordDecl *Base
81      = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
82    if (Base->hasTrivialDestructor()) continue;
83
84    // If we've already found a base class with a non-trivial
85    // destructor, give up.
86    if (UniqueBase) return true;
87    UniqueBase = Base;
88  }
89
90  // If we didn't find any bases with a non-trivial destructor, then
91  // the base destructor is actually effectively trivial, which can
92  // happen if it was needlessly user-defined or if there are virtual
93  // bases with non-trivial destructors.
94  if (!UniqueBase)
95    return true;
96
97  /// If we don't have a definition for the destructor yet, don't
98  /// emit.  We can't emit aliases to declarations; that's just not
99  /// how aliases work.
100  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
101  if (!BaseD->isImplicit() && !BaseD->hasBody())
102    return true;
103
104  // If the base is at a non-zero offset, give up.
105  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
106  if (ClassLayout.getBaseClassOffsetInBits(UniqueBase) != 0)
107    return true;
108
109  return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
110                                  GlobalDecl(BaseD, Dtor_Base));
111}
112
113/// Try to emit a definition as a global alias for another definition.
114bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
115                                             GlobalDecl TargetDecl) {
116  if (!getCodeGenOpts().CXXCtorDtorAliases)
117    return true;
118
119  // The alias will use the linkage of the referrent.  If we can't
120  // support aliases with that linkage, fail.
121  llvm::GlobalValue::LinkageTypes Linkage
122    = getFunctionLinkage(cast<FunctionDecl>(AliasDecl.getDecl()));
123
124  switch (Linkage) {
125  // We can definitely emit aliases to definitions with external linkage.
126  case llvm::GlobalValue::ExternalLinkage:
127  case llvm::GlobalValue::ExternalWeakLinkage:
128    break;
129
130  // Same with local linkage.
131  case llvm::GlobalValue::InternalLinkage:
132  case llvm::GlobalValue::PrivateLinkage:
133  case llvm::GlobalValue::LinkerPrivateLinkage:
134    break;
135
136  // We should try to support linkonce linkages.
137  case llvm::GlobalValue::LinkOnceAnyLinkage:
138  case llvm::GlobalValue::LinkOnceODRLinkage:
139    return true;
140
141  // Other linkages will probably never be supported.
142  default:
143    return true;
144  }
145
146  llvm::GlobalValue::LinkageTypes TargetLinkage
147    = getFunctionLinkage(cast<FunctionDecl>(TargetDecl.getDecl()));
148
149  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
150    return true;
151
152  // Derive the type for the alias.
153  const llvm::PointerType *AliasType
154    = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
155
156  // Find the referrent.  Some aliases might require a bitcast, in
157  // which case the caller is responsible for ensuring the soundness
158  // of these semantics.
159  llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
160  llvm::Constant *Aliasee = Ref;
161  if (Ref->getType() != AliasType)
162    Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
163
164  // Create the alias with no name.
165  llvm::GlobalAlias *Alias =
166    new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
167
168  // Switch any previous uses to the alias.
169  llvm::StringRef MangledName = getMangledName(AliasDecl);
170  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
171  if (Entry) {
172    assert(Entry->isDeclaration() && "definition already exists for alias");
173    assert(Entry->getType() == AliasType &&
174           "declaration exists with different type");
175    Alias->takeName(Entry);
176    Entry->replaceAllUsesWith(Alias);
177    Entry->eraseFromParent();
178  } else {
179    Alias->setName(MangledName);
180  }
181
182  // Finally, set up the alias with its proper name and attributes.
183  SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
184
185  return false;
186}
187
188void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
189  // The constructor used for constructing this as a complete class;
190  // constucts the virtual bases, then calls the base constructor.
191  EmitGlobal(GlobalDecl(D, Ctor_Complete));
192
193  // The constructor used for constructing this as a base class;
194  // ignores virtual bases.
195  EmitGlobal(GlobalDecl(D, Ctor_Base));
196}
197
198void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
199                                       CXXCtorType Type) {
200  // The complete constructor is equivalent to the base constructor
201  // for classes with no virtual bases.  Try to emit it as an alias.
202  if (Type == Ctor_Complete &&
203      !D->getParent()->getNumVBases() &&
204      !TryEmitDefinitionAsAlias(GlobalDecl(D, Ctor_Complete),
205                                GlobalDecl(D, Ctor_Base)))
206    return;
207
208  llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXConstructor(D, Type));
209  setFunctionLinkage(D, Fn);
210
211  CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
212
213  SetFunctionDefinitionAttributes(D, Fn);
214  SetLLVMFunctionAttributesForDefinition(D, Fn);
215}
216
217llvm::GlobalValue *
218CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
219                                       CXXCtorType Type) {
220  GlobalDecl GD(D, Type);
221
222  llvm::StringRef Name = getMangledName(GD);
223  if (llvm::GlobalValue *V = GetGlobalValue(Name))
224    return V;
225
226  const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
227  const llvm::FunctionType *FTy =
228    getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
229                               FPT->isVariadic());
230  return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD));
231}
232
233void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
234  // The destructor in a virtual table is always a 'deleting'
235  // destructor, which calls the complete destructor and then uses the
236  // appropriate operator delete.
237  if (D->isVirtual())
238    EmitGlobal(GlobalDecl(D, Dtor_Deleting));
239
240  // The destructor used for destructing this as a most-derived class;
241  // call the base destructor and then destructs any virtual bases.
242  EmitGlobal(GlobalDecl(D, Dtor_Complete));
243
244  // The destructor used for destructing this as a base class; ignores
245  // virtual bases.
246  EmitGlobal(GlobalDecl(D, Dtor_Base));
247}
248
249void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
250                                      CXXDtorType Type) {
251  // The complete destructor is equivalent to the base destructor for
252  // classes with no virtual bases, so try to emit it as an alias.
253  if (Type == Dtor_Complete &&
254      !D->getParent()->getNumVBases() &&
255      !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete),
256                                GlobalDecl(D, Dtor_Base)))
257    return;
258
259  // The base destructor is equivalent to the base destructor of its
260  // base class if there is exactly one non-virtual base class with a
261  // non-trivial destructor, there are no fields with a non-trivial
262  // destructor, and the body of the destructor is trivial.
263  if (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D))
264    return;
265
266  llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type));
267  setFunctionLinkage(D, Fn);
268
269  CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
270
271  SetFunctionDefinitionAttributes(D, Fn);
272  SetLLVMFunctionAttributesForDefinition(D, Fn);
273}
274
275llvm::GlobalValue *
276CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
277                                      CXXDtorType Type) {
278  GlobalDecl GD(D, Type);
279
280  llvm::StringRef Name = getMangledName(GD);
281  if (llvm::GlobalValue *V = GetGlobalValue(Name))
282    return V;
283
284  const llvm::FunctionType *FTy =
285    getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
286
287  return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD));
288}
289
290static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VTableIndex,
291                                     llvm::Value *This, const llvm::Type *Ty) {
292  Ty = Ty->getPointerTo()->getPointerTo();
293
294  llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
295  llvm::Value *VFuncPtr =
296    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
297  return CGF.Builder.CreateLoad(VFuncPtr);
298}
299
300llvm::Value *
301CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
302                                  const llvm::Type *Ty) {
303  MD = MD->getCanonicalDecl();
304  uint64_t VTableIndex = CGM.getVTables().getMethodVTableIndex(MD);
305
306  return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
307}
308
309/// BuildVirtualCall - This routine is to support gcc's kext ABI making
310/// indirect call to virtual functions. It makes the call through indexing
311/// into the vtable.
312llvm::Value *
313CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
314                                  NestedNameSpecifier *Qual,
315                                  llvm::Value *This,
316                                  const llvm::Type *Ty) {
317  llvm::Value *VTable = 0;
318  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
319         "BuildAppleKextVirtualCall - bad Qual kind");
320
321  const Type *QTy = Qual->getAsType();
322  QualType T = QualType(QTy, 0);
323  const RecordType *RT = T->getAs<RecordType>();
324  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
325  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
326
327  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
328    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
329
330  VTable = CGM.getVTables().GetAddrOfVTable(RD);
331  Ty = Ty->getPointerTo()->getPointerTo();
332  VTable = Builder.CreateBitCast(VTable, Ty);
333  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
334  MD = MD->getCanonicalDecl();
335  uint64_t VTableIndex = CGM.getVTables().getMethodVTableIndex(MD);
336  uint64_t AddressPoint =
337    CGM.getVTables().getAddressPoint(BaseSubobject(RD, 0), RD);
338  VTableIndex += AddressPoint;
339  llvm::Value *VFuncPtr =
340    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
341  return CGF.Builder.CreateLoad(VFuncPtr);
342}
343
344/// BuildVirtualCall - This routine makes indirect vtable call for
345/// call to virtual destructors. It returns 0 if it could not do it.
346llvm::Value *
347CodeGenFunction::BuildAppleKextVirtualDestructorCall(
348                                            const CXXDestructorDecl *DD,
349                                            CXXDtorType Type,
350                                            const CXXRecordDecl *RD) {
351  llvm::Value * Callee = 0;
352  const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD);
353  // FIXME. Dtor_Base dtor is always direct!!
354  // It need be somehow inline expanded into the caller.
355  // -O does that. But need to support -O0 as well.
356  if (MD->isVirtual() && Type != Dtor_Base) {
357    DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
358    // Compute the function type we're calling.
359    const CGFunctionInfo *FInfo =
360    &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
361                                    Dtor_Complete);
362    const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
363    const llvm::Type *Ty
364      = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
365    if (!RD)
366      RD = DD->getParent();
367    llvm::Value *VTable = CGM.getVTables().GetAddrOfVTable(RD);
368    Ty = Ty->getPointerTo()->getPointerTo();
369    VTable = Builder.CreateBitCast(VTable, Ty);
370    uint64_t VTableIndex =
371    CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type));
372    uint64_t AddressPoint =
373    CGM.getVTables().getAddressPoint(BaseSubobject(RD, 0), RD);
374    VTableIndex += AddressPoint;
375    llvm::Value *VFuncPtr =
376    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
377    Callee = CGF.Builder.CreateLoad(VFuncPtr);
378  }
379  return Callee;
380}
381
382llvm::Value *
383CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
384                                  llvm::Value *This, const llvm::Type *Ty) {
385  DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
386  uint64_t VTableIndex =
387    CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type));
388
389  return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
390}
391
392