blob: 8d06b6011c01aa2c194293a474423db8d5e73e05 [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"
John McCall93d557b2010-08-22 00:05:51 +000023#include "CodeGenFunction.h"
Charles Davis3a811f12010-05-25 19:52:27 +000024#include "CodeGenModule.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include <clang/AST/Mangle.h>
John McCall93d557b2010-08-22 00:05:51 +000026#include <clang/AST/Type.h>
John McCall0502a222011-06-17 07:33:57 +000027#include <llvm/Intrinsics.h>
John McCall0bab0cd2010-08-23 01:21:21 +000028#include <llvm/Target/TargetData.h>
John McCall93d557b2010-08-22 00:05:51 +000029#include <llvm/Value.h>
Charles Davis3a811f12010-05-25 19:52:27 +000030
31using namespace clang;
John McCall93d557b2010-08-22 00:05:51 +000032using namespace CodeGen;
Charles Davis3a811f12010-05-25 19:52:27 +000033
34namespace {
Charles Davis071cc7d2010-08-16 03:33:14 +000035class ItaniumCXXABI : public CodeGen::CGCXXABI {
John McCall0bab0cd2010-08-23 01:21:21 +000036private:
Chris Lattner9cbe4f02011-07-09 17:41:47 +000037 llvm::IntegerType *PtrDiffTy;
John McCall93d557b2010-08-22 00:05:51 +000038protected:
John McCallbabc9a92010-08-22 00:59:17 +000039 bool IsARM;
John McCall0bab0cd2010-08-23 01:21:21 +000040
41 // It's a little silly for us to cache this.
Chris Lattner9cbe4f02011-07-09 17:41:47 +000042 llvm::IntegerType *getPtrDiffTy() {
John McCall0bab0cd2010-08-23 01:21:21 +000043 if (!PtrDiffTy) {
John McCall9cb2cee2010-09-02 10:25:57 +000044 QualType T = getContext().getPointerDiffType();
Chris Lattner9cbe4f02011-07-09 17:41:47 +000045 llvm::Type *Ty = CGM.getTypes().ConvertType(T);
John McCall0bab0cd2010-08-23 01:21:21 +000046 PtrDiffTy = cast<llvm::IntegerType>(Ty);
47 }
48 return PtrDiffTy;
49 }
50
John McCall6ec278d2011-01-27 09:37:56 +000051 bool NeedsArrayCookie(const CXXNewExpr *expr);
52 bool NeedsArrayCookie(const CXXDeleteExpr *expr,
53 QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +000054
Charles Davis3a811f12010-05-25 19:52:27 +000055public:
John McCallbabc9a92010-08-22 00:59:17 +000056 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
Peter Collingbourne14110472011-01-13 18:57:25 +000057 CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { }
John McCall93d557b2010-08-22 00:05:51 +000058
John McCallf16aa102010-08-22 21:01:12 +000059 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000060
Chris Lattner9cbe4f02011-07-09 17:41:47 +000061 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000062
John McCall93d557b2010-08-22 00:05:51 +000063 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
64 llvm::Value *&This,
65 llvm::Value *MemFnPtr,
66 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000067
John McCall6c2ab1d2010-08-31 21:07:20 +000068 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
69 llvm::Value *Base,
70 llvm::Value *MemPtr,
71 const MemberPointerType *MPT);
72
John McCall0bab0cd2010-08-23 01:21:21 +000073 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
74 const CastExpr *E,
75 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000076 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
77 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000078
John McCall0bab0cd2010-08-23 01:21:21 +000079 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000080
John McCall755d8492011-04-12 00:42:48 +000081 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000082 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
83 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000084 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
85 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
86 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000087
John McCall0bab0cd2010-08-23 01:21:21 +000088 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
89 llvm::Value *L,
90 llvm::Value *R,
91 const MemberPointerType *MPT,
92 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000093
John McCall0bab0cd2010-08-23 01:21:21 +000094 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
95 llvm::Value *Addr,
96 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000097
98 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
99 CXXCtorType T,
100 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000101 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000102
103 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
104 CXXDtorType T,
105 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000106 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000107
108 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
109 QualType &ResTy,
110 FunctionArgList &Params);
111
112 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000113
John McCall6ec278d2011-01-27 09:37:56 +0000114 CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
John McCall1e7fe752010-09-02 09:58:18 +0000115 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
116 llvm::Value *NewPtr,
117 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000118 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000119 QualType ElementType);
120 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
John McCall6ec278d2011-01-27 09:37:56 +0000121 const CXXDeleteExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000122 QualType ElementType, llvm::Value *&NumElements,
123 llvm::Value *&AllocPtr, CharUnits &CookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000124
John McCall3030eb82010-11-06 09:44:32 +0000125 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Richard Smith7ca48502012-02-13 22:16:19 +0000126 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Charles Davis3a811f12010-05-25 19:52:27 +0000127};
John McCallee79a4c2010-08-21 22:46:04 +0000128
129class ARMCXXABI : public ItaniumCXXABI {
130public:
John McCallbabc9a92010-08-22 00:59:17 +0000131 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000132
133 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
134 CXXCtorType T,
135 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000136 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000137
138 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
139 CXXDtorType 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 BuildInstanceFunctionParams(CodeGenFunction &CGF,
144 QualType &ResTy,
145 FunctionArgList &Params);
146
147 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
148
149 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
150
John McCall6ec278d2011-01-27 09:37:56 +0000151 CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
John McCall1e7fe752010-09-02 09:58:18 +0000152 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
153 llvm::Value *NewPtr,
154 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000155 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000156 QualType ElementType);
157 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
John McCall6ec278d2011-01-27 09:37:56 +0000158 const CXXDeleteExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000159 QualType ElementType, llvm::Value *&NumElements,
160 llvm::Value *&AllocPtr, CharUnits &CookieSize);
John McCall4c40d982010-08-31 07:33:07 +0000161
162private:
163 /// \brief Returns true if the given instance method is one of the
164 /// kinds that the ARM ABI says returns 'this'.
165 static bool HasThisReturn(GlobalDecl GD) {
166 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
167 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
168 (isa<CXXConstructorDecl>(MD)));
169 }
John McCallee79a4c2010-08-21 22:46:04 +0000170};
Charles Davis3a811f12010-05-25 19:52:27 +0000171}
172
Charles Davis071cc7d2010-08-16 03:33:14 +0000173CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
Charles Davis3a811f12010-05-25 19:52:27 +0000174 return new ItaniumCXXABI(CGM);
175}
176
John McCallee79a4c2010-08-21 22:46:04 +0000177CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) {
178 return new ARMCXXABI(CGM);
179}
180
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000181llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000182ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
183 if (MPT->isMemberDataPointer())
184 return getPtrDiffTy();
Chris Lattner7650d952011-06-18 22:49:11 +0000185 return llvm::StructType::get(getPtrDiffTy(), getPtrDiffTy(), NULL);
John McCall875ab102010-08-22 06:43:33 +0000186}
187
John McCallbabc9a92010-08-22 00:59:17 +0000188/// In the Itanium and ARM ABIs, method pointers have the form:
189/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
190///
191/// In the Itanium ABI:
192/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
193/// - the this-adjustment is (memptr.adj)
194/// - the virtual offset is (memptr.ptr - 1)
195///
196/// In the ARM ABI:
197/// - method pointers are virtual if (memptr.adj & 1) is nonzero
198/// - the this-adjustment is (memptr.adj >> 1)
199/// - the virtual offset is (memptr.ptr)
200/// ARM uses 'adj' for the virtual flag because Thumb functions
201/// may be only single-byte aligned.
202///
203/// If the member is virtual, the adjusted 'this' pointer points
204/// to a vtable pointer from which the virtual offset is applied.
205///
206/// If the member is non-virtual, memptr.ptr is the address of
207/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000208llvm::Value *
209ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
210 llvm::Value *&This,
211 llvm::Value *MemFnPtr,
212 const MemberPointerType *MPT) {
213 CGBuilderTy &Builder = CGF.Builder;
214
215 const FunctionProtoType *FPT =
216 MPT->getPointeeType()->getAs<FunctionProtoType>();
217 const CXXRecordDecl *RD =
218 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
219
Chris Lattner2acc6e32011-07-18 04:24:23 +0000220 llvm::FunctionType *FTy =
John McCall93d557b2010-08-22 00:05:51 +0000221 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
222 FPT->isVariadic());
223
Chris Lattner2acc6e32011-07-18 04:24:23 +0000224 llvm::IntegerType *ptrdiff = getPtrDiffTy();
John McCallbabc9a92010-08-22 00:59:17 +0000225 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
John McCall93d557b2010-08-22 00:05:51 +0000226
John McCallbabc9a92010-08-22 00:59:17 +0000227 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
228 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
229 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
230
John McCalld608cdb2010-08-22 10:59:02 +0000231 // Extract memptr.adj, which is in the second field.
232 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000233
234 // Compute the true adjustment.
235 llvm::Value *Adj = RawAdj;
236 if (IsARM)
237 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000238
239 // Apply the adjustment and cast back to the original struct type
240 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000241 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
242 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
243 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000244
245 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000246 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000247
248 // If the LSB in the function pointer is 1, the function pointer points to
249 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000250 llvm::Value *IsVirtual;
251 if (IsARM)
252 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
253 else
254 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
255 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000256 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
257
258 // In the virtual path, the adjustment left 'This' pointing to the
259 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000260 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000261 CGF.EmitBlock(FnVirtual);
262
263 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000264 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000265 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000266 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000267
268 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000269 llvm::Value *VTableOffset = FnAsInt;
270 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
271 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000272
273 // Load the virtual function to call.
274 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000275 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000276 CGF.EmitBranch(FnEnd);
277
278 // In the non-virtual path, the function pointer is actually a
279 // function pointer.
280 CGF.EmitBlock(FnNonVirtual);
281 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000282 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000283
284 // We're done.
285 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000286 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000287 Callee->addIncoming(VirtualFn, FnVirtual);
288 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
289 return Callee;
290}
John McCall3023def2010-08-22 03:04:22 +0000291
John McCall6c2ab1d2010-08-31 21:07:20 +0000292/// Compute an l-value by applying the given pointer-to-member to a
293/// base object.
294llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
295 llvm::Value *Base,
296 llvm::Value *MemPtr,
297 const MemberPointerType *MPT) {
298 assert(MemPtr->getType() == getPtrDiffTy());
299
300 CGBuilderTy &Builder = CGF.Builder;
301
302 unsigned AS = cast<llvm::PointerType>(Base->getType())->getAddressSpace();
303
304 // Cast to char*.
305 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
306
307 // Apply the offset, which we assume is non-null.
308 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
309
310 // Cast the address to the appropriate pointer type, adopting the
311 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000312 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000313 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000314 return Builder.CreateBitCast(Addr, PType);
315}
316
John McCall4d4e5c12012-02-15 01:22:51 +0000317/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
318/// conversion.
319///
320/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000321///
322/// Obligatory offset/adjustment diagram:
323/// <-- offset --> <-- adjustment -->
324/// |--------------------------|----------------------|--------------------|
325/// ^Derived address point ^Base address point ^Member address point
326///
327/// So when converting a base member pointer to a derived member pointer,
328/// we add the offset to the adjustment because the address point has
329/// decreased; and conversely, when converting a derived MP to a base MP
330/// we subtract the offset from the adjustment because the address point
331/// has increased.
332///
333/// The standard forbids (at compile time) conversion to and from
334/// virtual bases, which is why we don't have to consider them here.
335///
336/// The standard forbids (at run time) casting a derived MP to a base
337/// MP when the derived MP does not point to a member of the base.
338/// This is why -1 is a reasonable choice for null data member
339/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000340llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000341ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
342 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000343 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000344 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000345 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
346 E->getCastKind() == CK_ReinterpretMemberPointer);
347
348 // Under Itanium, reinterprets don't require any additional processing.
349 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
350
351 // Use constant emission if we can.
352 if (isa<llvm::Constant>(src))
353 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
354
355 llvm::Constant *adj = getMemberPointerAdjustment(E);
356 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000357
358 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000359 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000360
John McCall4d4e5c12012-02-15 01:22:51 +0000361 const MemberPointerType *destTy =
362 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000363
John McCall0bab0cd2010-08-23 01:21:21 +0000364 // For member data pointers, this is just a matter of adding the
365 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000366 if (destTy->isMemberDataPointer()) {
367 llvm::Value *dst;
368 if (isDerivedToBase)
369 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000370 else
John McCall4d4e5c12012-02-15 01:22:51 +0000371 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000372
373 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000374 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
375 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
376 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000377 }
378
John McCalld608cdb2010-08-22 10:59:02 +0000379 // The this-adjustment is left-shifted by 1 on ARM.
380 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000381 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
382 offset <<= 1;
383 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000384 }
385
John McCall4d4e5c12012-02-15 01:22:51 +0000386 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
387 llvm::Value *dstAdj;
388 if (isDerivedToBase)
389 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000390 else
John McCall4d4e5c12012-02-15 01:22:51 +0000391 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000392
John McCall4d4e5c12012-02-15 01:22:51 +0000393 return Builder.CreateInsertValue(src, dstAdj, 1);
394}
395
396llvm::Constant *
397ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
398 llvm::Constant *src) {
399 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
400 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
401 E->getCastKind() == CK_ReinterpretMemberPointer);
402
403 // Under Itanium, reinterprets don't require any additional processing.
404 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
405
406 // If the adjustment is trivial, we don't need to do anything.
407 llvm::Constant *adj = getMemberPointerAdjustment(E);
408 if (!adj) return src;
409
410 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
411
412 const MemberPointerType *destTy =
413 E->getType()->castAs<MemberPointerType>();
414
415 // For member data pointers, this is just a matter of adding the
416 // offset if the source is non-null.
417 if (destTy->isMemberDataPointer()) {
418 // null maps to null.
419 if (src->isAllOnesValue()) return src;
420
421 if (isDerivedToBase)
422 return llvm::ConstantExpr::getNSWSub(src, adj);
423 else
424 return llvm::ConstantExpr::getNSWAdd(src, adj);
425 }
426
427 // The this-adjustment is left-shifted by 1 on ARM.
428 if (IsARM) {
429 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
430 offset <<= 1;
431 adj = llvm::ConstantInt::get(adj->getType(), offset);
432 }
433
434 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
435 llvm::Constant *dstAdj;
436 if (isDerivedToBase)
437 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
438 else
439 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
440
441 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000442}
John McCallcf2c85e2010-08-22 04:16:24 +0000443
444llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000445ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000446 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCall0bab0cd2010-08-23 01:21:21 +0000447
448 // Itanium C++ ABI 2.3:
449 // A NULL pointer is represented as -1.
450 if (MPT->isMemberDataPointer())
451 return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000452
453 llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
454 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000455 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000456}
457
John McCall5808ce42011-02-03 08:15:49 +0000458llvm::Constant *
459ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
460 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000461 // Itanium C++ ABI 2.3:
462 // A pointer to data member is an offset from the base address of
463 // the class object containing it, represented as a ptrdiff_t
John McCall5808ce42011-02-03 08:15:49 +0000464 return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000465}
466
John McCall755d8492011-04-12 00:42:48 +0000467llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000468 return BuildMemberPointer(MD, CharUnits::Zero());
469}
470
471llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
472 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000473 assert(MD->isInstance() && "Member function must not be static!");
474 MD = MD->getCanonicalDecl();
475
476 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000477 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCalld608cdb2010-08-22 10:59:02 +0000478
479 // Get the function pointer (or index if this is a virtual function).
480 llvm::Constant *MemPtr[2];
481 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000482 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000483
Ken Dyck1246ba62011-04-09 01:30:02 +0000484 const ASTContext &Context = getContext();
485 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000486 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000487 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000488
489 if (IsARM) {
490 // ARM C++ ABI 3.2.1:
491 // This ABI specifies that adj contains twice the this
492 // adjustment, plus 1 if the member function is virtual. The
493 // least significant bit of adj then makes exactly the same
494 // discrimination as the least significant bit of ptr does for
495 // Itanium.
496 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
Richard Smith2d6a5672012-01-14 04:30:29 +0000497 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
498 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000499 } else {
500 // Itanium C++ ABI 2.3:
501 // For a virtual function, [the pointer field] is 1 plus the
502 // virtual table offset (in bytes) of the function,
503 // represented as a ptrdiff_t.
504 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
Richard Smith2d6a5672012-01-14 04:30:29 +0000505 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
506 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000507 }
508 } else {
John McCall755d8492011-04-12 00:42:48 +0000509 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000510 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000511 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000512 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000513 // The function has a computable LLVM signature; use the correct type.
514 Ty = Types.GetFunctionType(Types.getFunctionInfo(MD),
515 FPT->isVariadic());
John McCalld608cdb2010-08-22 10:59:02 +0000516 } else {
John McCall755d8492011-04-12 00:42:48 +0000517 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
518 // function type is incomplete.
519 Ty = ptrdiff_t;
John McCalld608cdb2010-08-22 10:59:02 +0000520 }
John McCall755d8492011-04-12 00:42:48 +0000521 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000522
John McCall379b5152011-04-11 07:02:50 +0000523 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
Richard Smith2d6a5672012-01-14 04:30:29 +0000524 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, (IsARM ? 2 : 1) *
525 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000526 }
John McCall875ab102010-08-22 06:43:33 +0000527
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000528 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000529}
530
Richard Smith2d6a5672012-01-14 04:30:29 +0000531llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
532 QualType MPType) {
533 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
534 const ValueDecl *MPD = MP.getMemberPointerDecl();
535 if (!MPD)
536 return EmitNullMemberPointer(MPT);
537
538 // Compute the this-adjustment.
539 CharUnits ThisAdjustment = CharUnits::Zero();
540 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
541 bool DerivedMember = MP.isMemberPointerToDerivedMember();
542 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
543 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
544 const CXXRecordDecl *Base = RD;
545 const CXXRecordDecl *Derived = Path[I];
546 if (DerivedMember)
547 std::swap(Base, Derived);
548 ThisAdjustment +=
549 getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
550 RD = Path[I];
551 }
552 if (DerivedMember)
553 ThisAdjustment = -ThisAdjustment;
554
555 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
556 return BuildMemberPointer(MD, ThisAdjustment);
557
558 CharUnits FieldOffset =
559 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
560 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
561}
562
John McCalle9fd7eb2010-08-22 08:30:07 +0000563/// The comparison algorithm is pretty easy: the member pointers are
564/// the same if they're either bitwise identical *or* both null.
565///
566/// ARM is different here only because null-ness is more complicated.
567llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000568ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
569 llvm::Value *L,
570 llvm::Value *R,
571 const MemberPointerType *MPT,
572 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000573 CGBuilderTy &Builder = CGF.Builder;
574
John McCalle9fd7eb2010-08-22 08:30:07 +0000575 llvm::ICmpInst::Predicate Eq;
576 llvm::Instruction::BinaryOps And, Or;
577 if (Inequality) {
578 Eq = llvm::ICmpInst::ICMP_NE;
579 And = llvm::Instruction::Or;
580 Or = llvm::Instruction::And;
581 } else {
582 Eq = llvm::ICmpInst::ICMP_EQ;
583 And = llvm::Instruction::And;
584 Or = llvm::Instruction::Or;
585 }
586
John McCall0bab0cd2010-08-23 01:21:21 +0000587 // Member data pointers are easy because there's a unique null
588 // value, so it just comes down to bitwise equality.
589 if (MPT->isMemberDataPointer())
590 return Builder.CreateICmp(Eq, L, R);
591
592 // For member function pointers, the tautologies are more complex.
593 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000594 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000595 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000596 // (L == R) <==> (L.ptr == R.ptr &&
597 // (L.adj == R.adj ||
598 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000599 // The inequality tautologies have exactly the same structure, except
600 // applying De Morgan's laws.
601
602 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
603 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
604
John McCalle9fd7eb2010-08-22 08:30:07 +0000605 // This condition tests whether L.ptr == R.ptr. This must always be
606 // true for equality to hold.
607 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
608
609 // This condition, together with the assumption that L.ptr == R.ptr,
610 // tests whether the pointers are both null. ARM imposes an extra
611 // condition.
612 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
613 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
614
615 // This condition tests whether L.adj == R.adj. If this isn't
616 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000617 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
618 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000619 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
620
621 // Null member function pointers on ARM clear the low bit of Adj,
622 // so the zero condition has to check that neither low bit is set.
623 if (IsARM) {
624 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
625
626 // Compute (l.adj | r.adj) & 1 and test it against zero.
627 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
628 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
629 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
630 "cmp.or.adj");
631 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
632 }
633
634 // Tie together all our conditions.
635 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
636 Result = Builder.CreateBinOp(And, PtrEq, Result,
637 Inequality ? "memptr.ne" : "memptr.eq");
638 return Result;
639}
640
641llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000642ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
643 llvm::Value *MemPtr,
644 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000645 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000646
647 /// For member data pointers, this is just a check against -1.
648 if (MPT->isMemberDataPointer()) {
649 assert(MemPtr->getType() == getPtrDiffTy());
650 llvm::Value *NegativeOne =
651 llvm::Constant::getAllOnesValue(MemPtr->getType());
652 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
653 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000654
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000655 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000656 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000657
658 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
659 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
660
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000661 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
662 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000663 if (IsARM) {
664 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000665 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000666 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000667 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
668 "memptr.isvirtual");
669 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000670 }
671
672 return Result;
673}
John McCall875ab102010-08-22 06:43:33 +0000674
John McCallf16aa102010-08-22 21:01:12 +0000675/// The Itanium ABI requires non-zero initialization only for data
676/// member pointers, for which '0' is a valid offset.
677bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
678 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000679}
John McCall4c40d982010-08-31 07:33:07 +0000680
681/// The generic ABI passes 'this', plus a VTT if it's initializing a
682/// base subobject.
683void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
684 CXXCtorType Type,
685 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000686 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000687 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000688
689 // 'this' is already there.
690
691 // Check if we need to add a VTT parameter (which has type void **).
692 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
693 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
694}
695
696/// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
697void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
698 CXXCtorType Type,
699 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000700 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000701 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
702 ResTy = ArgTys[0];
703}
704
705/// The generic ABI passes 'this', plus a VTT if it's destroying a
706/// base subobject.
707void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
708 CXXDtorType Type,
709 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000710 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000711 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000712
713 // 'this' is already there.
714
715 // Check if we need to add a VTT parameter (which has type void **).
716 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
717 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
718}
719
720/// The ARM ABI does the same as the Itanium ABI, but returns 'this'
721/// for non-deleting destructors.
722void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
723 CXXDtorType Type,
724 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000725 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000726 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
727
728 if (Type != Dtor_Deleting)
729 ResTy = ArgTys[0];
730}
731
732void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
733 QualType &ResTy,
734 FunctionArgList &Params) {
735 /// Create the 'this' variable.
736 BuildThisParam(CGF, Params);
737
738 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
739 assert(MD->isInstance());
740
741 // Check if we need a VTT parameter as well.
742 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000743 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000744
745 // FIXME: avoid the fake decl
746 QualType T = Context.getPointerType(Context.VoidPtrTy);
747 ImplicitParamDecl *VTTDecl
748 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
749 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000750 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000751 getVTTDecl(CGF) = VTTDecl;
752 }
753}
754
755void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
756 QualType &ResTy,
757 FunctionArgList &Params) {
758 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
759
760 // Return 'this' from certain constructors and destructors.
761 if (HasThisReturn(CGF.CurGD))
John McCalld26bc762011-03-09 04:27:21 +0000762 ResTy = Params[0]->getType();
John McCall4c40d982010-08-31 07:33:07 +0000763}
764
765void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
766 /// Initialize the 'this' slot.
767 EmitThisParam(CGF);
768
769 /// Initialize the 'vtt' slot if needed.
770 if (getVTTDecl(CGF)) {
771 getVTTValue(CGF)
772 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
773 "vtt");
774 }
775}
776
777void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
778 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
779
780 /// Initialize the return slot to 'this' at the start of the
781 /// function.
782 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000783 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000784}
785
786void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
787 RValue RV, QualType ResultType) {
788 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
789 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
790
791 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000792 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000793 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
794 RValue Undef = RValue::get(llvm::UndefValue::get(T));
795 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
796}
John McCall1e7fe752010-09-02 09:58:18 +0000797
798/************************** Array allocation cookies **************************/
799
John McCall6ec278d2011-01-27 09:37:56 +0000800bool ItaniumCXXABI::NeedsArrayCookie(const CXXNewExpr *expr) {
John McCall1e7fe752010-09-02 09:58:18 +0000801 // If the class's usual deallocation function takes two arguments,
John McCall6ec278d2011-01-27 09:37:56 +0000802 // it needs a cookie.
803 if (expr->doesUsualArrayDeleteWantSize())
804 return true;
John McCall1e7fe752010-09-02 09:58:18 +0000805
John McCallf85e1932011-06-15 23:02:42 +0000806 // Automatic Reference Counting:
807 // We need an array cookie for pointers with strong or weak lifetime.
808 QualType AllocatedType = expr->getAllocatedType();
809 if (getContext().getLangOptions().ObjCAutoRefCount &&
810 AllocatedType->isObjCLifetimeType()) {
811 switch (AllocatedType.getObjCLifetime()) {
812 case Qualifiers::OCL_None:
813 case Qualifiers::OCL_ExplicitNone:
814 case Qualifiers::OCL_Autoreleasing:
815 return false;
816
817 case Qualifiers::OCL_Strong:
818 case Qualifiers::OCL_Weak:
819 return true;
820 }
821 }
822
John McCall6ec278d2011-01-27 09:37:56 +0000823 // Otherwise, if the class has a non-trivial destructor, it always
824 // needs a cookie.
825 const CXXRecordDecl *record =
John McCallf85e1932011-06-15 23:02:42 +0000826 AllocatedType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
John McCall6ec278d2011-01-27 09:37:56 +0000827 return (record && !record->hasTrivialDestructor());
John McCall1e7fe752010-09-02 09:58:18 +0000828}
829
John McCall6ec278d2011-01-27 09:37:56 +0000830bool ItaniumCXXABI::NeedsArrayCookie(const CXXDeleteExpr *expr,
831 QualType elementType) {
832 // If the class's usual deallocation function takes two arguments,
833 // it needs a cookie.
834 if (expr->doesUsualArrayDeleteWantSize())
835 return true;
836
Eli Friedman91873b72011-07-27 18:54:57 +0000837 return elementType.isDestructedType();
John McCall6ec278d2011-01-27 09:37:56 +0000838}
839
840CharUnits ItaniumCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) {
841 if (!NeedsArrayCookie(expr))
John McCall1e7fe752010-09-02 09:58:18 +0000842 return CharUnits::Zero();
843
John McCall6ec278d2011-01-27 09:37:56 +0000844 // Padding is the maximum of sizeof(size_t) and alignof(elementType)
John McCall9cb2cee2010-09-02 10:25:57 +0000845 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000846 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
John McCall6ec278d2011-01-27 09:37:56 +0000847 Ctx.getTypeAlignInChars(expr->getAllocatedType()));
John McCall1e7fe752010-09-02 09:58:18 +0000848}
849
850llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
851 llvm::Value *NewPtr,
852 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000853 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000854 QualType ElementType) {
John McCall6ec278d2011-01-27 09:37:56 +0000855 assert(NeedsArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000856
857 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
858
John McCall9cb2cee2010-09-02 10:25:57 +0000859 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000860 QualType SizeTy = Ctx.getSizeType();
861 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
862
863 // The size of the cookie.
864 CharUnits CookieSize =
865 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
866
867 // Compute an offset to the cookie.
868 llvm::Value *CookiePtr = NewPtr;
869 CharUnits CookieOffset = CookieSize - SizeSize;
870 if (!CookieOffset.isZero())
871 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
872 CookieOffset.getQuantity());
873
874 // Write the number of elements into the appropriate slot.
875 llvm::Value *NumElementsPtr
876 = CGF.Builder.CreateBitCast(CookiePtr,
877 CGF.ConvertType(SizeTy)->getPointerTo(AS));
878 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
879
880 // Finally, compute a pointer to the actual data buffer by skipping
881 // over the cookie completely.
882 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
883 CookieSize.getQuantity());
884}
885
886void ItaniumCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
887 llvm::Value *Ptr,
John McCall6ec278d2011-01-27 09:37:56 +0000888 const CXXDeleteExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000889 QualType ElementType,
890 llvm::Value *&NumElements,
891 llvm::Value *&AllocPtr,
892 CharUnits &CookieSize) {
893 // Derive a char* in the same address space as the pointer.
894 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000895 llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
John McCall1e7fe752010-09-02 09:58:18 +0000896
897 // If we don't need an array cookie, bail out early.
John McCall6ec278d2011-01-27 09:37:56 +0000898 if (!NeedsArrayCookie(expr, ElementType)) {
John McCall1e7fe752010-09-02 09:58:18 +0000899 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
900 NumElements = 0;
901 CookieSize = CharUnits::Zero();
902 return;
903 }
904
John McCall9cb2cee2010-09-02 10:25:57 +0000905 QualType SizeTy = getContext().getSizeType();
906 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000907 llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
John McCall1e7fe752010-09-02 09:58:18 +0000908
909 CookieSize
John McCall9cb2cee2010-09-02 10:25:57 +0000910 = std::max(SizeSize, getContext().getTypeAlignInChars(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000911
912 CharUnits NumElementsOffset = CookieSize - SizeSize;
913
914 // Compute the allocated pointer.
915 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
916 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
917 -CookieSize.getQuantity());
918
919 llvm::Value *NumElementsPtr = AllocPtr;
920 if (!NumElementsOffset.isZero())
921 NumElementsPtr =
922 CGF.Builder.CreateConstInBoundsGEP1_64(NumElementsPtr,
923 NumElementsOffset.getQuantity());
924 NumElementsPtr =
925 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
926 NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
927}
928
John McCall6ec278d2011-01-27 09:37:56 +0000929CharUnits ARMCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) {
930 if (!NeedsArrayCookie(expr))
John McCall1e7fe752010-09-02 09:58:18 +0000931 return CharUnits::Zero();
932
933 // On ARM, the cookie is always:
934 // struct array_cookie {
935 // std::size_t element_size; // element_size != 0
936 // std::size_t element_count;
937 // };
938 // TODO: what should we do if the allocated type actually wants
939 // greater alignment?
940 return getContext().getTypeSizeInChars(getContext().getSizeType()) * 2;
941}
942
943llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
944 llvm::Value *NewPtr,
945 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000946 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000947 QualType ElementType) {
John McCall6ec278d2011-01-27 09:37:56 +0000948 assert(NeedsArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000949
950 // NewPtr is a char*.
951
952 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
953
John McCall9cb2cee2010-09-02 10:25:57 +0000954 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000955 CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000956 llvm::IntegerType *SizeTy =
John McCall1e7fe752010-09-02 09:58:18 +0000957 cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType()));
958
959 // The cookie is always at the start of the buffer.
960 llvm::Value *CookiePtr = NewPtr;
961
962 // The first element is the element size.
963 CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS));
964 llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy,
965 Ctx.getTypeSizeInChars(ElementType).getQuantity());
966 CGF.Builder.CreateStore(ElementSize, CookiePtr);
967
968 // The second element is the element count.
969 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1);
970 CGF.Builder.CreateStore(NumElements, CookiePtr);
971
972 // Finally, compute a pointer to the actual data buffer by skipping
973 // over the cookie completely.
974 CharUnits CookieSize = 2 * SizeSize;
975 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
976 CookieSize.getQuantity());
977}
978
979void ARMCXXABI::ReadArrayCookie(CodeGenFunction &CGF,
980 llvm::Value *Ptr,
John McCall6ec278d2011-01-27 09:37:56 +0000981 const CXXDeleteExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000982 QualType ElementType,
983 llvm::Value *&NumElements,
984 llvm::Value *&AllocPtr,
985 CharUnits &CookieSize) {
986 // Derive a char* in the same address space as the pointer.
987 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000988 llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS);
John McCall1e7fe752010-09-02 09:58:18 +0000989
990 // If we don't need an array cookie, bail out early.
John McCall6ec278d2011-01-27 09:37:56 +0000991 if (!NeedsArrayCookie(expr, ElementType)) {
John McCall1e7fe752010-09-02 09:58:18 +0000992 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
993 NumElements = 0;
994 CookieSize = CharUnits::Zero();
995 return;
996 }
997
John McCall9cb2cee2010-09-02 10:25:57 +0000998 QualType SizeTy = getContext().getSizeType();
999 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001000 llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
John McCall1e7fe752010-09-02 09:58:18 +00001001
1002 // The cookie size is always 2 * sizeof(size_t).
1003 CookieSize = 2 * SizeSize;
John McCall1e7fe752010-09-02 09:58:18 +00001004
1005 // The allocated pointer is the input ptr, minus that amount.
1006 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy);
1007 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
1008 -CookieSize.getQuantity());
1009
1010 // The number of elements is at offset sizeof(size_t) relative to that.
1011 llvm::Value *NumElementsPtr
1012 = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr,
1013 SizeSize.getQuantity());
1014 NumElementsPtr =
1015 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS));
1016 NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
1017}
1018
John McCall5cd91b52010-09-08 01:44:27 +00001019/*********************** Static local initialization **************************/
1020
1021static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001022 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001023 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001024 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +00001025 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +00001026 GuardPtrTy, /*isVarArg=*/false);
John McCall5cd91b52010-09-08 01:44:27 +00001027
Nick Lewyckye76872e2012-02-13 23:45:02 +00001028 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
1029 llvm::Attribute::NoUnwind);
John McCall5cd91b52010-09-08 01:44:27 +00001030}
1031
1032static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001033 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001034 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001035 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001036 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
John McCall5cd91b52010-09-08 01:44:27 +00001037
Nick Lewyckye76872e2012-02-13 23:45:02 +00001038 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
1039 llvm::Attribute::NoUnwind);
John McCall5cd91b52010-09-08 01:44:27 +00001040}
1041
1042static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001043 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001044 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001045 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001046 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
John McCall5cd91b52010-09-08 01:44:27 +00001047
Nick Lewyckye76872e2012-02-13 23:45:02 +00001048 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
1049 llvm::Attribute::NoUnwind);
John McCall5cd91b52010-09-08 01:44:27 +00001050}
1051
1052namespace {
1053 struct CallGuardAbort : EHScopeStack::Cleanup {
1054 llvm::GlobalVariable *Guard;
1055 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1056
John McCallad346f42011-07-12 20:27:29 +00001057 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5cd91b52010-09-08 01:44:27 +00001058 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
1059 ->setDoesNotThrow();
1060 }
1061 };
1062}
1063
1064/// The ARM code here follows the Itanium code closely enough that we
1065/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001066void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1067 const VarDecl &D,
Richard Smith7ca48502012-02-13 22:16:19 +00001068 llvm::GlobalVariable *GV,
1069 bool PerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001070 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001071
1072 // We only need to use thread-safe statics for local variables;
1073 // global initialization is always single-threaded.
John McCall0502a222011-06-17 07:33:57 +00001074 bool threadsafe =
1075 (getContext().getLangOptions().ThreadsafeStatics && D.isLocalVarDecl());
Anders Carlsson173d5122011-04-27 04:37:08 +00001076
Chris Lattner2acc6e32011-07-18 04:24:23 +00001077 llvm::IntegerType *GuardTy;
Anders Carlsson173d5122011-04-27 04:37:08 +00001078
1079 // If we have a global variable with internal linkage and thread-safe statics
1080 // are disabled, we can just let the guard variable be of type i8.
John McCall0502a222011-06-17 07:33:57 +00001081 bool useInt8GuardVariable = !threadsafe && GV->hasInternalLinkage();
1082 if (useInt8GuardVariable) {
1083 GuardTy = CGF.Int8Ty;
1084 } else {
Anders Carlsson173d5122011-04-27 04:37:08 +00001085 // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
John McCall0502a222011-06-17 07:33:57 +00001086 GuardTy = (IsARM ? CGF.Int32Ty : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001087 }
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001088 llvm::PointerType *GuardPtrTy = GuardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001089
1090 // Create the guard variable.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001091 SmallString<256> GuardVName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +00001092 llvm::raw_svector_ostream Out(GuardVName);
1093 getMangleContext().mangleItaniumGuardVariable(&D, Out);
1094 Out.flush();
John McCall112c9672010-11-02 21:04:24 +00001095
John McCall3030eb82010-11-06 09:44:32 +00001096 // Just absorb linkage and visibility from the variable.
John McCall5cd91b52010-09-08 01:44:27 +00001097 llvm::GlobalVariable *GuardVariable =
1098 new llvm::GlobalVariable(CGM.getModule(), GuardTy,
John McCall3030eb82010-11-06 09:44:32 +00001099 false, GV->getLinkage(),
John McCall5cd91b52010-09-08 01:44:27 +00001100 llvm::ConstantInt::get(GuardTy, 0),
1101 GuardVName.str());
John McCall112c9672010-11-02 21:04:24 +00001102 GuardVariable->setVisibility(GV->getVisibility());
John McCall5cd91b52010-09-08 01:44:27 +00001103
1104 // Test whether the variable has completed initialization.
1105 llvm::Value *IsInitialized;
1106
1107 // ARM C++ ABI 3.2.3.1:
1108 // To support the potential use of initialization guard variables
1109 // as semaphores that are the target of ARM SWP and LDREX/STREX
1110 // synchronizing instructions we define a static initialization
1111 // guard variable to be a 4-byte aligned, 4- byte word with the
1112 // following inline access protocol.
1113 // #define INITIALIZED 1
1114 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1115 // if (__cxa_guard_acquire(&obj_guard))
1116 // ...
1117 // }
John McCall0502a222011-06-17 07:33:57 +00001118 if (IsARM && !useInt8GuardVariable) {
John McCall5cd91b52010-09-08 01:44:27 +00001119 llvm::Value *V = Builder.CreateLoad(GuardVariable);
1120 V = Builder.CreateAnd(V, Builder.getInt32(1));
1121 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1122
1123 // Itanium C++ ABI 3.3.2:
1124 // The following is pseudo-code showing how these functions can be used:
1125 // if (obj_guard.first_byte == 0) {
1126 // if ( __cxa_guard_acquire (&obj_guard) ) {
1127 // try {
1128 // ... initialize the object ...;
1129 // } catch (...) {
1130 // __cxa_guard_abort (&obj_guard);
1131 // throw;
1132 // }
1133 // ... queue object destructor with __cxa_atexit() ...;
1134 // __cxa_guard_release (&obj_guard);
1135 // }
1136 // }
1137 } else {
1138 // Load the first byte of the guard variable.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001139 llvm::Type *PtrTy = Builder.getInt8PtrTy();
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001140 llvm::LoadInst *LI =
Benjamin Kramer578faa82011-09-27 21:06:10 +00001141 Builder.CreateLoad(Builder.CreateBitCast(GuardVariable, PtrTy));
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001142 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001143
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001144 // Itanium ABI:
1145 // An implementation supporting thread-safety on multiprocessor
1146 // systems must also guarantee that references to the initialized
1147 // object do not occur before the load of the initialization flag.
1148 //
1149 // In LLVM, we do this by marking the load Acquire.
1150 if (threadsafe)
1151 LI->setAtomic(llvm::Acquire);
1152
1153 IsInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001154 }
1155
1156 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1157 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1158
1159 // Check if the first byte of the guard variable is zero.
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001160 Builder.CreateCondBr(IsInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001161
1162 CGF.EmitBlock(InitCheckBlock);
1163
1164 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001165 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001166 // Call __cxa_guard_acquire.
1167 llvm::Value *V
1168 = Builder.CreateCall(getGuardAcquireFn(CGM, GuardPtrTy), GuardVariable);
1169
1170 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1171
1172 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1173 InitBlock, EndBlock);
1174
1175 // Call __cxa_guard_abort along the exceptional edge.
1176 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, GuardVariable);
1177
1178 CGF.EmitBlock(InitBlock);
1179 }
1180
1181 // Emit the initializer and add a global destructor if appropriate.
Richard Smith7ca48502012-02-13 22:16:19 +00001182 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001183
John McCall0502a222011-06-17 07:33:57 +00001184 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001185 // Pop the guard-abort cleanup if we pushed one.
1186 CGF.PopCleanupBlock();
1187
1188 // Call __cxa_guard_release. This cannot throw.
1189 Builder.CreateCall(getGuardReleaseFn(CGM, GuardPtrTy), GuardVariable);
1190 } else {
1191 Builder.CreateStore(llvm::ConstantInt::get(GuardTy, 1), GuardVariable);
1192 }
1193
1194 CGF.EmitBlock(EndBlock);
1195}