CGCXX.cpp 14 KB

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