blob: 9fce392352de5781a9d94da3de1b30e206cb049f [file] [log] [blame]
Charles Davis3a811f12010-05-25 19:52:27 +00001//===------- 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//
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis3a811f12010-05-25 19:52:27 +000011// 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
John McCallee79a4c2010-08-21 22:46:04 +000015//
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//
Charles Davis3a811f12010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
John McCall0bab0cd2010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davis9ee494f2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall93d557b2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis3a811f12010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Craig Topperba77cb92012-09-15 18:47:51 +000026#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Value.h"
Charles Davis3a811f12010-05-25 19:52:27 +000031
32using namespace clang;
John McCall93d557b2010-08-22 00:05:51 +000033using namespace CodeGen;
Charles Davis3a811f12010-05-25 19:52:27 +000034
35namespace {
Charles Davis071cc7d2010-08-16 03:33:14 +000036class ItaniumCXXABI : public CodeGen::CGCXXABI {
John McCall0bab0cd2010-08-23 01:21:21 +000037private:
Chris Lattner9cbe4f02011-07-09 17:41:47 +000038 llvm::IntegerType *PtrDiffTy;
John McCall93d557b2010-08-22 00:05:51 +000039protected:
John McCallbabc9a92010-08-22 00:59:17 +000040 bool IsARM;
John McCall0bab0cd2010-08-23 01:21:21 +000041
42 // It's a little silly for us to cache this.
Chris Lattner9cbe4f02011-07-09 17:41:47 +000043 llvm::IntegerType *getPtrDiffTy() {
John McCall0bab0cd2010-08-23 01:21:21 +000044 if (!PtrDiffTy) {
John McCall9cb2cee2010-09-02 10:25:57 +000045 QualType T = getContext().getPointerDiffType();
Chris Lattner9cbe4f02011-07-09 17:41:47 +000046 llvm::Type *Ty = CGM.getTypes().ConvertType(T);
John McCall0bab0cd2010-08-23 01:21:21 +000047 PtrDiffTy = cast<llvm::IntegerType>(Ty);
48 }
49 return PtrDiffTy;
50 }
51
Charles Davis3a811f12010-05-25 19:52:27 +000052public:
John McCallbabc9a92010-08-22 00:59:17 +000053 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
Peter Collingbourne14110472011-01-13 18:57:25 +000054 CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { }
John McCall93d557b2010-08-22 00:05:51 +000055
John McCallf16aa102010-08-22 21:01:12 +000056 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000057
Chris Lattner9cbe4f02011-07-09 17:41:47 +000058 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000059
John McCall93d557b2010-08-22 00:05:51 +000060 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
61 llvm::Value *&This,
62 llvm::Value *MemFnPtr,
63 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000064
John McCall6c2ab1d2010-08-31 21:07:20 +000065 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
66 llvm::Value *Base,
67 llvm::Value *MemPtr,
68 const MemberPointerType *MPT);
69
John McCall0bab0cd2010-08-23 01:21:21 +000070 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
71 const CastExpr *E,
72 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000073 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
74 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000075
John McCall0bab0cd2010-08-23 01:21:21 +000076 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000077
John McCall755d8492011-04-12 00:42:48 +000078 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000079 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
80 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000081 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
82 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
83 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000084
John McCall0bab0cd2010-08-23 01:21:21 +000085 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
86 llvm::Value *L,
87 llvm::Value *R,
88 const MemberPointerType *MPT,
89 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000090
John McCall0bab0cd2010-08-23 01:21:21 +000091 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
92 llvm::Value *Addr,
93 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000094
John McCallecd03b42012-09-25 10:10:39 +000095 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
96 llvm::Value *ptr,
97 QualType type);
98
John McCall4c40d982010-08-31 07:33:07 +000099 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
100 CXXCtorType T,
101 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000102 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000103
104 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
105 CXXDtorType T,
106 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000107 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000108
109 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
110 QualType &ResTy,
111 FunctionArgList &Params);
112
113 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000114
Joao Matos285baac2012-07-17 17:10:11 +0000115 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000116 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000117
John McCalle2b45e22012-05-01 05:23:51 +0000118 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000119 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
120 llvm::Value *NewPtr,
121 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000122 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000123 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000124 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
125 llvm::Value *allocPtr,
126 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000127
John McCall3030eb82010-11-06 09:44:32 +0000128 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000129 llvm::GlobalVariable *DeclPtr, bool PerformInit);
John McCall20bb1752012-05-01 06:13:13 +0000130 void registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor,
131 llvm::Constant *addr);
Charles Davis3a811f12010-05-25 19:52:27 +0000132};
John McCallee79a4c2010-08-21 22:46:04 +0000133
134class ARMCXXABI : public ItaniumCXXABI {
135public:
John McCallbabc9a92010-08-22 00:59:17 +0000136 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000137
138 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
139 CXXCtorType T,
140 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000141 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000142
143 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
144 CXXDtorType T,
145 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000146 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000147
148 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
149 QualType &ResTy,
150 FunctionArgList &Params);
151
152 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
153
154 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
155
John McCalle2b45e22012-05-01 05:23:51 +0000156 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000157 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
158 llvm::Value *NewPtr,
159 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000160 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000161 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000162 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
163 CharUnits cookieSize);
John McCall4c40d982010-08-31 07:33:07 +0000164
165private:
166 /// \brief Returns true if the given instance method is one of the
167 /// kinds that the ARM ABI says returns 'this'.
168 static bool HasThisReturn(GlobalDecl GD) {
169 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
170 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
171 (isa<CXXConstructorDecl>(MD)));
172 }
John McCallee79a4c2010-08-21 22:46:04 +0000173};
Charles Davis3a811f12010-05-25 19:52:27 +0000174}
175
Charles Davis071cc7d2010-08-16 03:33:14 +0000176CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
Charles Davis3a811f12010-05-25 19:52:27 +0000177 return new ItaniumCXXABI(CGM);
178}
179
John McCallee79a4c2010-08-21 22:46:04 +0000180CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) {
181 return new ARMCXXABI(CGM);
182}
183
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000184llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000185ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
186 if (MPT->isMemberDataPointer())
187 return getPtrDiffTy();
Chris Lattner7650d952011-06-18 22:49:11 +0000188 return llvm::StructType::get(getPtrDiffTy(), getPtrDiffTy(), NULL);
John McCall875ab102010-08-22 06:43:33 +0000189}
190
John McCallbabc9a92010-08-22 00:59:17 +0000191/// In the Itanium and ARM ABIs, method pointers have the form:
192/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
193///
194/// In the Itanium ABI:
195/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
196/// - the this-adjustment is (memptr.adj)
197/// - the virtual offset is (memptr.ptr - 1)
198///
199/// In the ARM ABI:
200/// - method pointers are virtual if (memptr.adj & 1) is nonzero
201/// - the this-adjustment is (memptr.adj >> 1)
202/// - the virtual offset is (memptr.ptr)
203/// ARM uses 'adj' for the virtual flag because Thumb functions
204/// may be only single-byte aligned.
205///
206/// If the member is virtual, the adjusted 'this' pointer points
207/// to a vtable pointer from which the virtual offset is applied.
208///
209/// If the member is non-virtual, memptr.ptr is the address of
210/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000211llvm::Value *
212ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
213 llvm::Value *&This,
214 llvm::Value *MemFnPtr,
215 const MemberPointerType *MPT) {
216 CGBuilderTy &Builder = CGF.Builder;
217
218 const FunctionProtoType *FPT =
219 MPT->getPointeeType()->getAs<FunctionProtoType>();
220 const CXXRecordDecl *RD =
221 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
222
Chris Lattner2acc6e32011-07-18 04:24:23 +0000223 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000224 CGM.getTypes().GetFunctionType(
225 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000226
Chris Lattner2acc6e32011-07-18 04:24:23 +0000227 llvm::IntegerType *ptrdiff = getPtrDiffTy();
John McCallbabc9a92010-08-22 00:59:17 +0000228 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
John McCall93d557b2010-08-22 00:05:51 +0000229
John McCallbabc9a92010-08-22 00:59:17 +0000230 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
231 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
232 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
233
John McCalld608cdb2010-08-22 10:59:02 +0000234 // Extract memptr.adj, which is in the second field.
235 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000236
237 // Compute the true adjustment.
238 llvm::Value *Adj = RawAdj;
239 if (IsARM)
240 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000241
242 // Apply the adjustment and cast back to the original struct type
243 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000244 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
245 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
246 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000247
248 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000249 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000250
251 // If the LSB in the function pointer is 1, the function pointer points to
252 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000253 llvm::Value *IsVirtual;
254 if (IsARM)
255 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
256 else
257 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
258 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000259 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
260
261 // In the virtual path, the adjustment left 'This' pointing to the
262 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000263 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000264 CGF.EmitBlock(FnVirtual);
265
266 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000267 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000268 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000269 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000270
271 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000272 llvm::Value *VTableOffset = FnAsInt;
273 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
274 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000275
276 // Load the virtual function to call.
277 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000278 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000279 CGF.EmitBranch(FnEnd);
280
281 // In the non-virtual path, the function pointer is actually a
282 // function pointer.
283 CGF.EmitBlock(FnNonVirtual);
284 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000285 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000286
287 // We're done.
288 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000289 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000290 Callee->addIncoming(VirtualFn, FnVirtual);
291 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
292 return Callee;
293}
John McCall3023def2010-08-22 03:04:22 +0000294
John McCall6c2ab1d2010-08-31 21:07:20 +0000295/// Compute an l-value by applying the given pointer-to-member to a
296/// base object.
297llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
298 llvm::Value *Base,
299 llvm::Value *MemPtr,
300 const MemberPointerType *MPT) {
301 assert(MemPtr->getType() == getPtrDiffTy());
302
303 CGBuilderTy &Builder = CGF.Builder;
304
Micah Villmow956a5a12012-10-25 15:39:14 +0000305 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000306
307 // Cast to char*.
308 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
309
310 // Apply the offset, which we assume is non-null.
311 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
312
313 // Cast the address to the appropriate pointer type, adopting the
314 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000315 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000316 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000317 return Builder.CreateBitCast(Addr, PType);
318}
319
John McCall4d4e5c12012-02-15 01:22:51 +0000320/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
321/// conversion.
322///
323/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000324///
325/// Obligatory offset/adjustment diagram:
326/// <-- offset --> <-- adjustment -->
327/// |--------------------------|----------------------|--------------------|
328/// ^Derived address point ^Base address point ^Member address point
329///
330/// So when converting a base member pointer to a derived member pointer,
331/// we add the offset to the adjustment because the address point has
332/// decreased; and conversely, when converting a derived MP to a base MP
333/// we subtract the offset from the adjustment because the address point
334/// has increased.
335///
336/// The standard forbids (at compile time) conversion to and from
337/// virtual bases, which is why we don't have to consider them here.
338///
339/// The standard forbids (at run time) casting a derived MP to a base
340/// MP when the derived MP does not point to a member of the base.
341/// This is why -1 is a reasonable choice for null data member
342/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000343llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000344ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
345 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000346 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000347 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000348 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
349 E->getCastKind() == CK_ReinterpretMemberPointer);
350
351 // Under Itanium, reinterprets don't require any additional processing.
352 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
353
354 // Use constant emission if we can.
355 if (isa<llvm::Constant>(src))
356 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
357
358 llvm::Constant *adj = getMemberPointerAdjustment(E);
359 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000360
361 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000362 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000363
John McCall4d4e5c12012-02-15 01:22:51 +0000364 const MemberPointerType *destTy =
365 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000366
John McCall0bab0cd2010-08-23 01:21:21 +0000367 // For member data pointers, this is just a matter of adding the
368 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000369 if (destTy->isMemberDataPointer()) {
370 llvm::Value *dst;
371 if (isDerivedToBase)
372 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000373 else
John McCall4d4e5c12012-02-15 01:22:51 +0000374 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000375
376 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000377 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
378 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
379 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000380 }
381
John McCalld608cdb2010-08-22 10:59:02 +0000382 // The this-adjustment is left-shifted by 1 on ARM.
383 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000384 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
385 offset <<= 1;
386 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000387 }
388
John McCall4d4e5c12012-02-15 01:22:51 +0000389 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
390 llvm::Value *dstAdj;
391 if (isDerivedToBase)
392 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000393 else
John McCall4d4e5c12012-02-15 01:22:51 +0000394 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000395
John McCall4d4e5c12012-02-15 01:22:51 +0000396 return Builder.CreateInsertValue(src, dstAdj, 1);
397}
398
399llvm::Constant *
400ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
401 llvm::Constant *src) {
402 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
403 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
404 E->getCastKind() == CK_ReinterpretMemberPointer);
405
406 // Under Itanium, reinterprets don't require any additional processing.
407 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
408
409 // If the adjustment is trivial, we don't need to do anything.
410 llvm::Constant *adj = getMemberPointerAdjustment(E);
411 if (!adj) return src;
412
413 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
414
415 const MemberPointerType *destTy =
416 E->getType()->castAs<MemberPointerType>();
417
418 // For member data pointers, this is just a matter of adding the
419 // offset if the source is non-null.
420 if (destTy->isMemberDataPointer()) {
421 // null maps to null.
422 if (src->isAllOnesValue()) return src;
423
424 if (isDerivedToBase)
425 return llvm::ConstantExpr::getNSWSub(src, adj);
426 else
427 return llvm::ConstantExpr::getNSWAdd(src, adj);
428 }
429
430 // The this-adjustment is left-shifted by 1 on ARM.
431 if (IsARM) {
432 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
433 offset <<= 1;
434 adj = llvm::ConstantInt::get(adj->getType(), offset);
435 }
436
437 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
438 llvm::Constant *dstAdj;
439 if (isDerivedToBase)
440 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
441 else
442 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
443
444 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000445}
John McCallcf2c85e2010-08-22 04:16:24 +0000446
447llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000448ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000449 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCall0bab0cd2010-08-23 01:21:21 +0000450
451 // Itanium C++ ABI 2.3:
452 // A NULL pointer is represented as -1.
453 if (MPT->isMemberDataPointer())
454 return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000455
456 llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
457 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000458 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000459}
460
John McCall5808ce42011-02-03 08:15:49 +0000461llvm::Constant *
462ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
463 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000464 // Itanium C++ ABI 2.3:
465 // A pointer to data member is an offset from the base address of
466 // the class object containing it, represented as a ptrdiff_t
John McCall5808ce42011-02-03 08:15:49 +0000467 return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000468}
469
John McCall755d8492011-04-12 00:42:48 +0000470llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000471 return BuildMemberPointer(MD, CharUnits::Zero());
472}
473
474llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
475 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000476 assert(MD->isInstance() && "Member function must not be static!");
477 MD = MD->getCanonicalDecl();
478
479 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000480 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCalld608cdb2010-08-22 10:59:02 +0000481
482 // Get the function pointer (or index if this is a virtual function).
483 llvm::Constant *MemPtr[2];
484 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000485 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000486
Ken Dyck1246ba62011-04-09 01:30:02 +0000487 const ASTContext &Context = getContext();
488 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000489 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000490 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000491
492 if (IsARM) {
493 // ARM C++ ABI 3.2.1:
494 // This ABI specifies that adj contains twice the this
495 // adjustment, plus 1 if the member function is virtual. The
496 // least significant bit of adj then makes exactly the same
497 // discrimination as the least significant bit of ptr does for
498 // Itanium.
499 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
Richard Smith2d6a5672012-01-14 04:30:29 +0000500 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
501 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000502 } else {
503 // Itanium C++ ABI 2.3:
504 // For a virtual function, [the pointer field] is 1 plus the
505 // virtual table offset (in bytes) of the function,
506 // represented as a ptrdiff_t.
507 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
Richard Smith2d6a5672012-01-14 04:30:29 +0000508 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
509 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000510 }
511 } else {
John McCall755d8492011-04-12 00:42:48 +0000512 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000513 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000514 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000515 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000516 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000517 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000518 } else {
John McCall755d8492011-04-12 00:42:48 +0000519 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
520 // function type is incomplete.
521 Ty = ptrdiff_t;
John McCalld608cdb2010-08-22 10:59:02 +0000522 }
John McCall755d8492011-04-12 00:42:48 +0000523 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000524
John McCall379b5152011-04-11 07:02:50 +0000525 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
Richard Smith2d6a5672012-01-14 04:30:29 +0000526 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, (IsARM ? 2 : 1) *
527 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000528 }
John McCall875ab102010-08-22 06:43:33 +0000529
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000530 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000531}
532
Richard Smith2d6a5672012-01-14 04:30:29 +0000533llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
534 QualType MPType) {
535 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
536 const ValueDecl *MPD = MP.getMemberPointerDecl();
537 if (!MPD)
538 return EmitNullMemberPointer(MPT);
539
540 // Compute the this-adjustment.
541 CharUnits ThisAdjustment = CharUnits::Zero();
542 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
543 bool DerivedMember = MP.isMemberPointerToDerivedMember();
544 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
545 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
546 const CXXRecordDecl *Base = RD;
547 const CXXRecordDecl *Derived = Path[I];
548 if (DerivedMember)
549 std::swap(Base, Derived);
550 ThisAdjustment +=
551 getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
552 RD = Path[I];
553 }
554 if (DerivedMember)
555 ThisAdjustment = -ThisAdjustment;
556
557 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
558 return BuildMemberPointer(MD, ThisAdjustment);
559
560 CharUnits FieldOffset =
561 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
562 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
563}
564
John McCalle9fd7eb2010-08-22 08:30:07 +0000565/// The comparison algorithm is pretty easy: the member pointers are
566/// the same if they're either bitwise identical *or* both null.
567///
568/// ARM is different here only because null-ness is more complicated.
569llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000570ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
571 llvm::Value *L,
572 llvm::Value *R,
573 const MemberPointerType *MPT,
574 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000575 CGBuilderTy &Builder = CGF.Builder;
576
John McCalle9fd7eb2010-08-22 08:30:07 +0000577 llvm::ICmpInst::Predicate Eq;
578 llvm::Instruction::BinaryOps And, Or;
579 if (Inequality) {
580 Eq = llvm::ICmpInst::ICMP_NE;
581 And = llvm::Instruction::Or;
582 Or = llvm::Instruction::And;
583 } else {
584 Eq = llvm::ICmpInst::ICMP_EQ;
585 And = llvm::Instruction::And;
586 Or = llvm::Instruction::Or;
587 }
588
John McCall0bab0cd2010-08-23 01:21:21 +0000589 // Member data pointers are easy because there's a unique null
590 // value, so it just comes down to bitwise equality.
591 if (MPT->isMemberDataPointer())
592 return Builder.CreateICmp(Eq, L, R);
593
594 // For member function pointers, the tautologies are more complex.
595 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000596 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000597 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000598 // (L == R) <==> (L.ptr == R.ptr &&
599 // (L.adj == R.adj ||
600 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000601 // The inequality tautologies have exactly the same structure, except
602 // applying De Morgan's laws.
603
604 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
605 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
606
John McCalle9fd7eb2010-08-22 08:30:07 +0000607 // This condition tests whether L.ptr == R.ptr. This must always be
608 // true for equality to hold.
609 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
610
611 // This condition, together with the assumption that L.ptr == R.ptr,
612 // tests whether the pointers are both null. ARM imposes an extra
613 // condition.
614 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
615 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
616
617 // This condition tests whether L.adj == R.adj. If this isn't
618 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000619 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
620 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000621 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
622
623 // Null member function pointers on ARM clear the low bit of Adj,
624 // so the zero condition has to check that neither low bit is set.
625 if (IsARM) {
626 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
627
628 // Compute (l.adj | r.adj) & 1 and test it against zero.
629 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
630 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
631 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
632 "cmp.or.adj");
633 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
634 }
635
636 // Tie together all our conditions.
637 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
638 Result = Builder.CreateBinOp(And, PtrEq, Result,
639 Inequality ? "memptr.ne" : "memptr.eq");
640 return Result;
641}
642
643llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000644ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
645 llvm::Value *MemPtr,
646 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000647 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000648
649 /// For member data pointers, this is just a check against -1.
650 if (MPT->isMemberDataPointer()) {
651 assert(MemPtr->getType() == getPtrDiffTy());
652 llvm::Value *NegativeOne =
653 llvm::Constant::getAllOnesValue(MemPtr->getType());
654 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
655 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000656
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000657 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000658 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000659
660 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
661 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
662
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000663 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
664 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000665 if (IsARM) {
666 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000667 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000668 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000669 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
670 "memptr.isvirtual");
671 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000672 }
673
674 return Result;
675}
John McCall875ab102010-08-22 06:43:33 +0000676
John McCallf16aa102010-08-22 21:01:12 +0000677/// The Itanium ABI requires non-zero initialization only for data
678/// member pointers, for which '0' is a valid offset.
679bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
680 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000681}
John McCall4c40d982010-08-31 07:33:07 +0000682
John McCallecd03b42012-09-25 10:10:39 +0000683/// The Itanium ABI always places an offset to the complete object
684/// at entry -2 in the vtable.
685llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
686 llvm::Value *ptr,
687 QualType type) {
688 // Grab the vtable pointer as an intptr_t*.
689 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
690
691 // Track back to entry -2 and pull out the offset there.
692 llvm::Value *offsetPtr =
693 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
694 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
695 offset->setAlignment(CGF.PointerAlignInBytes);
696
697 // Apply the offset.
698 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
699 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
700}
701
John McCall4c40d982010-08-31 07:33:07 +0000702/// The generic ABI passes 'this', plus a VTT if it's initializing a
703/// base subobject.
704void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
705 CXXCtorType Type,
706 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000707 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000708 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000709
710 // 'this' is already there.
711
712 // Check if we need to add a VTT parameter (which has type void **).
713 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
714 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
715}
716
717/// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
718void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
719 CXXCtorType Type,
720 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000721 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000722 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
723 ResTy = ArgTys[0];
724}
725
726/// The generic ABI passes 'this', plus a VTT if it's destroying a
727/// base subobject.
728void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
729 CXXDtorType Type,
730 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000731 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000732 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000733
734 // 'this' is already there.
735
736 // Check if we need to add a VTT parameter (which has type void **).
737 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
738 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
739}
740
741/// The ARM ABI does the same as the Itanium ABI, but returns 'this'
742/// for non-deleting destructors.
743void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
744 CXXDtorType Type,
745 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000746 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000747 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
748
749 if (Type != Dtor_Deleting)
750 ResTy = ArgTys[0];
751}
752
753void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
754 QualType &ResTy,
755 FunctionArgList &Params) {
756 /// Create the 'this' variable.
757 BuildThisParam(CGF, Params);
758
759 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
760 assert(MD->isInstance());
761
762 // Check if we need a VTT parameter as well.
763 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000764 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000765
766 // FIXME: avoid the fake decl
767 QualType T = Context.getPointerType(Context.VoidPtrTy);
768 ImplicitParamDecl *VTTDecl
769 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
770 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000771 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000772 getVTTDecl(CGF) = VTTDecl;
773 }
774}
775
776void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
777 QualType &ResTy,
778 FunctionArgList &Params) {
779 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
780
781 // Return 'this' from certain constructors and destructors.
782 if (HasThisReturn(CGF.CurGD))
John McCalld26bc762011-03-09 04:27:21 +0000783 ResTy = Params[0]->getType();
John McCall4c40d982010-08-31 07:33:07 +0000784}
785
786void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
787 /// Initialize the 'this' slot.
788 EmitThisParam(CGF);
789
790 /// Initialize the 'vtt' slot if needed.
791 if (getVTTDecl(CGF)) {
792 getVTTValue(CGF)
793 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
794 "vtt");
795 }
796}
797
798void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
799 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
800
801 /// Initialize the return slot to 'this' at the start of the
802 /// function.
803 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000804 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000805}
806
807void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
808 RValue RV, QualType ResultType) {
809 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
810 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
811
812 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000813 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000814 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
815 RValue Undef = RValue::get(llvm::UndefValue::get(T));
816 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
817}
John McCall1e7fe752010-09-02 09:58:18 +0000818
819/************************** Array allocation cookies **************************/
820
John McCalle2b45e22012-05-01 05:23:51 +0000821CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
822 // The array cookie is a size_t; pad that up to the element alignment.
823 // The cookie is actually right-justified in that space.
824 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
825 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000826}
827
828llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
829 llvm::Value *NewPtr,
830 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000831 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000832 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000833 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000834
Micah Villmow956a5a12012-10-25 15:39:14 +0000835 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000836
John McCall9cb2cee2010-09-02 10:25:57 +0000837 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000838 QualType SizeTy = Ctx.getSizeType();
839 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
840
841 // The size of the cookie.
842 CharUnits CookieSize =
843 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000844 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000845
846 // Compute an offset to the cookie.
847 llvm::Value *CookiePtr = NewPtr;
848 CharUnits CookieOffset = CookieSize - SizeSize;
849 if (!CookieOffset.isZero())
850 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
851 CookieOffset.getQuantity());
852
853 // Write the number of elements into the appropriate slot.
854 llvm::Value *NumElementsPtr
855 = CGF.Builder.CreateBitCast(CookiePtr,
856 CGF.ConvertType(SizeTy)->getPointerTo(AS));
857 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
858
859 // Finally, compute a pointer to the actual data buffer by skipping
860 // over the cookie completely.
861 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
862 CookieSize.getQuantity());
863}
864
John McCalle2b45e22012-05-01 05:23:51 +0000865llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
866 llvm::Value *allocPtr,
867 CharUnits cookieSize) {
868 // The element size is right-justified in the cookie.
869 llvm::Value *numElementsPtr = allocPtr;
870 CharUnits numElementsOffset =
871 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
872 if (!numElementsOffset.isZero())
873 numElementsPtr =
874 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
875 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000876
Micah Villmow956a5a12012-10-25 15:39:14 +0000877 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000878 numElementsPtr =
879 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
880 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000881}
882
John McCalle2b45e22012-05-01 05:23:51 +0000883CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCall1e7fe752010-09-02 09:58:18 +0000884 // On ARM, the cookie is always:
885 // struct array_cookie {
886 // std::size_t element_size; // element_size != 0
887 // std::size_t element_count;
888 // };
889 // TODO: what should we do if the allocated type actually wants
890 // greater alignment?
John McCalle2b45e22012-05-01 05:23:51 +0000891 return CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000892}
893
894llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
895 llvm::Value *NewPtr,
896 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000897 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000898 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000899 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000900
901 // NewPtr is a char*.
902
Micah Villmow956a5a12012-10-25 15:39:14 +0000903 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000904
John McCall9cb2cee2010-09-02 10:25:57 +0000905 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000906 CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000907 llvm::IntegerType *SizeTy =
John McCall1e7fe752010-09-02 09:58:18 +0000908 cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType()));
909
910 // The cookie is always at the start of the buffer.
911 llvm::Value *CookiePtr = NewPtr;
912
913 // The first element is the element size.
914 CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS));
915 llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy,
916 Ctx.getTypeSizeInChars(ElementType).getQuantity());
917 CGF.Builder.CreateStore(ElementSize, CookiePtr);
918
919 // The second element is the element count.
920 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1);
921 CGF.Builder.CreateStore(NumElements, CookiePtr);
922
923 // Finally, compute a pointer to the actual data buffer by skipping
924 // over the cookie completely.
925 CharUnits CookieSize = 2 * SizeSize;
926 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
927 CookieSize.getQuantity());
928}
929
John McCalle2b45e22012-05-01 05:23:51 +0000930llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
931 llvm::Value *allocPtr,
932 CharUnits cookieSize) {
933 // The number of elements is at offset sizeof(size_t) relative to
934 // the allocated pointer.
935 llvm::Value *numElementsPtr
936 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000937
Micah Villmow956a5a12012-10-25 15:39:14 +0000938 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000939 numElementsPtr =
940 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
941 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000942}
943
John McCall5cd91b52010-09-08 01:44:27 +0000944/*********************** Static local initialization **************************/
945
946static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000947 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000948 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000949 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +0000950 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +0000951 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000952 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling72390b32012-12-20 19:27:06 +0000953 llvm::Attribute::get(CGM.getLLVMContext(),
954 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000955}
956
957static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000958 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000959 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000960 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000961 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000962 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling72390b32012-12-20 19:27:06 +0000963 llvm::Attribute::get(CGM.getLLVMContext(),
964 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000965}
966
967static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000968 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000969 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000970 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000971 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000972 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling72390b32012-12-20 19:27:06 +0000973 llvm::Attribute::get(CGM.getLLVMContext(),
974 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000975}
976
977namespace {
978 struct CallGuardAbort : EHScopeStack::Cleanup {
979 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +0000980 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +0000981
John McCallad346f42011-07-12 20:27:29 +0000982 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5cd91b52010-09-08 01:44:27 +0000983 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
984 ->setDoesNotThrow();
985 }
986 };
987}
988
989/// The ARM code here follows the Itanium code closely enough that we
990/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +0000991void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
992 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +0000993 llvm::GlobalVariable *var,
994 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +0000995 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +0000996
997 // We only need to use thread-safe statics for local variables;
998 // global initialization is always single-threaded.
John McCall0502a222011-06-17 07:33:57 +0000999 bool threadsafe =
David Blaikie4e4d0842012-03-11 07:00:24 +00001000 (getContext().getLangOpts().ThreadsafeStatics && D.isLocalVarDecl());
Anders Carlsson173d5122011-04-27 04:37:08 +00001001
Anders Carlsson173d5122011-04-27 04:37:08 +00001002 // If we have a global variable with internal linkage and thread-safe statics
1003 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001004 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1005
1006 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001007 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001008 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001009 } else {
Anders Carlsson173d5122011-04-27 04:37:08 +00001010 // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
John McCall355bba72012-03-30 21:00:39 +00001011 guardTy = (IsARM ? CGF.Int32Ty : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001012 }
John McCall355bba72012-03-30 21:00:39 +00001013 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001014
John McCall355bba72012-03-30 21:00:39 +00001015 // Create the guard variable if we don't already have it (as we
1016 // might if we're double-emitting this function body).
1017 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1018 if (!guard) {
1019 // Mangle the name for the guard.
1020 SmallString<256> guardName;
1021 {
1022 llvm::raw_svector_ostream out(guardName);
1023 getMangleContext().mangleItaniumGuardVariable(&D, out);
1024 out.flush();
1025 }
John McCall112c9672010-11-02 21:04:24 +00001026
John McCall355bba72012-03-30 21:00:39 +00001027 // Create the guard variable with a zero-initializer.
1028 // Just absorb linkage and visibility from the guarded variable.
1029 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1030 false, var->getLinkage(),
1031 llvm::ConstantInt::get(guardTy, 0),
1032 guardName.str());
1033 guard->setVisibility(var->getVisibility());
1034
1035 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1036 }
John McCall49d26d22012-03-30 07:09:50 +00001037
John McCall5cd91b52010-09-08 01:44:27 +00001038 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001039 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001040
1041 // ARM C++ ABI 3.2.3.1:
1042 // To support the potential use of initialization guard variables
1043 // as semaphores that are the target of ARM SWP and LDREX/STREX
1044 // synchronizing instructions we define a static initialization
1045 // guard variable to be a 4-byte aligned, 4- byte word with the
1046 // following inline access protocol.
1047 // #define INITIALIZED 1
1048 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1049 // if (__cxa_guard_acquire(&obj_guard))
1050 // ...
1051 // }
John McCall0502a222011-06-17 07:33:57 +00001052 if (IsARM && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001053 llvm::Value *V = Builder.CreateLoad(guard);
John McCall5cd91b52010-09-08 01:44:27 +00001054 V = Builder.CreateAnd(V, Builder.getInt32(1));
John McCall355bba72012-03-30 21:00:39 +00001055 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001056
1057 // Itanium C++ ABI 3.3.2:
1058 // The following is pseudo-code showing how these functions can be used:
1059 // if (obj_guard.first_byte == 0) {
1060 // if ( __cxa_guard_acquire (&obj_guard) ) {
1061 // try {
1062 // ... initialize the object ...;
1063 // } catch (...) {
1064 // __cxa_guard_abort (&obj_guard);
1065 // throw;
1066 // }
1067 // ... queue object destructor with __cxa_atexit() ...;
1068 // __cxa_guard_release (&obj_guard);
1069 // }
1070 // }
1071 } else {
1072 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001073 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001074 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001075 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001076
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001077 // Itanium ABI:
1078 // An implementation supporting thread-safety on multiprocessor
1079 // systems must also guarantee that references to the initialized
1080 // object do not occur before the load of the initialization flag.
1081 //
1082 // In LLVM, we do this by marking the load Acquire.
1083 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001084 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001085
John McCall355bba72012-03-30 21:00:39 +00001086 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001087 }
1088
1089 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1090 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1091
1092 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001093 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001094
1095 CGF.EmitBlock(InitCheckBlock);
1096
1097 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001098 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001099 // Call __cxa_guard_acquire.
1100 llvm::Value *V
John McCall355bba72012-03-30 21:00:39 +00001101 = Builder.CreateCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001102
1103 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1104
1105 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1106 InitBlock, EndBlock);
1107
1108 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001109 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001110
1111 CGF.EmitBlock(InitBlock);
1112 }
1113
1114 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001115 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001116
John McCall0502a222011-06-17 07:33:57 +00001117 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001118 // Pop the guard-abort cleanup if we pushed one.
1119 CGF.PopCleanupBlock();
1120
1121 // Call __cxa_guard_release. This cannot throw.
John McCall355bba72012-03-30 21:00:39 +00001122 Builder.CreateCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001123 } else {
John McCall355bba72012-03-30 21:00:39 +00001124 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001125 }
1126
1127 CGF.EmitBlock(EndBlock);
1128}
John McCall20bb1752012-05-01 06:13:13 +00001129
1130/// Register a global destructor using __cxa_atexit.
1131static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1132 llvm::Constant *dtor,
1133 llvm::Constant *addr) {
1134 // We're assuming that the destructor function is something we can
1135 // reasonably call with the default CC. Go ahead and cast it to the
1136 // right prototype.
1137 llvm::Type *dtorTy =
1138 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1139
1140 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1141 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1142 llvm::FunctionType *atexitTy =
1143 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1144
1145 // Fetch the actual function.
1146 llvm::Constant *atexit =
1147 CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
1148 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1149 fn->setDoesNotThrow();
1150
1151 // Create a variable that binds the atexit to this shared object.
1152 llvm::Constant *handle =
1153 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1154
1155 llvm::Value *args[] = {
1156 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1157 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1158 handle
1159 };
1160 CGF.Builder.CreateCall(atexit, args)->setDoesNotThrow();
1161}
1162
1163/// Register a global destructor as best as we know how.
1164void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1165 llvm::Constant *dtor,
1166 llvm::Constant *addr) {
1167 // Use __cxa_atexit if available.
1168 if (CGM.getCodeGenOpts().CXAAtExit) {
1169 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr);
1170 }
1171
1172 // In Apple kexts, we want to add a global destructor entry.
1173 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001174 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001175 // Generate a global destructor entry.
1176 return CGM.AddCXXDtorEntry(dtor, addr);
1177 }
1178
1179 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1180}