ItaniumCXXABI.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
  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 provides C++ code generation targeting the Itanium C++ ABI. The class
  11. // in this file generates structures that follow the Itanium C++ ABI, which is
  12. // documented at:
  13. // http://www.codesourcery.com/public/cxx-abi/abi.html
  14. // http://www.codesourcery.com/public/cxx-abi/abi-eh.html
  15. //
  16. // It also supports the closely-related ARM ABI, documented at:
  17. // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #include "CGCXXABI.h"
  21. #include "CGRecordLayout.h"
  22. #include "CodeGenFunction.h"
  23. #include "CodeGenModule.h"
  24. #include <clang/AST/Mangle.h>
  25. #include <clang/AST/Type.h>
  26. #include <llvm/Intrinsics.h>
  27. #include <llvm/Target/TargetData.h>
  28. #include <llvm/Value.h>
  29. using namespace clang;
  30. using namespace CodeGen;
  31. namespace {
  32. class ItaniumCXXABI : public CodeGen::CGCXXABI {
  33. private:
  34. llvm::IntegerType *PtrDiffTy;
  35. protected:
  36. bool IsARM;
  37. // It's a little silly for us to cache this.
  38. llvm::IntegerType *getPtrDiffTy() {
  39. if (!PtrDiffTy) {
  40. QualType T = getContext().getPointerDiffType();
  41. llvm::Type *Ty = CGM.getTypes().ConvertType(T);
  42. PtrDiffTy = cast<llvm::IntegerType>(Ty);
  43. }
  44. return PtrDiffTy;
  45. }
  46. bool NeedsArrayCookie(const CXXNewExpr *expr);
  47. bool NeedsArrayCookie(const CXXDeleteExpr *expr,
  48. QualType elementType);
  49. public:
  50. ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
  51. CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { }
  52. bool isZeroInitializable(const MemberPointerType *MPT);
  53. llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
  54. llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
  55. llvm::Value *&This,
  56. llvm::Value *MemFnPtr,
  57. const MemberPointerType *MPT);
  58. llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
  59. llvm::Value *Base,
  60. llvm::Value *MemPtr,
  61. const MemberPointerType *MPT);
  62. llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
  63. const CastExpr *E,
  64. llvm::Value *Src);
  65. llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
  66. llvm::Constant *Src);
  67. llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
  68. llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
  69. llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
  70. CharUnits offset);
  71. llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
  72. llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
  73. CharUnits ThisAdjustment);
  74. llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
  75. llvm::Value *L,
  76. llvm::Value *R,
  77. const MemberPointerType *MPT,
  78. bool Inequality);
  79. llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  80. llvm::Value *Addr,
  81. const MemberPointerType *MPT);
  82. void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
  83. CXXCtorType T,
  84. CanQualType &ResTy,
  85. SmallVectorImpl<CanQualType> &ArgTys);
  86. void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
  87. CXXDtorType T,
  88. CanQualType &ResTy,
  89. SmallVectorImpl<CanQualType> &ArgTys);
  90. void BuildInstanceFunctionParams(CodeGenFunction &CGF,
  91. QualType &ResTy,
  92. FunctionArgList &Params);
  93. void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
  94. CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
  95. llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
  96. llvm::Value *NewPtr,
  97. llvm::Value *NumElements,
  98. const CXXNewExpr *expr,
  99. QualType ElementType);
  100. void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
  101. const CXXDeleteExpr *expr,
  102. QualType ElementType, llvm::Value *&NumElements,
  103. llvm::Value *&AllocPtr, CharUnits &CookieSize);
  104. void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
  105. llvm::GlobalVariable *DeclPtr, bool PerformInit);
  106. };
  107. class ARMCXXABI : public ItaniumCXXABI {
  108. public:
  109. ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
  110. void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
  111. CXXCtorType T,
  112. CanQualType &ResTy,
  113. SmallVectorImpl<CanQualType> &ArgTys);
  114. void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
  115. CXXDtorType T,
  116. CanQualType &ResTy,
  117. SmallVectorImpl<CanQualType> &ArgTys);
  118. void BuildInstanceFunctionParams(CodeGenFunction &CGF,
  119. QualType &ResTy,
  120. FunctionArgList &Params);
  121. void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
  122. void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
  123. CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
  124. llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
  125. llvm::Value *NewPtr,
  126. llvm::Value *NumElements,
  127. const CXXNewExpr *expr,
  128. QualType ElementType);
  129. void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
  130. const CXXDeleteExpr *expr,
  131. QualType ElementType, llvm::Value *&NumElements,
  132. llvm::Value *&AllocPtr, CharUnits &CookieSize);
  133. private:
  134. /// \brief Returns true if the given instance method is one of the
  135. /// kinds that the ARM ABI says returns 'this'.
  136. static bool HasThisReturn(GlobalDecl GD) {
  137. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  138. return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
  139. (isa<CXXConstructorDecl>(MD)));
  140. }
  141. };
  142. }
  143. CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
  144. return new ItaniumCXXABI(CGM);
  145. }
  146. CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) {
  147. return new ARMCXXABI(CGM);
  148. }
  149. llvm::Type *
  150. ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
  151. if (MPT->isMemberDataPointer())
  152. return getPtrDiffTy();
  153. return llvm::StructType::get(getPtrDiffTy(), getPtrDiffTy(), NULL);
  154. }
  155. /// In the Itanium and ARM ABIs, method pointers have the form:
  156. /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
  157. ///
  158. /// In the Itanium ABI:
  159. /// - method pointers are virtual if (memptr.ptr & 1) is nonzero
  160. /// - the this-adjustment is (memptr.adj)
  161. /// - the virtual offset is (memptr.ptr - 1)
  162. ///
  163. /// In the ARM ABI:
  164. /// - method pointers are virtual if (memptr.adj & 1) is nonzero
  165. /// - the this-adjustment is (memptr.adj >> 1)
  166. /// - the virtual offset is (memptr.ptr)
  167. /// ARM uses 'adj' for the virtual flag because Thumb functions
  168. /// may be only single-byte aligned.
  169. ///
  170. /// If the member is virtual, the adjusted 'this' pointer points
  171. /// to a vtable pointer from which the virtual offset is applied.
  172. ///
  173. /// If the member is non-virtual, memptr.ptr is the address of
  174. /// the function to call.
  175. llvm::Value *
  176. ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
  177. llvm::Value *&This,
  178. llvm::Value *MemFnPtr,
  179. const MemberPointerType *MPT) {
  180. CGBuilderTy &Builder = CGF.Builder;
  181. const FunctionProtoType *FPT =
  182. MPT->getPointeeType()->getAs<FunctionProtoType>();
  183. const CXXRecordDecl *RD =
  184. cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
  185. llvm::FunctionType *FTy =
  186. CGM.getTypes().GetFunctionType(
  187. CGM.getTypes().arrangeCXXMethodType(RD, FPT));
  188. llvm::IntegerType *ptrdiff = getPtrDiffTy();
  189. llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
  190. llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
  191. llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
  192. llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
  193. // Extract memptr.adj, which is in the second field.
  194. llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
  195. // Compute the true adjustment.
  196. llvm::Value *Adj = RawAdj;
  197. if (IsARM)
  198. Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
  199. // Apply the adjustment and cast back to the original struct type
  200. // for consistency.
  201. llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
  202. Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
  203. This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
  204. // Load the function pointer.
  205. llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
  206. // If the LSB in the function pointer is 1, the function pointer points to
  207. // a virtual function.
  208. llvm::Value *IsVirtual;
  209. if (IsARM)
  210. IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
  211. else
  212. IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
  213. IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
  214. Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
  215. // In the virtual path, the adjustment left 'This' pointing to the
  216. // vtable of the correct base subobject. The "function pointer" is an
  217. // offset within the vtable (+1 for the virtual flag on non-ARM).
  218. CGF.EmitBlock(FnVirtual);
  219. // Cast the adjusted this to a pointer to vtable pointer and load.
  220. llvm::Type *VTableTy = Builder.getInt8PtrTy();
  221. llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
  222. VTable = Builder.CreateLoad(VTable, "memptr.vtable");
  223. // Apply the offset.
  224. llvm::Value *VTableOffset = FnAsInt;
  225. if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
  226. VTable = Builder.CreateGEP(VTable, VTableOffset);
  227. // Load the virtual function to call.
  228. VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
  229. llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
  230. CGF.EmitBranch(FnEnd);
  231. // In the non-virtual path, the function pointer is actually a
  232. // function pointer.
  233. CGF.EmitBlock(FnNonVirtual);
  234. llvm::Value *NonVirtualFn =
  235. Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
  236. // We're done.
  237. CGF.EmitBlock(FnEnd);
  238. llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
  239. Callee->addIncoming(VirtualFn, FnVirtual);
  240. Callee->addIncoming(NonVirtualFn, FnNonVirtual);
  241. return Callee;
  242. }
  243. /// Compute an l-value by applying the given pointer-to-member to a
  244. /// base object.
  245. llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
  246. llvm::Value *Base,
  247. llvm::Value *MemPtr,
  248. const MemberPointerType *MPT) {
  249. assert(MemPtr->getType() == getPtrDiffTy());
  250. CGBuilderTy &Builder = CGF.Builder;
  251. unsigned AS = cast<llvm::PointerType>(Base->getType())->getAddressSpace();
  252. // Cast to char*.
  253. Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
  254. // Apply the offset, which we assume is non-null.
  255. llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
  256. // Cast the address to the appropriate pointer type, adopting the
  257. // address space of the base pointer.
  258. llvm::Type *PType
  259. = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
  260. return Builder.CreateBitCast(Addr, PType);
  261. }
  262. /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
  263. /// conversion.
  264. ///
  265. /// Bitcast conversions are always a no-op under Itanium.
  266. ///
  267. /// Obligatory offset/adjustment diagram:
  268. /// <-- offset --> <-- adjustment -->
  269. /// |--------------------------|----------------------|--------------------|
  270. /// ^Derived address point ^Base address point ^Member address point
  271. ///
  272. /// So when converting a base member pointer to a derived member pointer,
  273. /// we add the offset to the adjustment because the address point has
  274. /// decreased; and conversely, when converting a derived MP to a base MP
  275. /// we subtract the offset from the adjustment because the address point
  276. /// has increased.
  277. ///
  278. /// The standard forbids (at compile time) conversion to and from
  279. /// virtual bases, which is why we don't have to consider them here.
  280. ///
  281. /// The standard forbids (at run time) casting a derived MP to a base
  282. /// MP when the derived MP does not point to a member of the base.
  283. /// This is why -1 is a reasonable choice for null data member
  284. /// pointers.
  285. llvm::Value *
  286. ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
  287. const CastExpr *E,
  288. llvm::Value *src) {
  289. assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
  290. E->getCastKind() == CK_BaseToDerivedMemberPointer ||
  291. E->getCastKind() == CK_ReinterpretMemberPointer);
  292. // Under Itanium, reinterprets don't require any additional processing.
  293. if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
  294. // Use constant emission if we can.
  295. if (isa<llvm::Constant>(src))
  296. return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
  297. llvm::Constant *adj = getMemberPointerAdjustment(E);
  298. if (!adj) return src;
  299. CGBuilderTy &Builder = CGF.Builder;
  300. bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
  301. const MemberPointerType *destTy =
  302. E->getType()->castAs<MemberPointerType>();
  303. // For member data pointers, this is just a matter of adding the
  304. // offset if the source is non-null.
  305. if (destTy->isMemberDataPointer()) {
  306. llvm::Value *dst;
  307. if (isDerivedToBase)
  308. dst = Builder.CreateNSWSub(src, adj, "adj");
  309. else
  310. dst = Builder.CreateNSWAdd(src, adj, "adj");
  311. // Null check.
  312. llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
  313. llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
  314. return Builder.CreateSelect(isNull, src, dst);
  315. }
  316. // The this-adjustment is left-shifted by 1 on ARM.
  317. if (IsARM) {
  318. uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
  319. offset <<= 1;
  320. adj = llvm::ConstantInt::get(adj->getType(), offset);
  321. }
  322. llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
  323. llvm::Value *dstAdj;
  324. if (isDerivedToBase)
  325. dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
  326. else
  327. dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
  328. return Builder.CreateInsertValue(src, dstAdj, 1);
  329. }
  330. llvm::Constant *
  331. ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
  332. llvm::Constant *src) {
  333. assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
  334. E->getCastKind() == CK_BaseToDerivedMemberPointer ||
  335. E->getCastKind() == CK_ReinterpretMemberPointer);
  336. // Under Itanium, reinterprets don't require any additional processing.
  337. if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
  338. // If the adjustment is trivial, we don't need to do anything.
  339. llvm::Constant *adj = getMemberPointerAdjustment(E);
  340. if (!adj) return src;
  341. bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
  342. const MemberPointerType *destTy =
  343. E->getType()->castAs<MemberPointerType>();
  344. // For member data pointers, this is just a matter of adding the
  345. // offset if the source is non-null.
  346. if (destTy->isMemberDataPointer()) {
  347. // null maps to null.
  348. if (src->isAllOnesValue()) return src;
  349. if (isDerivedToBase)
  350. return llvm::ConstantExpr::getNSWSub(src, adj);
  351. else
  352. return llvm::ConstantExpr::getNSWAdd(src, adj);
  353. }
  354. // The this-adjustment is left-shifted by 1 on ARM.
  355. if (IsARM) {
  356. uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
  357. offset <<= 1;
  358. adj = llvm::ConstantInt::get(adj->getType(), offset);
  359. }
  360. llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
  361. llvm::Constant *dstAdj;
  362. if (isDerivedToBase)
  363. dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
  364. else
  365. dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
  366. return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
  367. }
  368. llvm::Constant *
  369. ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
  370. llvm::Type *ptrdiff_t = getPtrDiffTy();
  371. // Itanium C++ ABI 2.3:
  372. // A NULL pointer is represented as -1.
  373. if (MPT->isMemberDataPointer())
  374. return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
  375. llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
  376. llvm::Constant *Values[2] = { Zero, Zero };
  377. return llvm::ConstantStruct::getAnon(Values);
  378. }
  379. llvm::Constant *
  380. ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
  381. CharUnits offset) {
  382. // Itanium C++ ABI 2.3:
  383. // A pointer to data member is an offset from the base address of
  384. // the class object containing it, represented as a ptrdiff_t
  385. return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity());
  386. }
  387. llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
  388. return BuildMemberPointer(MD, CharUnits::Zero());
  389. }
  390. llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
  391. CharUnits ThisAdjustment) {
  392. assert(MD->isInstance() && "Member function must not be static!");
  393. MD = MD->getCanonicalDecl();
  394. CodeGenTypes &Types = CGM.getTypes();
  395. llvm::Type *ptrdiff_t = getPtrDiffTy();
  396. // Get the function pointer (or index if this is a virtual function).
  397. llvm::Constant *MemPtr[2];
  398. if (MD->isVirtual()) {
  399. uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
  400. const ASTContext &Context = getContext();
  401. CharUnits PointerWidth =
  402. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  403. uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
  404. if (IsARM) {
  405. // ARM C++ ABI 3.2.1:
  406. // This ABI specifies that adj contains twice the this
  407. // adjustment, plus 1 if the member function is virtual. The
  408. // least significant bit of adj then makes exactly the same
  409. // discrimination as the least significant bit of ptr does for
  410. // Itanium.
  411. MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
  412. MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
  413. 2 * ThisAdjustment.getQuantity() + 1);
  414. } else {
  415. // Itanium C++ ABI 2.3:
  416. // For a virtual function, [the pointer field] is 1 plus the
  417. // virtual table offset (in bytes) of the function,
  418. // represented as a ptrdiff_t.
  419. MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
  420. MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
  421. ThisAdjustment.getQuantity());
  422. }
  423. } else {
  424. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  425. llvm::Type *Ty;
  426. // Check whether the function has a computable LLVM signature.
  427. if (Types.isFuncTypeConvertible(FPT)) {
  428. // The function has a computable LLVM signature; use the correct type.
  429. Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
  430. } else {
  431. // Use an arbitrary non-function type to tell GetAddrOfFunction that the
  432. // function type is incomplete.
  433. Ty = ptrdiff_t;
  434. }
  435. llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
  436. MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
  437. MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, (IsARM ? 2 : 1) *
  438. ThisAdjustment.getQuantity());
  439. }
  440. return llvm::ConstantStruct::getAnon(MemPtr);
  441. }
  442. llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
  443. QualType MPType) {
  444. const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
  445. const ValueDecl *MPD = MP.getMemberPointerDecl();
  446. if (!MPD)
  447. return EmitNullMemberPointer(MPT);
  448. // Compute the this-adjustment.
  449. CharUnits ThisAdjustment = CharUnits::Zero();
  450. ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
  451. bool DerivedMember = MP.isMemberPointerToDerivedMember();
  452. const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
  453. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  454. const CXXRecordDecl *Base = RD;
  455. const CXXRecordDecl *Derived = Path[I];
  456. if (DerivedMember)
  457. std::swap(Base, Derived);
  458. ThisAdjustment +=
  459. getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
  460. RD = Path[I];
  461. }
  462. if (DerivedMember)
  463. ThisAdjustment = -ThisAdjustment;
  464. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
  465. return BuildMemberPointer(MD, ThisAdjustment);
  466. CharUnits FieldOffset =
  467. getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
  468. return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
  469. }
  470. /// The comparison algorithm is pretty easy: the member pointers are
  471. /// the same if they're either bitwise identical *or* both null.
  472. ///
  473. /// ARM is different here only because null-ness is more complicated.
  474. llvm::Value *
  475. ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
  476. llvm::Value *L,
  477. llvm::Value *R,
  478. const MemberPointerType *MPT,
  479. bool Inequality) {
  480. CGBuilderTy &Builder = CGF.Builder;
  481. llvm::ICmpInst::Predicate Eq;
  482. llvm::Instruction::BinaryOps And, Or;
  483. if (Inequality) {
  484. Eq = llvm::ICmpInst::ICMP_NE;
  485. And = llvm::Instruction::Or;
  486. Or = llvm::Instruction::And;
  487. } else {
  488. Eq = llvm::ICmpInst::ICMP_EQ;
  489. And = llvm::Instruction::And;
  490. Or = llvm::Instruction::Or;
  491. }
  492. // Member data pointers are easy because there's a unique null
  493. // value, so it just comes down to bitwise equality.
  494. if (MPT->isMemberDataPointer())
  495. return Builder.CreateICmp(Eq, L, R);
  496. // For member function pointers, the tautologies are more complex.
  497. // The Itanium tautology is:
  498. // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
  499. // The ARM tautology is:
  500. // (L == R) <==> (L.ptr == R.ptr &&
  501. // (L.adj == R.adj ||
  502. // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
  503. // The inequality tautologies have exactly the same structure, except
  504. // applying De Morgan's laws.
  505. llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
  506. llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
  507. // This condition tests whether L.ptr == R.ptr. This must always be
  508. // true for equality to hold.
  509. llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
  510. // This condition, together with the assumption that L.ptr == R.ptr,
  511. // tests whether the pointers are both null. ARM imposes an extra
  512. // condition.
  513. llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
  514. llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
  515. // This condition tests whether L.adj == R.adj. If this isn't
  516. // true, the pointers are unequal unless they're both null.
  517. llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
  518. llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
  519. llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
  520. // Null member function pointers on ARM clear the low bit of Adj,
  521. // so the zero condition has to check that neither low bit is set.
  522. if (IsARM) {
  523. llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
  524. // Compute (l.adj | r.adj) & 1 and test it against zero.
  525. llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
  526. llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
  527. llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
  528. "cmp.or.adj");
  529. EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
  530. }
  531. // Tie together all our conditions.
  532. llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
  533. Result = Builder.CreateBinOp(And, PtrEq, Result,
  534. Inequality ? "memptr.ne" : "memptr.eq");
  535. return Result;
  536. }
  537. llvm::Value *
  538. ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  539. llvm::Value *MemPtr,
  540. const MemberPointerType *MPT) {
  541. CGBuilderTy &Builder = CGF.Builder;
  542. /// For member data pointers, this is just a check against -1.
  543. if (MPT->isMemberDataPointer()) {
  544. assert(MemPtr->getType() == getPtrDiffTy());
  545. llvm::Value *NegativeOne =
  546. llvm::Constant::getAllOnesValue(MemPtr->getType());
  547. return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
  548. }
  549. // In Itanium, a member function pointer is not null if 'ptr' is not null.
  550. llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
  551. llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
  552. llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
  553. // On ARM, a member function pointer is also non-null if the low bit of 'adj'
  554. // (the virtual bit) is set.
  555. if (IsARM) {
  556. llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
  557. llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
  558. llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
  559. llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
  560. "memptr.isvirtual");
  561. Result = Builder.CreateOr(Result, IsVirtual);
  562. }
  563. return Result;
  564. }
  565. /// The Itanium ABI requires non-zero initialization only for data
  566. /// member pointers, for which '0' is a valid offset.
  567. bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
  568. return MPT->getPointeeType()->isFunctionType();
  569. }
  570. /// The generic ABI passes 'this', plus a VTT if it's initializing a
  571. /// base subobject.
  572. void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
  573. CXXCtorType Type,
  574. CanQualType &ResTy,
  575. SmallVectorImpl<CanQualType> &ArgTys) {
  576. ASTContext &Context = getContext();
  577. // 'this' is already there.
  578. // Check if we need to add a VTT parameter (which has type void **).
  579. if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
  580. ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
  581. }
  582. /// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
  583. void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
  584. CXXCtorType Type,
  585. CanQualType &ResTy,
  586. SmallVectorImpl<CanQualType> &ArgTys) {
  587. ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
  588. ResTy = ArgTys[0];
  589. }
  590. /// The generic ABI passes 'this', plus a VTT if it's destroying a
  591. /// base subobject.
  592. void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
  593. CXXDtorType Type,
  594. CanQualType &ResTy,
  595. SmallVectorImpl<CanQualType> &ArgTys) {
  596. ASTContext &Context = getContext();
  597. // 'this' is already there.
  598. // Check if we need to add a VTT parameter (which has type void **).
  599. if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
  600. ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
  601. }
  602. /// The ARM ABI does the same as the Itanium ABI, but returns 'this'
  603. /// for non-deleting destructors.
  604. void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
  605. CXXDtorType Type,
  606. CanQualType &ResTy,
  607. SmallVectorImpl<CanQualType> &ArgTys) {
  608. ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
  609. if (Type != Dtor_Deleting)
  610. ResTy = ArgTys[0];
  611. }
  612. void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
  613. QualType &ResTy,
  614. FunctionArgList &Params) {
  615. /// Create the 'this' variable.
  616. BuildThisParam(CGF, Params);
  617. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
  618. assert(MD->isInstance());
  619. // Check if we need a VTT parameter as well.
  620. if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
  621. ASTContext &Context = getContext();
  622. // FIXME: avoid the fake decl
  623. QualType T = Context.getPointerType(Context.VoidPtrTy);
  624. ImplicitParamDecl *VTTDecl
  625. = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
  626. &Context.Idents.get("vtt"), T);
  627. Params.push_back(VTTDecl);
  628. getVTTDecl(CGF) = VTTDecl;
  629. }
  630. }
  631. void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
  632. QualType &ResTy,
  633. FunctionArgList &Params) {
  634. ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
  635. // Return 'this' from certain constructors and destructors.
  636. if (HasThisReturn(CGF.CurGD))
  637. ResTy = Params[0]->getType();
  638. }
  639. void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
  640. /// Initialize the 'this' slot.
  641. EmitThisParam(CGF);
  642. /// Initialize the 'vtt' slot if needed.
  643. if (getVTTDecl(CGF)) {
  644. getVTTValue(CGF)
  645. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
  646. "vtt");
  647. }
  648. }
  649. void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
  650. ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
  651. /// Initialize the return slot to 'this' at the start of the
  652. /// function.
  653. if (HasThisReturn(CGF.CurGD))
  654. CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
  655. }
  656. void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
  657. RValue RV, QualType ResultType) {
  658. if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
  659. return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
  660. // Destructor thunks in the ARM ABI have indeterminate results.
  661. llvm::Type *T =
  662. cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
  663. RValue Undef = RValue::get(llvm::UndefValue::get(T));
  664. return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
  665. }
  666. /************************** Array allocation cookies **************************/
  667. bool ItaniumCXXABI::NeedsArrayCookie(const CXXNewExpr *expr) {
  668. // If the class's usual deallocation function takes two arguments,
  669. // it needs a cookie.
  670. if (expr->doesUsualArrayDeleteWantSize())
  671. return true;
  672. // Automatic Reference Counting:
  673. // We need an array cookie for pointers with strong or weak lifetime.
  674. QualType AllocatedType = expr->getAllocatedType();
  675. if (getContext().getLangOptions().ObjCAutoRefCount &&
  676. AllocatedType->isObjCLifetimeType()) {
  677. switch (AllocatedType.getObjCLifetime()) {
  678. case Qualifiers::OCL_None:
  679. case Qualifiers::OCL_ExplicitNone:
  680. case Qualifiers::OCL_Autoreleasing:
  681. return false;
  682. case Qualifiers::OCL_Strong:
  683. case Qualifiers::OCL_Weak:
  684. return true;
  685. }
  686. }
  687. // Otherwise, if the class has a non-trivial destructor, it always
  688. // needs a cookie.
  689. const CXXRecordDecl *record =
  690. AllocatedType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  691. return (record && !record->hasTrivialDestructor());
  692. }
  693. bool ItaniumCXXABI::NeedsArrayCookie(const CXXDeleteExpr *expr,
  694. QualType elementType) {
  695. // If the class's usual deallocation function takes two arguments,
  696. // it needs a cookie.
  697. if (expr->doesUsualArrayDeleteWantSize())
  698. return true;
  699. return elementType.isDestructedType();
  700. }
  701. CharUnits ItaniumCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) {
  702. if (!NeedsArrayCookie(expr))
  703. return CharUnits::Zero();
  704. // Padding is the maximum of sizeof(size_t) and alignof(elementType)
  705. ASTContext &Ctx = getContext();
  706. return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
  707. Ctx.getTypeAlignInChars(expr->getAllocatedType()));
  708. }
  709. llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  710. llvm::Value *NewPtr,
  711. llvm::Value *NumElements,
  712. const CXXNewExpr *expr,
  713. QualType ElementType) {
  714. assert(NeedsArrayCookie(expr));
  715. unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
  716. ASTContext &Ctx = getContext();
  717. QualType SizeTy = Ctx.getSizeType();
  718. CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
  719. // The size of the cookie.
  720. CharUnits CookieSize =
  721. std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
  722. // Compute an offset to the cookie.
  723. llvm::Value *CookiePtr = NewPtr;
  724. CharUnits CookieOffset = CookieSize - SizeSize;
  725. if (!CookieOffset.isZero())
  726. CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
  727. CookieOffset.getQuantity());
  728. // Write the number of elements into the appropriate slot.
  729. llvm::Value *NumElementsPtr
  730. = CGF.Builder.CreateBitCast(CookiePtr,
  731. CGF.ConvertType(SizeTy)->getPointerTo(AS));
  732. CGF.Builder.CreateStore(NumElements, NumElementsPtr);
  733. // Finally, compute a pointer to the actual data buffer by skipping
  734. // over the cookie completely.
  735. return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
  736. CookieSize.getQuantity());
  737. }
  738. void ItaniumCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
  739. llvm::Value *Ptr,
  740. const CXXDeleteExpr *expr,
  741. QualType ElementType,
  742. llvm::Value *&NumElements,
  743. llvm::Value *&AllocPtr,
  744. CharUnits &CookieSize) {
  745. // Derive a char* in the same address space as the pointer.
  746. unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
  747. llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
  748. // If we don't need an array cookie, bail out early.
  749. if (!NeedsArrayCookie(expr, ElementType)) {
  750. AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
  751. NumElements = 0;
  752. CookieSize = CharUnits::Zero();
  753. return;
  754. }
  755. QualType SizeTy = getContext().getSizeType();
  756. CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
  757. llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
  758. CookieSize
  759. = std::max(SizeSize, getContext().getTypeAlignInChars(ElementType));
  760. CharUnits NumElementsOffset = CookieSize - SizeSize;
  761. // Compute the allocated pointer.
  762. AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
  763. AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
  764. -CookieSize.getQuantity());
  765. llvm::Value *NumElementsPtr = AllocPtr;
  766. if (!NumElementsOffset.isZero())
  767. NumElementsPtr =
  768. CGF.Builder.CreateConstInBoundsGEP1_64(NumElementsPtr,
  769. NumElementsOffset.getQuantity());
  770. NumElementsPtr =
  771. CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
  772. NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
  773. }
  774. CharUnits ARMCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) {
  775. if (!NeedsArrayCookie(expr))
  776. return CharUnits::Zero();
  777. // On ARM, the cookie is always:
  778. // struct array_cookie {
  779. // std::size_t element_size; // element_size != 0
  780. // std::size_t element_count;
  781. // };
  782. // TODO: what should we do if the allocated type actually wants
  783. // greater alignment?
  784. return getContext().getTypeSizeInChars(getContext().getSizeType()) * 2;
  785. }
  786. llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  787. llvm::Value *NewPtr,
  788. llvm::Value *NumElements,
  789. const CXXNewExpr *expr,
  790. QualType ElementType) {
  791. assert(NeedsArrayCookie(expr));
  792. // NewPtr is a char*.
  793. unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
  794. ASTContext &Ctx = getContext();
  795. CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType());
  796. llvm::IntegerType *SizeTy =
  797. cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType()));
  798. // The cookie is always at the start of the buffer.
  799. llvm::Value *CookiePtr = NewPtr;
  800. // The first element is the element size.
  801. CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS));
  802. llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy,
  803. Ctx.getTypeSizeInChars(ElementType).getQuantity());
  804. CGF.Builder.CreateStore(ElementSize, CookiePtr);
  805. // The second element is the element count.
  806. CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1);
  807. CGF.Builder.CreateStore(NumElements, CookiePtr);
  808. // Finally, compute a pointer to the actual data buffer by skipping
  809. // over the cookie completely.
  810. CharUnits CookieSize = 2 * SizeSize;
  811. return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
  812. CookieSize.getQuantity());
  813. }
  814. void ARMCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
  815. llvm::Value *Ptr,
  816. const CXXDeleteExpr *expr,
  817. QualType ElementType,
  818. llvm::Value *&NumElements,
  819. llvm::Value *&AllocPtr,
  820. CharUnits &CookieSize) {
  821. // Derive a char* in the same address space as the pointer.
  822. unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
  823. llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
  824. // If we don't need an array cookie, bail out early.
  825. if (!NeedsArrayCookie(expr, ElementType)) {
  826. AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
  827. NumElements = 0;
  828. CookieSize = CharUnits::Zero();
  829. return;
  830. }
  831. QualType SizeTy = getContext().getSizeType();
  832. CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
  833. llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
  834. // The cookie size is always 2 * sizeof(size_t).
  835. CookieSize = 2 * SizeSize;
  836. // The allocated pointer is the input ptr, minus that amount.
  837. AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
  838. AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
  839. -CookieSize.getQuantity());
  840. // The number of elements is at offset sizeof(size_t) relative to that.
  841. llvm::Value *NumElementsPtr
  842. = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
  843. SizeSize.getQuantity());
  844. NumElementsPtr =
  845. CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
  846. NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
  847. }
  848. /*********************** Static local initialization **************************/
  849. static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
  850. llvm::PointerType *GuardPtrTy) {
  851. // int __cxa_guard_acquire(__guard *guard_object);
  852. llvm::FunctionType *FTy =
  853. llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
  854. GuardPtrTy, /*isVarArg=*/false);
  855. return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
  856. llvm::Attribute::NoUnwind);
  857. }
  858. static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
  859. llvm::PointerType *GuardPtrTy) {
  860. // void __cxa_guard_release(__guard *guard_object);
  861. llvm::FunctionType *FTy =
  862. llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
  863. return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
  864. llvm::Attribute::NoUnwind);
  865. }
  866. static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
  867. llvm::PointerType *GuardPtrTy) {
  868. // void __cxa_guard_abort(__guard *guard_object);
  869. llvm::FunctionType *FTy =
  870. llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
  871. return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
  872. llvm::Attribute::NoUnwind);
  873. }
  874. namespace {
  875. struct CallGuardAbort : EHScopeStack::Cleanup {
  876. llvm::GlobalVariable *Guard;
  877. CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
  878. void Emit(CodeGenFunction &CGF, Flags flags) {
  879. CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
  880. ->setDoesNotThrow();
  881. }
  882. };
  883. }
  884. /// The ARM code here follows the Itanium code closely enough that we
  885. /// just special-case it at particular places.
  886. void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
  887. const VarDecl &D,
  888. llvm::GlobalVariable *GV,
  889. bool PerformInit) {
  890. CGBuilderTy &Builder = CGF.Builder;
  891. // We only need to use thread-safe statics for local variables;
  892. // global initialization is always single-threaded.
  893. bool threadsafe =
  894. (getContext().getLangOptions().ThreadsafeStatics && D.isLocalVarDecl());
  895. llvm::IntegerType *GuardTy;
  896. // If we have a global variable with internal linkage and thread-safe statics
  897. // are disabled, we can just let the guard variable be of type i8.
  898. bool useInt8GuardVariable = !threadsafe && GV->hasInternalLinkage();
  899. if (useInt8GuardVariable) {
  900. GuardTy = CGF.Int8Ty;
  901. } else {
  902. // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
  903. GuardTy = (IsARM ? CGF.Int32Ty : CGF.Int64Ty);
  904. }
  905. llvm::PointerType *GuardPtrTy = GuardTy->getPointerTo();
  906. // Create the guard variable.
  907. SmallString<256> GuardVName;
  908. llvm::raw_svector_ostream Out(GuardVName);
  909. getMangleContext().mangleItaniumGuardVariable(&D, Out);
  910. Out.flush();
  911. // Just absorb linkage and visibility from the variable.
  912. llvm::GlobalVariable *GuardVariable =
  913. new llvm::GlobalVariable(CGM.getModule(), GuardTy,
  914. false, GV->getLinkage(),
  915. llvm::ConstantInt::get(GuardTy, 0),
  916. GuardVName.str());
  917. GuardVariable->setVisibility(GV->getVisibility());
  918. // Test whether the variable has completed initialization.
  919. llvm::Value *IsInitialized;
  920. // ARM C++ ABI 3.2.3.1:
  921. // To support the potential use of initialization guard variables
  922. // as semaphores that are the target of ARM SWP and LDREX/STREX
  923. // synchronizing instructions we define a static initialization
  924. // guard variable to be a 4-byte aligned, 4- byte word with the
  925. // following inline access protocol.
  926. // #define INITIALIZED 1
  927. // if ((obj_guard & INITIALIZED) != INITIALIZED) {
  928. // if (__cxa_guard_acquire(&obj_guard))
  929. // ...
  930. // }
  931. if (IsARM && !useInt8GuardVariable) {
  932. llvm::Value *V = Builder.CreateLoad(GuardVariable);
  933. V = Builder.CreateAnd(V, Builder.getInt32(1));
  934. IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
  935. // Itanium C++ ABI 3.3.2:
  936. // The following is pseudo-code showing how these functions can be used:
  937. // if (obj_guard.first_byte == 0) {
  938. // if ( __cxa_guard_acquire (&obj_guard) ) {
  939. // try {
  940. // ... initialize the object ...;
  941. // } catch (...) {
  942. // __cxa_guard_abort (&obj_guard);
  943. // throw;
  944. // }
  945. // ... queue object destructor with __cxa_atexit() ...;
  946. // __cxa_guard_release (&obj_guard);
  947. // }
  948. // }
  949. } else {
  950. // Load the first byte of the guard variable.
  951. llvm::Type *PtrTy = Builder.getInt8PtrTy();
  952. llvm::LoadInst *LI =
  953. Builder.CreateLoad(Builder.CreateBitCast(GuardVariable, PtrTy));
  954. LI->setAlignment(1);
  955. // Itanium ABI:
  956. // An implementation supporting thread-safety on multiprocessor
  957. // systems must also guarantee that references to the initialized
  958. // object do not occur before the load of the initialization flag.
  959. //
  960. // In LLVM, we do this by marking the load Acquire.
  961. if (threadsafe)
  962. LI->setAtomic(llvm::Acquire);
  963. IsInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
  964. }
  965. llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
  966. llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
  967. // Check if the first byte of the guard variable is zero.
  968. Builder.CreateCondBr(IsInitialized, InitCheckBlock, EndBlock);
  969. CGF.EmitBlock(InitCheckBlock);
  970. // Variables used when coping with thread-safe statics and exceptions.
  971. if (threadsafe) {
  972. // Call __cxa_guard_acquire.
  973. llvm::Value *V
  974. = Builder.CreateCall(getGuardAcquireFn(CGM, GuardPtrTy), GuardVariable);
  975. llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
  976. Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
  977. InitBlock, EndBlock);
  978. // Call __cxa_guard_abort along the exceptional edge.
  979. CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, GuardVariable);
  980. CGF.EmitBlock(InitBlock);
  981. }
  982. // Emit the initializer and add a global destructor if appropriate.
  983. CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
  984. if (threadsafe) {
  985. // Pop the guard-abort cleanup if we pushed one.
  986. CGF.PopCleanupBlock();
  987. // Call __cxa_guard_release. This cannot throw.
  988. Builder.CreateCall(getGuardReleaseFn(CGM, GuardPtrTy), GuardVariable);
  989. } else {
  990. Builder.CreateStore(llvm::ConstantInt::get(GuardTy, 1), GuardVariable);
  991. }
  992. CGF.EmitBlock(EndBlock);
  993. }