1218893Sdim//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This contains code dealing with C++ code generation.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14198092Srdivacky// We might split this into multiple files if it gets too unwieldy
15193326Sed
16252723Sdim#include "CodeGenModule.h"
17208600Srdivacky#include "CGCXXABI.h"
18193326Sed#include "CodeGenFunction.h"
19193326Sed#include "clang/AST/ASTContext.h"
20193326Sed#include "clang/AST/Decl.h"
21193326Sed#include "clang/AST/DeclCXX.h"
22193326Sed#include "clang/AST/DeclObjC.h"
23218893Sdim#include "clang/AST/Mangle.h"
24252723Sdim#include "clang/AST/RecordLayout.h"
25198092Srdivacky#include "clang/AST/StmtCXX.h"
26210299Sed#include "clang/Frontend/CodeGenOptions.h"
27193326Sed#include "llvm/ADT/StringExtras.h"
28193326Sedusing namespace clang;
29193326Sedusing namespace CodeGen;
30193326Sed
31204643Srdivacky/// Try to emit a base destructor as an alias to its primary
32204643Srdivacky/// base-class destructor.
33204643Srdivackybool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
34204643Srdivacky  if (!getCodeGenOpts().CXXCtorDtorAliases)
35204643Srdivacky    return true;
36198092Srdivacky
37263509Sdim  // Producing an alias to a base class ctor/dtor can degrade debug quality
38263509Sdim  // as the debugger cannot tell them appart.
39263509Sdim  if (getCodeGenOpts().OptimizationLevel == 0)
40263509Sdim    return true;
41263509Sdim
42204643Srdivacky  // If the destructor doesn't have a trivial body, we have to emit it
43204643Srdivacky  // separately.
44223017Sdim  if (!D->hasTrivialBody())
45204643Srdivacky    return true;
46198092Srdivacky
47204643Srdivacky  const CXXRecordDecl *Class = D->getParent();
48204643Srdivacky
49204643Srdivacky  // If we need to manipulate a VTT parameter, give up.
50204643Srdivacky  if (Class->getNumVBases()) {
51204643Srdivacky    // Extra Credit:  passing extra parameters is perfectly safe
52204643Srdivacky    // in many calling conventions, so only bail out if the ctor's
53204643Srdivacky    // calling convention is nonstandard.
54204643Srdivacky    return true;
55204643Srdivacky  }
56204643Srdivacky
57218893Sdim  // If any field has a non-trivial destructor, we have to emit the
58218893Sdim  // destructor separately.
59204643Srdivacky  for (CXXRecordDecl::field_iterator I = Class->field_begin(),
60204643Srdivacky         E = Class->field_end(); I != E; ++I)
61245431Sdim    if (I->getType().isDestructedType())
62218893Sdim      return true;
63204643Srdivacky
64204643Srdivacky  // Try to find a unique base class with a non-trivial destructor.
65204643Srdivacky  const CXXRecordDecl *UniqueBase = 0;
66204643Srdivacky  for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
67204643Srdivacky         E = Class->bases_end(); I != E; ++I) {
68204643Srdivacky
69204643Srdivacky    // We're in the base destructor, so skip virtual bases.
70204643Srdivacky    if (I->isVirtual()) continue;
71204643Srdivacky
72204643Srdivacky    // Skip base classes with trivial destructors.
73204643Srdivacky    const CXXRecordDecl *Base
74204643Srdivacky      = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
75204643Srdivacky    if (Base->hasTrivialDestructor()) continue;
76204643Srdivacky
77204643Srdivacky    // If we've already found a base class with a non-trivial
78204643Srdivacky    // destructor, give up.
79204643Srdivacky    if (UniqueBase) return true;
80204643Srdivacky    UniqueBase = Base;
81204643Srdivacky  }
82204643Srdivacky
83204643Srdivacky  // If we didn't find any bases with a non-trivial destructor, then
84204643Srdivacky  // the base destructor is actually effectively trivial, which can
85204643Srdivacky  // happen if it was needlessly user-defined or if there are virtual
86204643Srdivacky  // bases with non-trivial destructors.
87204643Srdivacky  if (!UniqueBase)
88204643Srdivacky    return true;
89204643Srdivacky
90204643Srdivacky  // If the base is at a non-zero offset, give up.
91204643Srdivacky  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
92245431Sdim  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
93204643Srdivacky    return true;
94204643Srdivacky
95263509Sdim  // Give up if the calling conventions don't match. We could update the call,
96263509Sdim  // but it is probably not worth it.
97263509Sdim  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
98263509Sdim  if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
99263509Sdim      D->getType()->getAs<FunctionType>()->getCallConv())
100263509Sdim    return true;
101263509Sdim
102204643Srdivacky  return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
103263509Sdim                                  GlobalDecl(BaseD, Dtor_Base),
104263509Sdim                                  false);
105193326Sed}
106193326Sed
107204643Srdivacky/// Try to emit a definition as a global alias for another definition.
108263509Sdim/// If \p InEveryTU is true, we know that an equivalent alias can be produced
109263509Sdim/// in every translation unit.
110204643Srdivackybool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
111263509Sdim                                             GlobalDecl TargetDecl,
112263509Sdim                                             bool InEveryTU) {
113204643Srdivacky  if (!getCodeGenOpts().CXXCtorDtorAliases)
114204643Srdivacky    return true;
115204643Srdivacky
116204643Srdivacky  // The alias will use the linkage of the referrent.  If we can't
117204643Srdivacky  // support aliases with that linkage, fail.
118263509Sdim  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
119204643Srdivacky
120263509Sdim  // We can't use an alias if the linkage is not valid for one.
121263509Sdim  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
122204643Srdivacky    return true;
123204643Srdivacky
124263509Sdim  llvm::GlobalValue::LinkageTypes TargetLinkage =
125263509Sdim      getFunctionLinkage(TargetDecl);
126204643Srdivacky
127263509Sdim  // Check if we have it already.
128263509Sdim  StringRef MangledName = getMangledName(AliasDecl);
129263509Sdim  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
130263509Sdim  if (Entry && !Entry->isDeclaration())
131263509Sdim    return false;
132263509Sdim  if (Replacements.count(MangledName))
133263509Sdim    return false;
134204793Srdivacky
135204643Srdivacky  // Derive the type for the alias.
136226890Sdim  llvm::PointerType *AliasType
137204643Srdivacky    = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
138204643Srdivacky
139204643Srdivacky  // Find the referrent.  Some aliases might require a bitcast, in
140204643Srdivacky  // which case the caller is responsible for ensuring the soundness
141204643Srdivacky  // of these semantics.
142204643Srdivacky  llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
143204643Srdivacky  llvm::Constant *Aliasee = Ref;
144204643Srdivacky  if (Ref->getType() != AliasType)
145204643Srdivacky    Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
146204643Srdivacky
147263509Sdim  // Instead of creating as alias to a linkonce_odr, replace all of the uses
148263509Sdim  // of the aliassee.
149263509Sdim  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
150263509Sdim     (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
151263509Sdim      !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
152263509Sdim    // FIXME: An extern template instanciation will create functions with
153263509Sdim    // linkage "AvailableExternally". In libc++, some classes also define
154263509Sdim    // members with attribute "AlwaysInline" and expect no reference to
155263509Sdim    // be generated. It is desirable to reenable this optimisation after
156263509Sdim    // corresponding LLVM changes.
157263509Sdim    Replacements[MangledName] = Aliasee;
158263509Sdim    return false;
159263509Sdim  }
160263509Sdim
161263509Sdim  if (!InEveryTU) {
162263509Sdim    /// If we don't have a definition for the destructor yet, don't
163263509Sdim    /// emit.  We can't emit aliases to declarations; that's just not
164263509Sdim    /// how aliases work.
165263509Sdim    if (Ref->isDeclaration())
166263509Sdim      return true;
167263509Sdim  }
168263509Sdim
169263509Sdim  // Don't create an alias to a linker weak symbol. This avoids producing
170263509Sdim  // different COMDATs in different TUs. Another option would be to
171263509Sdim  // output the alias both for weak_odr and linkonce_odr, but that
172263509Sdim  // requires explicit comdat support in the IL.
173263509Sdim  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
174263509Sdim    return true;
175263509Sdim
176204643Srdivacky  // Create the alias with no name.
177204643Srdivacky  llvm::GlobalAlias *Alias =
178204643Srdivacky    new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
179204643Srdivacky
180204643Srdivacky  // Switch any previous uses to the alias.
181204643Srdivacky  if (Entry) {
182204643Srdivacky    assert(Entry->getType() == AliasType &&
183204643Srdivacky           "declaration exists with different type");
184205408Srdivacky    Alias->takeName(Entry);
185204643Srdivacky    Entry->replaceAllUsesWith(Alias);
186204643Srdivacky    Entry->eraseFromParent();
187205408Srdivacky  } else {
188210299Sed    Alias->setName(MangledName);
189204643Srdivacky  }
190204643Srdivacky
191204643Srdivacky  // Finally, set up the alias with its proper name and attributes.
192218893Sdim  SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
193204643Srdivacky
194204643Srdivacky  return false;
195204643Srdivacky}
196204643Srdivacky
197221345Sdimvoid CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor,
198221345Sdim                                       CXXCtorType ctorType) {
199204643Srdivacky  // The complete constructor is equivalent to the base constructor
200204643Srdivacky  // for classes with no virtual bases.  Try to emit it as an alias.
201252723Sdim  if (getTarget().getCXXABI().hasConstructorVariants() &&
202221345Sdim      !ctor->getParent()->getNumVBases() &&
203263509Sdim      (ctorType == Ctor_Complete || ctorType == Ctor_Base)) {
204263509Sdim    bool ProducedAlias =
205263509Sdim        !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete),
206263509Sdim                                  GlobalDecl(ctor, Ctor_Base), true);
207263509Sdim    if (ctorType == Ctor_Complete && ProducedAlias)
208263509Sdim      return;
209263509Sdim  }
210198092Srdivacky
211235633Sdim  const CGFunctionInfo &fnInfo =
212235633Sdim    getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
213198092Srdivacky
214221345Sdim  llvm::Function *fn =
215221345Sdim    cast<llvm::Function>(GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo));
216263509Sdim  setFunctionLinkage(GlobalDecl(ctor, ctorType), fn);
217198092Srdivacky
218221345Sdim  CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo);
219221345Sdim
220221345Sdim  SetFunctionDefinitionAttributes(ctor, fn);
221221345Sdim  SetLLVMFunctionAttributesForDefinition(ctor, fn);
222193326Sed}
223193326Sed
224204643Srdivackyllvm::GlobalValue *
225221345SdimCodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
226221345Sdim                                       CXXCtorType ctorType,
227221345Sdim                                       const CGFunctionInfo *fnInfo) {
228221345Sdim  GlobalDecl GD(ctor, ctorType);
229210299Sed
230226890Sdim  StringRef name = getMangledName(GD);
231221345Sdim  if (llvm::GlobalValue *existing = GetGlobalValue(name))
232221345Sdim    return existing;
233204643Srdivacky
234235633Sdim  if (!fnInfo)
235235633Sdim    fnInfo = &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
236221345Sdim
237235633Sdim  llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo);
238221345Sdim  return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
239218893Sdim                                                      /*ForVTable=*/false));
240193326Sed}
241193326Sed
242221345Sdimvoid CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *dtor,
243221345Sdim                                      CXXDtorType dtorType) {
244204643Srdivacky  // The complete destructor is equivalent to the base destructor for
245204643Srdivacky  // classes with no virtual bases, so try to emit it as an alias.
246263509Sdim  if (!dtor->getParent()->getNumVBases() &&
247263509Sdim      (dtorType == Dtor_Complete || dtorType == Dtor_Base)) {
248263509Sdim    bool ProducedAlias =
249263509Sdim        !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete),
250263509Sdim                                  GlobalDecl(dtor, Dtor_Base), true);
251263509Sdim    if (ProducedAlias) {
252263509Sdim      if (dtorType == Dtor_Complete)
253263509Sdim        return;
254263509Sdim      if (dtor->isVirtual())
255263509Sdim        getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
256263509Sdim    }
257263509Sdim  }
258198092Srdivacky
259204643Srdivacky  // The base destructor is equivalent to the base destructor of its
260204643Srdivacky  // base class if there is exactly one non-virtual base class with a
261204643Srdivacky  // non-trivial destructor, there are no fields with a non-trivial
262204643Srdivacky  // destructor, and the body of the destructor is trivial.
263221345Sdim  if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor))
264204643Srdivacky    return;
265204643Srdivacky
266235633Sdim  const CGFunctionInfo &fnInfo =
267235633Sdim    getTypes().arrangeCXXDestructor(dtor, dtorType);
268204643Srdivacky
269221345Sdim  llvm::Function *fn =
270221345Sdim    cast<llvm::Function>(GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo));
271263509Sdim  setFunctionLinkage(GlobalDecl(dtor, dtorType), fn);
272198092Srdivacky
273221345Sdim  CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo);
274221345Sdim
275221345Sdim  SetFunctionDefinitionAttributes(dtor, fn);
276221345Sdim  SetLLVMFunctionAttributesForDefinition(dtor, fn);
277193326Sed}
278193326Sed
279204643Srdivackyllvm::GlobalValue *
280221345SdimCodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
281221345Sdim                                      CXXDtorType dtorType,
282263509Sdim                                      const CGFunctionInfo *fnInfo,
283263509Sdim                                      llvm::FunctionType *fnType) {
284221345Sdim  GlobalDecl GD(dtor, dtorType);
285210299Sed
286226890Sdim  StringRef name = getMangledName(GD);
287221345Sdim  if (llvm::GlobalValue *existing = GetGlobalValue(name))
288221345Sdim    return existing;
289204643Srdivacky
290263509Sdim  if (!fnType) {
291263509Sdim    if (!fnInfo) fnInfo = &getTypes().arrangeCXXDestructor(dtor, dtorType);
292263509Sdim    fnType = getTypes().GetFunctionType(*fnInfo);
293263509Sdim  }
294221345Sdim  return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
295218893Sdim                                                      /*ForVTable=*/false));
296193326Sed}
297193326Sed
298263509Sdimstatic llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
299263509Sdim                                              GlobalDecl GD,
300263509Sdim                                              llvm::Type *Ty,
301263509Sdim                                              const CXXRecordDecl *RD) {
302263509Sdim  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
303263509Sdim         "No kext in Microsoft ABI");
304263509Sdim  GD = GD.getCanonicalDecl();
305263509Sdim  CodeGenModule &CGM = CGF.CGM;
306263509Sdim  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
307218893Sdim  Ty = Ty->getPointerTo()->getPointerTo();
308263509Sdim  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
309263509Sdim  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
310263509Sdim  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
311263509Sdim  uint64_t AddressPoint =
312263509Sdim    CGM.getItaniumVTableContext().getVTableLayout(RD)
313263509Sdim       .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
314263509Sdim  VTableIndex += AddressPoint;
315263509Sdim  llvm::Value *VFuncPtr =
316263509Sdim    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
317199482Srdivacky  return CGF.Builder.CreateLoad(VFuncPtr);
318199482Srdivacky}
319199482Srdivacky
320263509Sdim/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
321218893Sdim/// indirect call to virtual functions. It makes the call through indexing
322218893Sdim/// into the vtable.
323199482Srdivackyllvm::Value *
324218893SdimCodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
325218893Sdim                                  NestedNameSpecifier *Qual,
326226890Sdim                                  llvm::Type *Ty) {
327218893Sdim  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
328218893Sdim         "BuildAppleKextVirtualCall - bad Qual kind");
329218893Sdim
330218893Sdim  const Type *QTy = Qual->getAsType();
331218893Sdim  QualType T = QualType(QTy, 0);
332218893Sdim  const RecordType *RT = T->getAs<RecordType>();
333218893Sdim  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
334218893Sdim  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
335218893Sdim
336218893Sdim  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
337218893Sdim    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
338263509Sdim
339263509Sdim  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
340199482Srdivacky}
341208600Srdivacky
342218893Sdim/// BuildVirtualCall - This routine makes indirect vtable call for
343218893Sdim/// call to virtual destructors. It returns 0 if it could not do it.
344218893Sdimllvm::Value *
345218893SdimCodeGenFunction::BuildAppleKextVirtualDestructorCall(
346218893Sdim                                            const CXXDestructorDecl *DD,
347218893Sdim                                            CXXDtorType Type,
348218893Sdim                                            const CXXRecordDecl *RD) {
349218893Sdim  const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD);
350218893Sdim  // FIXME. Dtor_Base dtor is always direct!!
351218893Sdim  // It need be somehow inline expanded into the caller.
352218893Sdim  // -O does that. But need to support -O0 as well.
353218893Sdim  if (MD->isVirtual() && Type != Dtor_Base) {
354218893Sdim    // Compute the function type we're calling.
355263509Sdim    const CGFunctionInfo &FInfo =
356263509Sdim      CGM.getTypes().arrangeCXXDestructor(DD, Dtor_Complete);
357235633Sdim    llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
358263509Sdim    return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
359218893Sdim  }
360263509Sdim  return 0;
361212904Sdim}
362