CGCXX.cpp revision 583f6de423aa42c8a4894cc64e72036484e6343b
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                                  false);
100}
101
102/// Try to emit a definition as a global alias for another definition.
103/// If \p InEveryTU is true, we know that an equivalent alias can be produced
104/// in every translation unit.
105bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
106                                             GlobalDecl TargetDecl,
107                                             bool InEveryTU) {
108  if (!getCodeGenOpts().CXXCtorDtorAliases)
109    return true;
110
111  // The alias will use the linkage of the referrent.  If we can't
112  // support aliases with that linkage, fail.
113  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
114
115  llvm::GlobalValue::LinkageTypes TargetLinkage
116    = getFunctionLinkage(TargetDecl);
117
118  // Don't create an alias to a linker weak symbol unless we know we can do
119  // that in every TU. This avoids producing different COMDATs in different
120  // TUs.
121  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage)) {
122    if (!InEveryTU)
123      return true;
124
125    // In addition to making sure we produce it in every TU, we have to make
126    // sure llvm keeps it.
127    // FIXME: Instead of outputting an alias we could just replace every use of
128    // AliasDecl with TargetDecl.
129    assert(Linkage == TargetLinkage);
130    Linkage = llvm::GlobalValue::WeakODRLinkage;
131  }
132
133  // We can't use an alias if the linkage is not valid for one.
134  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
135    return true;
136
137  // Check if we have it already.
138  StringRef MangledName = getMangledName(AliasDecl);
139  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
140  if (Entry && !Entry->isDeclaration())
141    return false;
142
143  // Derive the type for the alias.
144  llvm::PointerType *AliasType
145    = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
146
147  // Find the referrent.  Some aliases might require a bitcast, in
148  // which case the caller is responsible for ensuring the soundness
149  // of these semantics.
150  llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
151  llvm::Constant *Aliasee = Ref;
152  if (Ref->getType() != AliasType)
153    Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
154
155  // Create the alias with no name.
156  llvm::GlobalAlias *Alias =
157    new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
158
159  // Switch any previous uses to the alias.
160  if (Entry) {
161    assert(Entry->getType() == AliasType &&
162           "declaration exists with different type");
163    Alias->takeName(Entry);
164    Entry->replaceAllUsesWith(Alias);
165    Entry->eraseFromParent();
166  } else {
167    Alias->setName(MangledName);
168  }
169
170  // Finally, set up the alias with its proper name and attributes.
171  SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
172
173  return false;
174}
175
176void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor,
177                                       CXXCtorType ctorType) {
178  // The complete constructor is equivalent to the base constructor
179  // for classes with no virtual bases.  Try to emit it as an alias.
180  if (getTarget().getCXXABI().hasConstructorVariants() &&
181      !ctor->getParent()->getNumVBases() &&
182      (ctorType == Ctor_Complete || ctorType == Ctor_Base)) {
183    bool ProducedAlias =
184        !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete),
185                                  GlobalDecl(ctor, Ctor_Base), true);
186    if (ctorType == Ctor_Complete && ProducedAlias)
187      return;
188  }
189
190  const CGFunctionInfo &fnInfo =
191    getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
192
193  llvm::Function *fn =
194    cast<llvm::Function>(GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo));
195  setFunctionLinkage(GlobalDecl(ctor, ctorType), fn);
196
197  CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo);
198
199  SetFunctionDefinitionAttributes(ctor, fn);
200  SetLLVMFunctionAttributesForDefinition(ctor, fn);
201}
202
203llvm::GlobalValue *
204CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
205                                       CXXCtorType ctorType,
206                                       const CGFunctionInfo *fnInfo) {
207  GlobalDecl GD(ctor, ctorType);
208
209  StringRef name = getMangledName(GD);
210  if (llvm::GlobalValue *existing = GetGlobalValue(name))
211    return existing;
212
213  if (!fnInfo)
214    fnInfo = &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
215
216  llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo);
217  return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
218                                                      /*ForVTable=*/false));
219}
220
221void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *dtor,
222                                      CXXDtorType dtorType) {
223  // The complete destructor is equivalent to the base destructor for
224  // classes with no virtual bases, so try to emit it as an alias.
225  if (!dtor->getParent()->getNumVBases() &&
226      (dtorType == Dtor_Complete || dtorType == Dtor_Base)) {
227    bool ProducedAlias =
228        !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete),
229                                  GlobalDecl(dtor, Dtor_Base), true);
230    if (ProducedAlias) {
231      if (dtorType == Dtor_Complete)
232        return;
233      if (dtor->isVirtual())
234        getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
235    }
236  }
237
238  // The base destructor is equivalent to the base destructor of its
239  // base class if there is exactly one non-virtual base class with a
240  // non-trivial destructor, there are no fields with a non-trivial
241  // destructor, and the body of the destructor is trivial.
242  if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor))
243    return;
244
245  const CGFunctionInfo &fnInfo =
246    getTypes().arrangeCXXDestructor(dtor, dtorType);
247
248  llvm::Function *fn =
249    cast<llvm::Function>(GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo));
250  setFunctionLinkage(GlobalDecl(dtor, dtorType), fn);
251
252  CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo);
253
254  SetFunctionDefinitionAttributes(dtor, fn);
255  SetLLVMFunctionAttributesForDefinition(dtor, fn);
256}
257
258llvm::GlobalValue *
259CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
260                                      CXXDtorType dtorType,
261                                      const CGFunctionInfo *fnInfo,
262                                      llvm::FunctionType *fnType) {
263  // If the class has no virtual bases, then the complete and base destructors
264  // are equivalent, for all C++ ABIs supported by clang.  We can save on code
265  // size by calling the base dtor directly, especially if we'd have to emit a
266  // thunk otherwise.
267  // FIXME: We should do this for Itanium, after verifying that nothing breaks.
268  if (dtorType == Dtor_Complete && dtor->getParent()->getNumVBases() == 0 &&
269      getCXXABI().useThunkForDtorVariant(dtor, Dtor_Complete))
270    dtorType = Dtor_Base;
271
272  GlobalDecl GD(dtor, dtorType);
273
274  StringRef name = getMangledName(GD);
275  if (llvm::GlobalValue *existing = GetGlobalValue(name))
276    return existing;
277
278  if (!fnType) {
279    if (!fnInfo) fnInfo = &getTypes().arrangeCXXDestructor(dtor, dtorType);
280    fnType = getTypes().GetFunctionType(*fnInfo);
281  }
282  return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
283                                                      /*ForVTable=*/false));
284}
285
286static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
287                                              GlobalDecl GD,
288                                              llvm::Type *Ty,
289                                              const CXXRecordDecl *RD) {
290  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
291         "No kext in Microsoft ABI");
292  GD = GD.getCanonicalDecl();
293  CodeGenModule &CGM = CGF.CGM;
294  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
295  Ty = Ty->getPointerTo()->getPointerTo();
296  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
297  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
298  uint64_t VTableIndex = CGM.getVTableContext().getMethodVTableIndex(GD);
299  uint64_t AddressPoint =
300    CGM.getVTableContext().getVTableLayout(RD)
301       .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
302  VTableIndex += AddressPoint;
303  llvm::Value *VFuncPtr =
304    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
305  return CGF.Builder.CreateLoad(VFuncPtr);
306}
307
308/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
309/// indirect call to virtual functions. It makes the call through indexing
310/// into the vtable.
311llvm::Value *
312CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
313                                  NestedNameSpecifier *Qual,
314                                  llvm::Type *Ty) {
315  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
316         "BuildAppleKextVirtualCall - bad Qual kind");
317
318  const Type *QTy = Qual->getAsType();
319  QualType T = QualType(QTy, 0);
320  const RecordType *RT = T->getAs<RecordType>();
321  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
322  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
323
324  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
325    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
326
327  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
328}
329
330/// BuildVirtualCall - This routine makes indirect vtable call for
331/// call to virtual destructors. It returns 0 if it could not do it.
332llvm::Value *
333CodeGenFunction::BuildAppleKextVirtualDestructorCall(
334                                            const CXXDestructorDecl *DD,
335                                            CXXDtorType Type,
336                                            const CXXRecordDecl *RD) {
337  const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD);
338  // FIXME. Dtor_Base dtor is always direct!!
339  // It need be somehow inline expanded into the caller.
340  // -O does that. But need to support -O0 as well.
341  if (MD->isVirtual() && Type != Dtor_Base) {
342    // Compute the function type we're calling.
343    const CGFunctionInfo &FInfo =
344      CGM.getTypes().arrangeCXXDestructor(DD, Dtor_Complete);
345    llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
346    return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
347  }
348  return 0;
349}
350