CGCXX.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code dealing with C++ code generation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. // We might split this into multiple files if it gets too unwieldy
  13. #include "CGCXXABI.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/Attr.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/Mangle.h"
  22. #include "clang/AST/RecordLayout.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/Basic/CodeGenOptions.h"
  25. #include "llvm/ADT/StringExtras.h"
  26. using namespace clang;
  27. using namespace CodeGen;
  28. /// Try to emit a base destructor as an alias to its primary
  29. /// base-class destructor.
  30. bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
  31. if (!getCodeGenOpts().CXXCtorDtorAliases)
  32. return true;
  33. // Producing an alias to a base class ctor/dtor can degrade debug quality
  34. // as the debugger cannot tell them apart.
  35. if (getCodeGenOpts().OptimizationLevel == 0)
  36. return true;
  37. // If sanitizing memory to check for use-after-dtor, do not emit as
  38. // an alias, unless this class owns no members.
  39. if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  40. !D->getParent()->field_empty())
  41. return true;
  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. const CXXRecordDecl *Class = D->getParent();
  47. // We are going to instrument this destructor, so give up even if it is
  48. // currently empty.
  49. if (Class->mayInsertExtraPadding())
  50. return true;
  51. // If we need to manipulate a VTT parameter, give up.
  52. if (Class->getNumVBases()) {
  53. // Extra Credit: passing extra parameters is perfectly safe
  54. // in many calling conventions, so only bail out if the ctor's
  55. // calling convention is nonstandard.
  56. return true;
  57. }
  58. // If any field has a non-trivial destructor, we have to emit the
  59. // destructor separately.
  60. for (const auto *I : Class->fields())
  61. if (I->getType().isDestructedType())
  62. return true;
  63. // Try to find a unique base class with a non-trivial destructor.
  64. const CXXRecordDecl *UniqueBase = nullptr;
  65. for (const auto &I : Class->bases()) {
  66. // We're in the base destructor, so skip virtual bases.
  67. if (I.isVirtual()) continue;
  68. // Skip base classes with trivial destructors.
  69. const auto *Base =
  70. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  71. if (Base->hasTrivialDestructor()) continue;
  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. // If we didn't find any bases with a non-trivial destructor, then
  78. // the base destructor is actually effectively trivial, which can
  79. // happen if it was needlessly user-defined or if there are virtual
  80. // bases with non-trivial destructors.
  81. if (!UniqueBase)
  82. return true;
  83. // If the base is at a non-zero offset, give up.
  84. const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
  85. if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
  86. return true;
  87. // Give up if the calling conventions don't match. We could update the call,
  88. // but it is probably not worth it.
  89. const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
  90. if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=
  91. D->getType()->castAs<FunctionType>()->getCallConv())
  92. return true;
  93. GlobalDecl AliasDecl(D, Dtor_Base);
  94. GlobalDecl TargetDecl(BaseD, Dtor_Base);
  95. // The alias will use the linkage of the referent. If we can't
  96. // support aliases with that linkage, fail.
  97. llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
  98. // We can't use an alias if the linkage is not valid for one.
  99. if (!llvm::GlobalAlias::isValidLinkage(Linkage))
  100. return true;
  101. llvm::GlobalValue::LinkageTypes TargetLinkage =
  102. getFunctionLinkage(TargetDecl);
  103. // Check if we have it already.
  104. StringRef MangledName = getMangledName(AliasDecl);
  105. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  106. if (Entry && !Entry->isDeclaration())
  107. return false;
  108. if (Replacements.count(MangledName))
  109. return false;
  110. // Derive the type for the alias.
  111. llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
  112. llvm::PointerType *AliasType = AliasValueType->getPointerTo();
  113. // Find the referent. Some aliases might require a bitcast, in
  114. // which case the caller is responsible for ensuring the soundness
  115. // of these semantics.
  116. auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
  117. llvm::Constant *Aliasee = Ref;
  118. if (Ref->getType() != AliasType)
  119. Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
  120. // Instead of creating as alias to a linkonce_odr, replace all of the uses
  121. // of the aliasee.
  122. if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
  123. !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&
  124. TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
  125. // FIXME: An extern template instantiation will create functions with
  126. // linkage "AvailableExternally". In libc++, some classes also define
  127. // members with attribute "AlwaysInline" and expect no reference to
  128. // be generated. It is desirable to reenable this optimisation after
  129. // corresponding LLVM changes.
  130. addReplacement(MangledName, Aliasee);
  131. return false;
  132. }
  133. // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
  134. // template instantiation or a dllexported class, avoid forming it on COFF.
  135. // A COFF weak external alias cannot satisfy a normal undefined symbol
  136. // reference from another TU. The other TU must also mark the referenced
  137. // symbol as weak, which we cannot rely on.
  138. if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
  139. getTriple().isOSBinFormatCOFF()) {
  140. return true;
  141. }
  142. // If we don't have a definition for the destructor yet or the definition is
  143. // avaialable_externally, don't emit an alias. We can't emit aliases to
  144. // declarations; that's just not how aliases work.
  145. if (Ref->isDeclarationForLinker())
  146. return true;
  147. // Don't create an alias to a linker weak symbol. This avoids producing
  148. // different COMDATs in different TUs. Another option would be to
  149. // output the alias both for weak_odr and linkonce_odr, but that
  150. // requires explicit comdat support in the IL.
  151. if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
  152. return true;
  153. // Create the alias with no name.
  154. auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
  155. Aliasee, &getModule());
  156. // Destructors are always unnamed_addr.
  157. Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  158. // Switch any previous uses to the alias.
  159. if (Entry) {
  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. // Finally, set up the alias with its proper name and attributes.
  169. SetCommonAttributes(AliasDecl, Alias);
  170. return false;
  171. }
  172. llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {
  173. const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);
  174. auto *Fn = cast<llvm::Function>(
  175. getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,
  176. /*DontDefer=*/true, ForDefinition));
  177. setFunctionLinkage(GD, Fn);
  178. CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
  179. setNonAliasAttributes(GD, Fn);
  180. SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);
  181. return Fn;
  182. }
  183. llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(
  184. GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,
  185. bool DontDefer, ForDefinition_t IsForDefinition) {
  186. auto *MD = cast<CXXMethodDecl>(GD.getDecl());
  187. if (isa<CXXDestructorDecl>(MD)) {
  188. // Always alias equivalent complete destructors to base destructors in the
  189. // MS ABI.
  190. if (getTarget().getCXXABI().isMicrosoft() &&
  191. GD.getDtorType() == Dtor_Complete &&
  192. MD->getParent()->getNumVBases() == 0)
  193. GD = GD.getWithDtorType(Dtor_Base);
  194. }
  195. if (!FnType) {
  196. if (!FnInfo)
  197. FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);
  198. FnType = getTypes().GetFunctionType(*FnInfo);
  199. }
  200. llvm::Constant *Ptr = GetOrCreateLLVMFunction(
  201. getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
  202. /*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
  203. return {FnType, Ptr};
  204. }
  205. static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,
  206. GlobalDecl GD,
  207. llvm::Type *Ty,
  208. const CXXRecordDecl *RD) {
  209. assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
  210. "No kext in Microsoft ABI");
  211. CodeGenModule &CGM = CGF.CGM;
  212. llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
  213. Ty = Ty->getPointerTo();
  214. VTable = CGF.Builder.CreateBitCast(VTable, Ty->getPointerTo());
  215. assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
  216. uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
  217. const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
  218. VTableLayout::AddressPointLocation AddressPoint =
  219. VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
  220. VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
  221. AddressPoint.AddressPointIndex;
  222. llvm::Value *VFuncPtr =
  223. CGF.Builder.CreateConstInBoundsGEP1_64(Ty, VTable, VTableIndex, "vfnkxt");
  224. llvm::Value *VFunc = CGF.Builder.CreateAlignedLoad(
  225. Ty, VFuncPtr, llvm::Align(CGF.PointerAlignInBytes));
  226. CGCallee Callee(GD, VFunc);
  227. return Callee;
  228. }
  229. /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
  230. /// indirect call to virtual functions. It makes the call through indexing
  231. /// into the vtable.
  232. CGCallee
  233. CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  234. NestedNameSpecifier *Qual,
  235. llvm::Type *Ty) {
  236. assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
  237. "BuildAppleKextVirtualCall - bad Qual kind");
  238. const Type *QTy = Qual->getAsType();
  239. QualType T = QualType(QTy, 0);
  240. const RecordType *RT = T->getAs<RecordType>();
  241. assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
  242. const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
  243. if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
  244. return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
  245. return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
  246. }
  247. /// BuildVirtualCall - This routine makes indirect vtable call for
  248. /// call to virtual destructors. It returns 0 if it could not do it.
  249. CGCallee
  250. CodeGenFunction::BuildAppleKextVirtualDestructorCall(
  251. const CXXDestructorDecl *DD,
  252. CXXDtorType Type,
  253. const CXXRecordDecl *RD) {
  254. assert(DD->isVirtual() && Type != Dtor_Base);
  255. // Compute the function type we're calling.
  256. const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
  257. GlobalDecl(DD, Dtor_Complete));
  258. llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
  259. return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
  260. }