blob: 7b1d8098aaed9979aea57f7bd106bee02469675a [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
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000115 void EmitConstructorCall(CodeGenFunction &CGF,
116 const CXXConstructorDecl *D,
117 CXXCtorType Type, bool ForVirtualBase,
118 bool Delegating,
119 llvm::Value *This,
120 CallExpr::const_arg_iterator ArgBeg,
121 CallExpr::const_arg_iterator ArgEnd);
122
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000123 RValue EmitVirtualDestructorCall(CodeGenFunction &CGF,
124 const CXXDestructorDecl *Dtor,
125 CXXDtorType DtorType,
126 SourceLocation CallLoc,
127 ReturnValueSlot ReturnValue,
128 llvm::Value *This);
129
Joao Matos285baac2012-07-17 17:10:11 +0000130 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000131 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000132
John McCalle2b45e22012-05-01 05:23:51 +0000133 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000134 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
135 llvm::Value *NewPtr,
136 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000137 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000138 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000139 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
140 llvm::Value *allocPtr,
141 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000142
John McCall3030eb82010-11-06 09:44:32 +0000143 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000144 llvm::GlobalVariable *DeclPtr, bool PerformInit);
John McCall20bb1752012-05-01 06:13:13 +0000145 void registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor,
146 llvm::Constant *addr);
Charles Davis3a811f12010-05-25 19:52:27 +0000147};
John McCallee79a4c2010-08-21 22:46:04 +0000148
149class ARMCXXABI : public ItaniumCXXABI {
150public:
John McCallbabc9a92010-08-22 00:59:17 +0000151 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000152
153 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
154 CXXCtorType T,
155 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000156 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000157
158 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
159 CXXDtorType T,
160 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000161 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000162
163 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
164 QualType &ResTy,
165 FunctionArgList &Params);
166
167 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
168
169 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
170
John McCalle2b45e22012-05-01 05:23:51 +0000171 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000172 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
173 llvm::Value *NewPtr,
174 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000175 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000176 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000177 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
178 CharUnits cookieSize);
John McCall4c40d982010-08-31 07:33:07 +0000179
180private:
181 /// \brief Returns true if the given instance method is one of the
182 /// kinds that the ARM ABI says returns 'this'.
183 static bool HasThisReturn(GlobalDecl GD) {
184 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
185 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
186 (isa<CXXConstructorDecl>(MD)));
187 }
John McCallee79a4c2010-08-21 22:46:04 +0000188};
Charles Davis3a811f12010-05-25 19:52:27 +0000189}
190
Charles Davis071cc7d2010-08-16 03:33:14 +0000191CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall96fcde02013-01-25 23:36:14 +0000192 switch (CGM.getContext().getTargetInfo().getCXXABI().getKind()) {
193 // For IR-generation purposes, there's no significant difference
194 // between the ARM and iOS ABIs.
195 case TargetCXXABI::GenericARM:
196 case TargetCXXABI::iOS:
197 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000198
Tim Northoverc264e162013-01-31 12:13:10 +0000199 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
200 // include the other 32-bit ARM oddities: constructor/destructor return values
201 // and array cookies.
202 case TargetCXXABI::GenericAArch64:
203 return new ItaniumCXXABI(CGM, /*IsARM = */ true);
204
John McCall96fcde02013-01-25 23:36:14 +0000205 case TargetCXXABI::GenericItanium:
206 return new ItaniumCXXABI(CGM);
207
208 case TargetCXXABI::Microsoft:
209 llvm_unreachable("Microsoft ABI is not Itanium-based");
210 }
211 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000212}
213
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000214llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000215ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
216 if (MPT->isMemberDataPointer())
217 return getPtrDiffTy();
Chris Lattner7650d952011-06-18 22:49:11 +0000218 return llvm::StructType::get(getPtrDiffTy(), getPtrDiffTy(), NULL);
John McCall875ab102010-08-22 06:43:33 +0000219}
220
John McCallbabc9a92010-08-22 00:59:17 +0000221/// In the Itanium and ARM ABIs, method pointers have the form:
222/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
223///
224/// In the Itanium ABI:
225/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
226/// - the this-adjustment is (memptr.adj)
227/// - the virtual offset is (memptr.ptr - 1)
228///
229/// In the ARM ABI:
230/// - method pointers are virtual if (memptr.adj & 1) is nonzero
231/// - the this-adjustment is (memptr.adj >> 1)
232/// - the virtual offset is (memptr.ptr)
233/// ARM uses 'adj' for the virtual flag because Thumb functions
234/// may be only single-byte aligned.
235///
236/// If the member is virtual, the adjusted 'this' pointer points
237/// to a vtable pointer from which the virtual offset is applied.
238///
239/// If the member is non-virtual, memptr.ptr is the address of
240/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000241llvm::Value *
242ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
243 llvm::Value *&This,
244 llvm::Value *MemFnPtr,
245 const MemberPointerType *MPT) {
246 CGBuilderTy &Builder = CGF.Builder;
247
248 const FunctionProtoType *FPT =
249 MPT->getPointeeType()->getAs<FunctionProtoType>();
250 const CXXRecordDecl *RD =
251 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
252
Chris Lattner2acc6e32011-07-18 04:24:23 +0000253 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000254 CGM.getTypes().GetFunctionType(
255 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000256
Chris Lattner2acc6e32011-07-18 04:24:23 +0000257 llvm::IntegerType *ptrdiff = getPtrDiffTy();
John McCallbabc9a92010-08-22 00:59:17 +0000258 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
John McCall93d557b2010-08-22 00:05:51 +0000259
John McCallbabc9a92010-08-22 00:59:17 +0000260 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
261 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
262 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
263
John McCalld608cdb2010-08-22 10:59:02 +0000264 // Extract memptr.adj, which is in the second field.
265 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000266
267 // Compute the true adjustment.
268 llvm::Value *Adj = RawAdj;
269 if (IsARM)
270 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000271
272 // Apply the adjustment and cast back to the original struct type
273 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000274 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
275 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
276 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000277
278 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000279 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000280
281 // If the LSB in the function pointer is 1, the function pointer points to
282 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000283 llvm::Value *IsVirtual;
284 if (IsARM)
285 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
286 else
287 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
288 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000289 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
290
291 // In the virtual path, the adjustment left 'This' pointing to the
292 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000293 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000294 CGF.EmitBlock(FnVirtual);
295
296 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000297 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000298 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000299 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000300
301 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000302 llvm::Value *VTableOffset = FnAsInt;
303 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
304 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000305
306 // Load the virtual function to call.
307 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000308 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000309 CGF.EmitBranch(FnEnd);
310
311 // In the non-virtual path, the function pointer is actually a
312 // function pointer.
313 CGF.EmitBlock(FnNonVirtual);
314 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000315 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000316
317 // We're done.
318 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000319 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000320 Callee->addIncoming(VirtualFn, FnVirtual);
321 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
322 return Callee;
323}
John McCall3023def2010-08-22 03:04:22 +0000324
John McCall6c2ab1d2010-08-31 21:07:20 +0000325/// Compute an l-value by applying the given pointer-to-member to a
326/// base object.
327llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
328 llvm::Value *Base,
329 llvm::Value *MemPtr,
330 const MemberPointerType *MPT) {
331 assert(MemPtr->getType() == getPtrDiffTy());
332
333 CGBuilderTy &Builder = CGF.Builder;
334
Micah Villmow956a5a12012-10-25 15:39:14 +0000335 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000336
337 // Cast to char*.
338 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
339
340 // Apply the offset, which we assume is non-null.
341 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
342
343 // Cast the address to the appropriate pointer type, adopting the
344 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000345 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000346 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000347 return Builder.CreateBitCast(Addr, PType);
348}
349
John McCall4d4e5c12012-02-15 01:22:51 +0000350/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
351/// conversion.
352///
353/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000354///
355/// Obligatory offset/adjustment diagram:
356/// <-- offset --> <-- adjustment -->
357/// |--------------------------|----------------------|--------------------|
358/// ^Derived address point ^Base address point ^Member address point
359///
360/// So when converting a base member pointer to a derived member pointer,
361/// we add the offset to the adjustment because the address point has
362/// decreased; and conversely, when converting a derived MP to a base MP
363/// we subtract the offset from the adjustment because the address point
364/// has increased.
365///
366/// The standard forbids (at compile time) conversion to and from
367/// virtual bases, which is why we don't have to consider them here.
368///
369/// The standard forbids (at run time) casting a derived MP to a base
370/// MP when the derived MP does not point to a member of the base.
371/// This is why -1 is a reasonable choice for null data member
372/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000373llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000374ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
375 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000376 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000377 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000378 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
379 E->getCastKind() == CK_ReinterpretMemberPointer);
380
381 // Under Itanium, reinterprets don't require any additional processing.
382 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
383
384 // Use constant emission if we can.
385 if (isa<llvm::Constant>(src))
386 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
387
388 llvm::Constant *adj = getMemberPointerAdjustment(E);
389 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000390
391 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000392 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000393
John McCall4d4e5c12012-02-15 01:22:51 +0000394 const MemberPointerType *destTy =
395 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000396
John McCall0bab0cd2010-08-23 01:21:21 +0000397 // For member data pointers, this is just a matter of adding the
398 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000399 if (destTy->isMemberDataPointer()) {
400 llvm::Value *dst;
401 if (isDerivedToBase)
402 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000403 else
John McCall4d4e5c12012-02-15 01:22:51 +0000404 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000405
406 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000407 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
408 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
409 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000410 }
411
John McCalld608cdb2010-08-22 10:59:02 +0000412 // The this-adjustment is left-shifted by 1 on ARM.
413 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000414 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
415 offset <<= 1;
416 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000417 }
418
John McCall4d4e5c12012-02-15 01:22:51 +0000419 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
420 llvm::Value *dstAdj;
421 if (isDerivedToBase)
422 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000423 else
John McCall4d4e5c12012-02-15 01:22:51 +0000424 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000425
John McCall4d4e5c12012-02-15 01:22:51 +0000426 return Builder.CreateInsertValue(src, dstAdj, 1);
427}
428
429llvm::Constant *
430ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
431 llvm::Constant *src) {
432 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
433 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
434 E->getCastKind() == CK_ReinterpretMemberPointer);
435
436 // Under Itanium, reinterprets don't require any additional processing.
437 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
438
439 // If the adjustment is trivial, we don't need to do anything.
440 llvm::Constant *adj = getMemberPointerAdjustment(E);
441 if (!adj) return src;
442
443 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
444
445 const MemberPointerType *destTy =
446 E->getType()->castAs<MemberPointerType>();
447
448 // For member data pointers, this is just a matter of adding the
449 // offset if the source is non-null.
450 if (destTy->isMemberDataPointer()) {
451 // null maps to null.
452 if (src->isAllOnesValue()) return src;
453
454 if (isDerivedToBase)
455 return llvm::ConstantExpr::getNSWSub(src, adj);
456 else
457 return llvm::ConstantExpr::getNSWAdd(src, adj);
458 }
459
460 // The this-adjustment is left-shifted by 1 on ARM.
461 if (IsARM) {
462 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
463 offset <<= 1;
464 adj = llvm::ConstantInt::get(adj->getType(), offset);
465 }
466
467 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
468 llvm::Constant *dstAdj;
469 if (isDerivedToBase)
470 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
471 else
472 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
473
474 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000475}
John McCallcf2c85e2010-08-22 04:16:24 +0000476
477llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000478ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000479 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCall0bab0cd2010-08-23 01:21:21 +0000480
481 // Itanium C++ ABI 2.3:
482 // A NULL pointer is represented as -1.
483 if (MPT->isMemberDataPointer())
484 return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000485
486 llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
487 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000488 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000489}
490
John McCall5808ce42011-02-03 08:15:49 +0000491llvm::Constant *
492ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
493 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000494 // Itanium C++ ABI 2.3:
495 // A pointer to data member is an offset from the base address of
496 // the class object containing it, represented as a ptrdiff_t
John McCall5808ce42011-02-03 08:15:49 +0000497 return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000498}
499
John McCall755d8492011-04-12 00:42:48 +0000500llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000501 return BuildMemberPointer(MD, CharUnits::Zero());
502}
503
504llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
505 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000506 assert(MD->isInstance() && "Member function must not be static!");
507 MD = MD->getCanonicalDecl();
508
509 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000510 llvm::Type *ptrdiff_t = getPtrDiffTy();
John McCalld608cdb2010-08-22 10:59:02 +0000511
512 // Get the function pointer (or index if this is a virtual function).
513 llvm::Constant *MemPtr[2];
514 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000515 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000516
Ken Dyck1246ba62011-04-09 01:30:02 +0000517 const ASTContext &Context = getContext();
518 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000519 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000520 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000521
522 if (IsARM) {
523 // ARM C++ ABI 3.2.1:
524 // This ABI specifies that adj contains twice the this
525 // adjustment, plus 1 if the member function is virtual. The
526 // least significant bit of adj then makes exactly the same
527 // discrimination as the least significant bit of ptr does for
528 // Itanium.
529 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
Richard Smith2d6a5672012-01-14 04:30:29 +0000530 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
531 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000532 } else {
533 // Itanium C++ ABI 2.3:
534 // For a virtual function, [the pointer field] is 1 plus the
535 // virtual table offset (in bytes) of the function,
536 // represented as a ptrdiff_t.
537 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
Richard Smith2d6a5672012-01-14 04:30:29 +0000538 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
539 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000540 }
541 } else {
John McCall755d8492011-04-12 00:42:48 +0000542 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000543 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000544 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000545 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000546 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000547 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000548 } else {
John McCall755d8492011-04-12 00:42:48 +0000549 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
550 // function type is incomplete.
551 Ty = ptrdiff_t;
John McCalld608cdb2010-08-22 10:59:02 +0000552 }
John McCall755d8492011-04-12 00:42:48 +0000553 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000554
John McCall379b5152011-04-11 07:02:50 +0000555 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
Richard Smith2d6a5672012-01-14 04:30:29 +0000556 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, (IsARM ? 2 : 1) *
557 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000558 }
John McCall875ab102010-08-22 06:43:33 +0000559
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000560 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000561}
562
Richard Smith2d6a5672012-01-14 04:30:29 +0000563llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
564 QualType MPType) {
565 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
566 const ValueDecl *MPD = MP.getMemberPointerDecl();
567 if (!MPD)
568 return EmitNullMemberPointer(MPT);
569
570 // Compute the this-adjustment.
571 CharUnits ThisAdjustment = CharUnits::Zero();
572 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
573 bool DerivedMember = MP.isMemberPointerToDerivedMember();
574 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
575 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
576 const CXXRecordDecl *Base = RD;
577 const CXXRecordDecl *Derived = Path[I];
578 if (DerivedMember)
579 std::swap(Base, Derived);
580 ThisAdjustment +=
581 getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
582 RD = Path[I];
583 }
584 if (DerivedMember)
585 ThisAdjustment = -ThisAdjustment;
586
587 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
588 return BuildMemberPointer(MD, ThisAdjustment);
589
590 CharUnits FieldOffset =
591 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
592 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
593}
594
John McCalle9fd7eb2010-08-22 08:30:07 +0000595/// The comparison algorithm is pretty easy: the member pointers are
596/// the same if they're either bitwise identical *or* both null.
597///
598/// ARM is different here only because null-ness is more complicated.
599llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000600ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
601 llvm::Value *L,
602 llvm::Value *R,
603 const MemberPointerType *MPT,
604 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000605 CGBuilderTy &Builder = CGF.Builder;
606
John McCalle9fd7eb2010-08-22 08:30:07 +0000607 llvm::ICmpInst::Predicate Eq;
608 llvm::Instruction::BinaryOps And, Or;
609 if (Inequality) {
610 Eq = llvm::ICmpInst::ICMP_NE;
611 And = llvm::Instruction::Or;
612 Or = llvm::Instruction::And;
613 } else {
614 Eq = llvm::ICmpInst::ICMP_EQ;
615 And = llvm::Instruction::And;
616 Or = llvm::Instruction::Or;
617 }
618
John McCall0bab0cd2010-08-23 01:21:21 +0000619 // Member data pointers are easy because there's a unique null
620 // value, so it just comes down to bitwise equality.
621 if (MPT->isMemberDataPointer())
622 return Builder.CreateICmp(Eq, L, R);
623
624 // For member function pointers, the tautologies are more complex.
625 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000626 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000627 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000628 // (L == R) <==> (L.ptr == R.ptr &&
629 // (L.adj == R.adj ||
630 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000631 // The inequality tautologies have exactly the same structure, except
632 // applying De Morgan's laws.
633
634 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
635 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
636
John McCalle9fd7eb2010-08-22 08:30:07 +0000637 // This condition tests whether L.ptr == R.ptr. This must always be
638 // true for equality to hold.
639 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
640
641 // This condition, together with the assumption that L.ptr == R.ptr,
642 // tests whether the pointers are both null. ARM imposes an extra
643 // condition.
644 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
645 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
646
647 // This condition tests whether L.adj == R.adj. If this isn't
648 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000649 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
650 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000651 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
652
653 // Null member function pointers on ARM clear the low bit of Adj,
654 // so the zero condition has to check that neither low bit is set.
655 if (IsARM) {
656 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
657
658 // Compute (l.adj | r.adj) & 1 and test it against zero.
659 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
660 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
661 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
662 "cmp.or.adj");
663 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
664 }
665
666 // Tie together all our conditions.
667 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
668 Result = Builder.CreateBinOp(And, PtrEq, Result,
669 Inequality ? "memptr.ne" : "memptr.eq");
670 return Result;
671}
672
673llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000674ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
675 llvm::Value *MemPtr,
676 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000677 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000678
679 /// For member data pointers, this is just a check against -1.
680 if (MPT->isMemberDataPointer()) {
681 assert(MemPtr->getType() == getPtrDiffTy());
682 llvm::Value *NegativeOne =
683 llvm::Constant::getAllOnesValue(MemPtr->getType());
684 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
685 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000686
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000687 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000688 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000689
690 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
691 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
692
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000693 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
694 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000695 if (IsARM) {
696 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000697 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000698 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000699 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
700 "memptr.isvirtual");
701 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000702 }
703
704 return Result;
705}
John McCall875ab102010-08-22 06:43:33 +0000706
John McCallf16aa102010-08-22 21:01:12 +0000707/// The Itanium ABI requires non-zero initialization only for data
708/// member pointers, for which '0' is a valid offset.
709bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
710 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000711}
John McCall4c40d982010-08-31 07:33:07 +0000712
John McCallecd03b42012-09-25 10:10:39 +0000713/// The Itanium ABI always places an offset to the complete object
714/// at entry -2 in the vtable.
715llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
716 llvm::Value *ptr,
717 QualType type) {
718 // Grab the vtable pointer as an intptr_t*.
719 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
720
721 // Track back to entry -2 and pull out the offset there.
722 llvm::Value *offsetPtr =
723 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
724 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
725 offset->setAlignment(CGF.PointerAlignInBytes);
726
727 // Apply the offset.
728 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
729 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
730}
731
John McCall4c40d982010-08-31 07:33:07 +0000732/// The generic ABI passes 'this', plus a VTT if it's initializing a
733/// base subobject.
734void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
735 CXXCtorType Type,
736 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000737 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000738 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000739
740 // 'this' is already there.
741
742 // Check if we need to add a VTT parameter (which has type void **).
743 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
744 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
745}
746
747/// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
748void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
749 CXXCtorType Type,
750 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000751 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000752 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
753 ResTy = ArgTys[0];
754}
755
756/// The generic ABI passes 'this', plus a VTT if it's destroying a
757/// base subobject.
758void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
759 CXXDtorType Type,
760 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000761 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000762 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000763
764 // 'this' is already there.
765
766 // Check if we need to add a VTT parameter (which has type void **).
767 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
768 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
769}
770
771/// The ARM ABI does the same as the Itanium ABI, but returns 'this'
772/// for non-deleting destructors.
773void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
774 CXXDtorType Type,
775 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000776 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall4c40d982010-08-31 07:33:07 +0000777 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
778
779 if (Type != Dtor_Deleting)
780 ResTy = ArgTys[0];
781}
782
783void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
784 QualType &ResTy,
785 FunctionArgList &Params) {
786 /// Create the 'this' variable.
787 BuildThisParam(CGF, Params);
788
789 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
790 assert(MD->isInstance());
791
792 // Check if we need a VTT parameter as well.
793 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000794 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000795
796 // FIXME: avoid the fake decl
797 QualType T = Context.getPointerType(Context.VoidPtrTy);
798 ImplicitParamDecl *VTTDecl
799 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
800 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000801 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000802 getVTTDecl(CGF) = VTTDecl;
803 }
804}
805
806void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
807 QualType &ResTy,
808 FunctionArgList &Params) {
809 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
810
811 // Return 'this' from certain constructors and destructors.
812 if (HasThisReturn(CGF.CurGD))
John McCalld26bc762011-03-09 04:27:21 +0000813 ResTy = Params[0]->getType();
John McCall4c40d982010-08-31 07:33:07 +0000814}
815
816void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
817 /// Initialize the 'this' slot.
818 EmitThisParam(CGF);
819
820 /// Initialize the 'vtt' slot if needed.
821 if (getVTTDecl(CGF)) {
822 getVTTValue(CGF)
823 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
824 "vtt");
825 }
826}
827
828void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
829 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
830
831 /// Initialize the return slot to 'this' at the start of the
832 /// function.
833 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000834 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000835}
836
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000837void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
838 const CXXConstructorDecl *D,
839 CXXCtorType Type, bool ForVirtualBase,
840 bool Delegating,
841 llvm::Value *This,
842 CallExpr::const_arg_iterator ArgBeg,
843 CallExpr::const_arg_iterator ArgEnd) {
844 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
845 Delegating);
846 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
847 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
848
849 // FIXME: Provide a source location here.
850 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
851 VTT, VTTTy, ArgBeg, ArgEnd);
852}
853
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000854RValue ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
855 const CXXDestructorDecl *Dtor,
856 CXXDtorType DtorType,
857 SourceLocation CallLoc,
858 ReturnValueSlot ReturnValue,
859 llvm::Value *This) {
860 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
861
862 const CGFunctionInfo *FInfo
863 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
864 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
865 llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, DtorType, This, Ty);
866
867 return CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValue, This,
868 /*ImplicitParam=*/0, QualType(), 0, 0);
869}
870
John McCall4c40d982010-08-31 07:33:07 +0000871void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
872 RValue RV, QualType ResultType) {
873 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
874 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
875
876 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000877 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000878 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
879 RValue Undef = RValue::get(llvm::UndefValue::get(T));
880 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
881}
John McCall1e7fe752010-09-02 09:58:18 +0000882
883/************************** Array allocation cookies **************************/
884
John McCalle2b45e22012-05-01 05:23:51 +0000885CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
886 // The array cookie is a size_t; pad that up to the element alignment.
887 // The cookie is actually right-justified in that space.
888 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
889 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000890}
891
892llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
893 llvm::Value *NewPtr,
894 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000895 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000896 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000897 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000898
Micah Villmow956a5a12012-10-25 15:39:14 +0000899 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000900
John McCall9cb2cee2010-09-02 10:25:57 +0000901 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000902 QualType SizeTy = Ctx.getSizeType();
903 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
904
905 // The size of the cookie.
906 CharUnits CookieSize =
907 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000908 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000909
910 // Compute an offset to the cookie.
911 llvm::Value *CookiePtr = NewPtr;
912 CharUnits CookieOffset = CookieSize - SizeSize;
913 if (!CookieOffset.isZero())
914 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
915 CookieOffset.getQuantity());
916
917 // Write the number of elements into the appropriate slot.
918 llvm::Value *NumElementsPtr
919 = CGF.Builder.CreateBitCast(CookiePtr,
920 CGF.ConvertType(SizeTy)->getPointerTo(AS));
921 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
922
923 // Finally, compute a pointer to the actual data buffer by skipping
924 // over the cookie completely.
925 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
926 CookieSize.getQuantity());
927}
928
John McCalle2b45e22012-05-01 05:23:51 +0000929llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
930 llvm::Value *allocPtr,
931 CharUnits cookieSize) {
932 // The element size is right-justified in the cookie.
933 llvm::Value *numElementsPtr = allocPtr;
934 CharUnits numElementsOffset =
935 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
936 if (!numElementsOffset.isZero())
937 numElementsPtr =
938 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
939 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000940
Micah Villmow956a5a12012-10-25 15:39:14 +0000941 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000942 numElementsPtr =
943 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
944 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000945}
946
John McCalle2b45e22012-05-01 05:23:51 +0000947CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +0000948 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +0000949 // struct array_cookie {
950 // std::size_t element_size; // element_size != 0
951 // std::size_t element_count;
952 // };
John McCallf3bbb152013-01-25 23:36:19 +0000953 // But the base ABI doesn't give anything an alignment greater than
954 // 8, so we can dismiss this as typical ABI-author blindness to
955 // actual language complexity and round up to the element alignment.
956 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
957 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000958}
959
960llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +0000961 llvm::Value *newPtr,
962 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +0000963 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +0000964 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000965 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000966
John McCallf3bbb152013-01-25 23:36:19 +0000967 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
968 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000969
970 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +0000971 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +0000972
973 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +0000974 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
975 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
976 getContext().getTypeSizeInChars(elementType).getQuantity());
977 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000978
979 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +0000980 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
981 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000982
983 // Finally, compute a pointer to the actual data buffer by skipping
984 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +0000985 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
986 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
987 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000988}
989
John McCalle2b45e22012-05-01 05:23:51 +0000990llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
991 llvm::Value *allocPtr,
992 CharUnits cookieSize) {
993 // The number of elements is at offset sizeof(size_t) relative to
994 // the allocated pointer.
995 llvm::Value *numElementsPtr
996 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000997
Micah Villmow956a5a12012-10-25 15:39:14 +0000998 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000999 numElementsPtr =
1000 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1001 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +00001002}
1003
John McCall5cd91b52010-09-08 01:44:27 +00001004/*********************** Static local initialization **************************/
1005
1006static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001007 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001008 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001009 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +00001010 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +00001011 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001012 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001013 llvm::AttributeSet::get(CGM.getLLVMContext(),
1014 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001015 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001016}
1017
1018static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001019 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001020 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001021 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001022 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001023 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001024 llvm::AttributeSet::get(CGM.getLLVMContext(),
1025 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001026 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001027}
1028
1029static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001030 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001031 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001032 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001033 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001034 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001035 llvm::AttributeSet::get(CGM.getLLVMContext(),
1036 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001037 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001038}
1039
1040namespace {
1041 struct CallGuardAbort : EHScopeStack::Cleanup {
1042 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001043 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001044
John McCallad346f42011-07-12 20:27:29 +00001045 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5cd91b52010-09-08 01:44:27 +00001046 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
1047 ->setDoesNotThrow();
1048 }
1049 };
1050}
1051
1052/// The ARM code here follows the Itanium code closely enough that we
1053/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001054void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1055 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001056 llvm::GlobalVariable *var,
1057 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001058 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001059
1060 // We only need to use thread-safe statics for local variables;
1061 // global initialization is always single-threaded.
John McCall0502a222011-06-17 07:33:57 +00001062 bool threadsafe =
David Blaikie4e4d0842012-03-11 07:00:24 +00001063 (getContext().getLangOpts().ThreadsafeStatics && D.isLocalVarDecl());
Anders Carlsson173d5122011-04-27 04:37:08 +00001064
Anders Carlsson173d5122011-04-27 04:37:08 +00001065 // If we have a global variable with internal linkage and thread-safe statics
1066 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001067 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1068
1069 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001070 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001071 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001072 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001073 // Guard variables are 64 bits in the generic ABI and size width on ARM
1074 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1075 guardTy = (IsARM ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001076 }
John McCall355bba72012-03-30 21:00:39 +00001077 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001078
John McCall355bba72012-03-30 21:00:39 +00001079 // Create the guard variable if we don't already have it (as we
1080 // might if we're double-emitting this function body).
1081 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1082 if (!guard) {
1083 // Mangle the name for the guard.
1084 SmallString<256> guardName;
1085 {
1086 llvm::raw_svector_ostream out(guardName);
1087 getMangleContext().mangleItaniumGuardVariable(&D, out);
1088 out.flush();
1089 }
John McCall112c9672010-11-02 21:04:24 +00001090
John McCall355bba72012-03-30 21:00:39 +00001091 // Create the guard variable with a zero-initializer.
1092 // Just absorb linkage and visibility from the guarded variable.
1093 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1094 false, var->getLinkage(),
1095 llvm::ConstantInt::get(guardTy, 0),
1096 guardName.str());
1097 guard->setVisibility(var->getVisibility());
1098
1099 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1100 }
John McCall49d26d22012-03-30 07:09:50 +00001101
John McCall5cd91b52010-09-08 01:44:27 +00001102 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001103 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001104
1105 // ARM C++ ABI 3.2.3.1:
1106 // To support the potential use of initialization guard variables
1107 // as semaphores that are the target of ARM SWP and LDREX/STREX
1108 // synchronizing instructions we define a static initialization
1109 // guard variable to be a 4-byte aligned, 4- byte word with the
1110 // following inline access protocol.
1111 // #define INITIALIZED 1
1112 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1113 // if (__cxa_guard_acquire(&obj_guard))
1114 // ...
1115 // }
John McCall0502a222011-06-17 07:33:57 +00001116 if (IsARM && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001117 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001118 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1119 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001120 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001121
1122 // Itanium C++ ABI 3.3.2:
1123 // The following is pseudo-code showing how these functions can be used:
1124 // if (obj_guard.first_byte == 0) {
1125 // if ( __cxa_guard_acquire (&obj_guard) ) {
1126 // try {
1127 // ... initialize the object ...;
1128 // } catch (...) {
1129 // __cxa_guard_abort (&obj_guard);
1130 // throw;
1131 // }
1132 // ... queue object destructor with __cxa_atexit() ...;
1133 // __cxa_guard_release (&obj_guard);
1134 // }
1135 // }
1136 } else {
1137 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001138 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001139 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001140 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001141
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001142 // Itanium ABI:
1143 // An implementation supporting thread-safety on multiprocessor
1144 // systems must also guarantee that references to the initialized
1145 // object do not occur before the load of the initialization flag.
1146 //
1147 // In LLVM, we do this by marking the load Acquire.
1148 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001149 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001150
John McCall355bba72012-03-30 21:00:39 +00001151 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001152 }
1153
1154 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1155 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1156
1157 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001158 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001159
1160 CGF.EmitBlock(InitCheckBlock);
1161
1162 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001163 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001164 // Call __cxa_guard_acquire.
1165 llvm::Value *V
John McCall355bba72012-03-30 21:00:39 +00001166 = Builder.CreateCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001167
1168 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1169
1170 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1171 InitBlock, EndBlock);
1172
1173 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001174 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001175
1176 CGF.EmitBlock(InitBlock);
1177 }
1178
1179 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001180 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001181
John McCall0502a222011-06-17 07:33:57 +00001182 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001183 // Pop the guard-abort cleanup if we pushed one.
1184 CGF.PopCleanupBlock();
1185
1186 // Call __cxa_guard_release. This cannot throw.
John McCall355bba72012-03-30 21:00:39 +00001187 Builder.CreateCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001188 } else {
John McCall355bba72012-03-30 21:00:39 +00001189 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001190 }
1191
1192 CGF.EmitBlock(EndBlock);
1193}
John McCall20bb1752012-05-01 06:13:13 +00001194
1195/// Register a global destructor using __cxa_atexit.
1196static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1197 llvm::Constant *dtor,
1198 llvm::Constant *addr) {
1199 // We're assuming that the destructor function is something we can
1200 // reasonably call with the default CC. Go ahead and cast it to the
1201 // right prototype.
1202 llvm::Type *dtorTy =
1203 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1204
1205 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1206 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1207 llvm::FunctionType *atexitTy =
1208 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1209
1210 // Fetch the actual function.
1211 llvm::Constant *atexit =
1212 CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
1213 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1214 fn->setDoesNotThrow();
1215
1216 // Create a variable that binds the atexit to this shared object.
1217 llvm::Constant *handle =
1218 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1219
1220 llvm::Value *args[] = {
1221 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1222 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1223 handle
1224 };
1225 CGF.Builder.CreateCall(atexit, args)->setDoesNotThrow();
1226}
1227
1228/// Register a global destructor as best as we know how.
1229void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1230 llvm::Constant *dtor,
1231 llvm::Constant *addr) {
1232 // Use __cxa_atexit if available.
1233 if (CGM.getCodeGenOpts().CXAAtExit) {
1234 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr);
1235 }
1236
1237 // In Apple kexts, we want to add a global destructor entry.
1238 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001239 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001240 // Generate a global destructor entry.
1241 return CGM.AddCXXDtorEntry(dtor, addr);
1242 }
1243
1244 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1245}