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  // Producing an alias to a base class ctor/dtor can degrade debug quality
38  // as the debugger cannot tell them apart.
39  if (getCodeGenOpts().OptimizationLevel == 0)
40    return true;
41
42  // If the destructor doesn't have a trivial body, we have to emit it
43  // separately.
44  if (!D->hasTrivialBody())
45    return true;
46
47  const CXXRecordDecl *Class = D->getParent();
48
49  // We are going to instrument this destructor, so give up even if it is
50  // currently empty.
51  if (Class->mayInsertExtraPadding())
52    return true;
53
54  // If we need to manipulate a VTT parameter, give up.
55  if (Class->getNumVBases()) {
56    // Extra Credit:  passing extra parameters is perfectly safe
57    // in many calling conventions, so only bail out if the ctor's
58    // calling convention is nonstandard.
59    return true;
60  }
61
62  // If any field has a non-trivial destructor, we have to emit the
63  // destructor separately.
64  for (const auto *I : Class->fields())
65    if (I->getType().isDestructedType())
66      return true;
67
68  // Try to find a unique base class with a non-trivial destructor.
69  const CXXRecordDecl *UniqueBase = nullptr;
70  for (const auto &I : Class->bases()) {
71
72    // We're in the base destructor, so skip virtual bases.
73    if (I.isVirtual()) continue;
74
75    // Skip base classes with trivial destructors.
76    const auto *Base =
77        cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
78    if (Base->hasTrivialDestructor()) continue;
79
80    // If we've already found a base class with a non-trivial
81    // destructor, give up.
82    if (UniqueBase) return true;
83    UniqueBase = Base;
84  }
85
86  // If we didn't find any bases with a non-trivial destructor, then
87  // the base destructor is actually effectively trivial, which can
88  // happen if it was needlessly user-defined or if there are virtual
89  // bases with non-trivial destructors.
90  if (!UniqueBase)
91    return true;
92
93  // If the base is at a non-zero offset, give up.
94  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
95  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
96    return true;
97
98  // Give up if the calling conventions don't match. We could update the call,
99  // but it is probably not worth it.
100  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
101  if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
102      D->getType()->getAs<FunctionType>()->getCallConv())
103    return true;
104
105  return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
106                                  GlobalDecl(BaseD, Dtor_Base),
107                                  false);
108}
109
110/// Try to emit a definition as a global alias for another definition.
111/// If \p InEveryTU is true, we know that an equivalent alias can be produced
112/// in every translation unit.
113bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
114                                             GlobalDecl TargetDecl,
115                                             bool InEveryTU) {
116  if (!getCodeGenOpts().CXXCtorDtorAliases)
117    return true;
118
119  // The alias will use the linkage of the referent.  If we can't
120  // support aliases with that linkage, fail.
121  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
122
123  // We can't use an alias if the linkage is not valid for one.
124  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
125    return true;
126
127  // Don't create a weak alias for a dllexport'd symbol.
128  if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() &&
129      llvm::GlobalValue::isWeakForLinker(Linkage))
130    return true;
131
132  llvm::GlobalValue::LinkageTypes TargetLinkage =
133      getFunctionLinkage(TargetDecl);
134
135  // Check if we have it already.
136  StringRef MangledName = getMangledName(AliasDecl);
137  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
138  if (Entry && !Entry->isDeclaration())
139    return false;
140  if (Replacements.count(MangledName))
141    return false;
142
143  // Derive the type for the alias.
144  llvm::PointerType *AliasType
145    = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
146
147  // Find the referent.  Some aliases might require a bitcast, in
148  // which case the caller is responsible for ensuring the soundness
149  // of these semantics.
150  auto *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  // Instead of creating as alias to a linkonce_odr, replace all of the uses
156  // of the aliasee.
157  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
158     (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
159      !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
160    // FIXME: An extern template instantiation will create functions with
161    // linkage "AvailableExternally". In libc++, some classes also define
162    // members with attribute "AlwaysInline" and expect no reference to
163    // be generated. It is desirable to reenable this optimisation after
164    // corresponding LLVM changes.
165    Replacements[MangledName] = Aliasee;
166    return false;
167  }
168
169  if (!InEveryTU) {
170    // If we don't have a definition for the destructor yet, don't
171    // emit.  We can't emit aliases to declarations; that's just not
172    // how aliases work.
173    if (Ref->isDeclaration())
174      return true;
175  }
176
177  // Don't create an alias to a linker weak symbol. This avoids producing
178  // different COMDATs in different TUs. Another option would be to
179  // output the alias both for weak_odr and linkonce_odr, but that
180  // requires explicit comdat support in the IL.
181  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
182    return true;
183
184  // Create the alias with no name.
185  auto *Alias = llvm::GlobalAlias::create(AliasType->getElementType(), 0,
186                                          Linkage, "", Aliasee, &getModule());
187
188  // Switch any previous uses to the alias.
189  if (Entry) {
190    assert(Entry->getType() == AliasType &&
191           "declaration exists with different type");
192    Alias->takeName(Entry);
193    Entry->replaceAllUsesWith(Alias);
194    Entry->eraseFromParent();
195  } else {
196    Alias->setName(MangledName);
197  }
198
199  // Finally, set up the alias with its proper name and attributes.
200  setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
201
202  return false;
203}
204
205llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
206                                                  StructorType Type) {
207  const CGFunctionInfo &FnInfo =
208      getTypes().arrangeCXXStructorDeclaration(MD, Type);
209  auto *Fn = cast<llvm::Function>(
210      getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true));
211
212  GlobalDecl GD;
213  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
214    GD = GlobalDecl(DD, toCXXDtorType(Type));
215  } else {
216    const auto *CD = cast<CXXConstructorDecl>(MD);
217    GD = GlobalDecl(CD, toCXXCtorType(Type));
218  }
219
220  setFunctionLinkage(GD, Fn);
221  CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
222  setFunctionDefinitionAttributes(MD, Fn);
223  SetLLVMFunctionAttributesForDefinition(MD, Fn);
224  return Fn;
225}
226
227llvm::GlobalValue *CodeGenModule::getAddrOfCXXStructor(
228    const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
229    llvm::FunctionType *FnType, bool DontDefer) {
230  GlobalDecl GD;
231  if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
232    GD = GlobalDecl(CD, toCXXCtorType(Type));
233  } else {
234    auto *DD = dyn_cast<CXXDestructorDecl>(MD);
235    GD = GlobalDecl(DD, toCXXDtorType(Type));
236  }
237
238  StringRef Name = getMangledName(GD);
239  if (llvm::GlobalValue *Existing = GetGlobalValue(Name))
240    return Existing;
241
242  if (!FnType) {
243    if (!FnInfo)
244      FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
245    FnType = getTypes().GetFunctionType(*FnInfo);
246  }
247
248  return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD,
249                                                      /*ForVTable=*/false,
250                                                      DontDefer));
251}
252
253static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
254                                              GlobalDecl GD,
255                                              llvm::Type *Ty,
256                                              const CXXRecordDecl *RD) {
257  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
258         "No kext in Microsoft ABI");
259  GD = GD.getCanonicalDecl();
260  CodeGenModule &CGM = CGF.CGM;
261  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
262  Ty = Ty->getPointerTo()->getPointerTo();
263  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
264  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
265  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
266  uint64_t AddressPoint =
267    CGM.getItaniumVTableContext().getVTableLayout(RD)
268       .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
269  VTableIndex += AddressPoint;
270  llvm::Value *VFuncPtr =
271    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
272  return CGF.Builder.CreateLoad(VFuncPtr);
273}
274
275/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
276/// indirect call to virtual functions. It makes the call through indexing
277/// into the vtable.
278llvm::Value *
279CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
280                                  NestedNameSpecifier *Qual,
281                                  llvm::Type *Ty) {
282  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
283         "BuildAppleKextVirtualCall - bad Qual kind");
284
285  const Type *QTy = Qual->getAsType();
286  QualType T = QualType(QTy, 0);
287  const RecordType *RT = T->getAs<RecordType>();
288  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
289  const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
290
291  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
292    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
293
294  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
295}
296
297/// BuildVirtualCall - This routine makes indirect vtable call for
298/// call to virtual destructors. It returns 0 if it could not do it.
299llvm::Value *
300CodeGenFunction::BuildAppleKextVirtualDestructorCall(
301                                            const CXXDestructorDecl *DD,
302                                            CXXDtorType Type,
303                                            const CXXRecordDecl *RD) {
304  const auto *MD = cast<CXXMethodDecl>(DD);
305  // FIXME. Dtor_Base dtor is always direct!!
306  // It need be somehow inline expanded into the caller.
307  // -O does that. But need to support -O0 as well.
308  if (MD->isVirtual() && Type != Dtor_Base) {
309    // Compute the function type we're calling.
310    const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
311        DD, StructorType::Complete);
312    llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
313    return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
314  }
315  return nullptr;
316}
317