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