blob: 7228400738126d145b88ed7c4ae19a2fce477617 [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 McCall93d557b2010-08-22 00:05:51 +000037protected:
John McCallbabc9a92010-08-22 00:59:17 +000038 bool IsARM;
John McCall0bab0cd2010-08-23 01:21:21 +000039
Charles Davis3a811f12010-05-25 19:52:27 +000040public:
John McCallbabc9a92010-08-22 00:59:17 +000041 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
Reid Kleckner92e44d92013-03-22 16:13:10 +000042 CGCXXABI(CGM), IsARM(IsARM) { }
John McCall93d557b2010-08-22 00:05:51 +000043
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000044 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
45 // Structures with either a non-trivial destructor or a non-trivial
46 // copy constructor are always indirect.
47 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
48 }
49
50 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
51 // Structures with either a non-trivial destructor or a non-trivial
52 // copy constructor are always indirect.
53 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
54 return RAA_Indirect;
55 return RAA_Default;
56 }
57
John McCallf16aa102010-08-22 21:01:12 +000058 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000059
Chris Lattner9cbe4f02011-07-09 17:41:47 +000060 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000061
John McCall93d557b2010-08-22 00:05:51 +000062 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
63 llvm::Value *&This,
64 llvm::Value *MemFnPtr,
65 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000066
John McCall6c2ab1d2010-08-31 21:07:20 +000067 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
68 llvm::Value *Base,
69 llvm::Value *MemPtr,
70 const MemberPointerType *MPT);
71
John McCall0bab0cd2010-08-23 01:21:21 +000072 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
73 const CastExpr *E,
74 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000075 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
76 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000077
John McCall0bab0cd2010-08-23 01:21:21 +000078 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000079
John McCall755d8492011-04-12 00:42:48 +000080 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000081 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
82 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000083 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
84 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
85 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000086
John McCall0bab0cd2010-08-23 01:21:21 +000087 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
88 llvm::Value *L,
89 llvm::Value *R,
90 const MemberPointerType *MPT,
91 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000092
John McCall0bab0cd2010-08-23 01:21:21 +000093 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
94 llvm::Value *Addr,
95 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000096
John McCallecd03b42012-09-25 10:10:39 +000097 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
98 llvm::Value *ptr,
99 QualType type);
100
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000101 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
102 llvm::Value *This,
103 const CXXRecordDecl *ClassDecl,
104 const CXXRecordDecl *BaseClassDecl);
105
John McCall4c40d982010-08-31 07:33:07 +0000106 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
107 CXXCtorType T,
108 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000109 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000110
111 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
112 CXXDtorType T,
113 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000114 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000115
116 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
117 QualType &ResTy,
118 FunctionArgList &Params);
119
120 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000121
Stephen Lind4c0cd02013-06-18 17:00:49 +0000122 RValue EmitConstructorCall(CodeGenFunction &CGF,
123 const CXXConstructorDecl *D,
124 CXXCtorType Type,
125 bool ForVirtualBase, bool Delegating,
126 ReturnValueSlot ReturnValue,
127 llvm::Value *This,
128 CallExpr::const_arg_iterator ArgBeg,
129 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000130
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000131 RValue EmitVirtualDestructorCall(CodeGenFunction &CGF,
132 const CXXDestructorDecl *Dtor,
133 CXXDtorType DtorType,
134 SourceLocation CallLoc,
135 ReturnValueSlot ReturnValue,
136 llvm::Value *This);
137
Joao Matos285baac2012-07-17 17:10:11 +0000138 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000139 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000140
John McCalle2b45e22012-05-01 05:23:51 +0000141 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000142 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
143 llvm::Value *NewPtr,
144 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000145 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000146 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000147 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
148 llvm::Value *allocPtr,
149 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000150
John McCall3030eb82010-11-06 09:44:32 +0000151 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000152 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smith04e51762013-04-14 23:01:42 +0000153 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
154 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smithb80a16e2013-04-19 16:42:07 +0000155
156 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
157 llvm::GlobalVariable *Var);
158 void EmitThreadLocalInitFuncs(
159 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
160 llvm::Function *InitFunc);
161 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
162 const DeclRefExpr *DRE);
Charles Davis3a811f12010-05-25 19:52:27 +0000163};
John McCallee79a4c2010-08-21 22:46:04 +0000164
165class ARMCXXABI : public ItaniumCXXABI {
166public:
John McCallbabc9a92010-08-22 00:59:17 +0000167 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000168
Stephen Lind4c0cd02013-06-18 17:00:49 +0000169 bool HasThisReturn(GlobalDecl GD) const {
170 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
171 isa<CXXDestructorDecl>(GD.getDecl()) &&
172 GD.getDtorType() != Dtor_Deleting));
173 }
John McCall4c40d982010-08-31 07:33:07 +0000174
175 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
176
John McCalle2b45e22012-05-01 05:23:51 +0000177 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000178 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
179 llvm::Value *NewPtr,
180 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000181 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000182 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000183 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
184 CharUnits cookieSize);
John McCallee79a4c2010-08-21 22:46:04 +0000185};
Charles Davis3a811f12010-05-25 19:52:27 +0000186}
187
Charles Davis071cc7d2010-08-16 03:33:14 +0000188CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +0000189 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall96fcde02013-01-25 23:36:14 +0000190 // For IR-generation purposes, there's no significant difference
191 // between the ARM and iOS ABIs.
192 case TargetCXXABI::GenericARM:
193 case TargetCXXABI::iOS:
194 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000195
Tim Northoverc264e162013-01-31 12:13:10 +0000196 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
197 // include the other 32-bit ARM oddities: constructor/destructor return values
198 // and array cookies.
199 case TargetCXXABI::GenericAArch64:
200 return new ItaniumCXXABI(CGM, /*IsARM = */ true);
201
John McCall96fcde02013-01-25 23:36:14 +0000202 case TargetCXXABI::GenericItanium:
203 return new ItaniumCXXABI(CGM);
204
205 case TargetCXXABI::Microsoft:
206 llvm_unreachable("Microsoft ABI is not Itanium-based");
207 }
208 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000209}
210
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000211llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000212ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
213 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000214 return CGM.PtrDiffTy;
215 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall875ab102010-08-22 06:43:33 +0000216}
217
John McCallbabc9a92010-08-22 00:59:17 +0000218/// In the Itanium and ARM ABIs, method pointers have the form:
219/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
220///
221/// In the Itanium ABI:
222/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
223/// - the this-adjustment is (memptr.adj)
224/// - the virtual offset is (memptr.ptr - 1)
225///
226/// In the ARM ABI:
227/// - method pointers are virtual if (memptr.adj & 1) is nonzero
228/// - the this-adjustment is (memptr.adj >> 1)
229/// - the virtual offset is (memptr.ptr)
230/// ARM uses 'adj' for the virtual flag because Thumb functions
231/// may be only single-byte aligned.
232///
233/// If the member is virtual, the adjusted 'this' pointer points
234/// to a vtable pointer from which the virtual offset is applied.
235///
236/// If the member is non-virtual, memptr.ptr is the address of
237/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000238llvm::Value *
239ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
240 llvm::Value *&This,
241 llvm::Value *MemFnPtr,
242 const MemberPointerType *MPT) {
243 CGBuilderTy &Builder = CGF.Builder;
244
245 const FunctionProtoType *FPT =
246 MPT->getPointeeType()->getAs<FunctionProtoType>();
247 const CXXRecordDecl *RD =
248 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
249
Chris Lattner2acc6e32011-07-18 04:24:23 +0000250 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000251 CGM.getTypes().GetFunctionType(
252 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000253
Reid Kleckner92e44d92013-03-22 16:13:10 +0000254 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall93d557b2010-08-22 00:05:51 +0000255
John McCallbabc9a92010-08-22 00:59:17 +0000256 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
257 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
258 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
259
John McCalld608cdb2010-08-22 10:59:02 +0000260 // Extract memptr.adj, which is in the second field.
261 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000262
263 // Compute the true adjustment.
264 llvm::Value *Adj = RawAdj;
265 if (IsARM)
266 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000267
268 // Apply the adjustment and cast back to the original struct type
269 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000270 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
271 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
272 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000273
274 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000275 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000276
277 // If the LSB in the function pointer is 1, the function pointer points to
278 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000279 llvm::Value *IsVirtual;
280 if (IsARM)
281 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
282 else
283 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
284 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000285 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
286
287 // In the virtual path, the adjustment left 'This' pointing to the
288 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000289 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000290 CGF.EmitBlock(FnVirtual);
291
292 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000293 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000294 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000295 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000296
297 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000298 llvm::Value *VTableOffset = FnAsInt;
299 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
300 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000301
302 // Load the virtual function to call.
303 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000304 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000305 CGF.EmitBranch(FnEnd);
306
307 // In the non-virtual path, the function pointer is actually a
308 // function pointer.
309 CGF.EmitBlock(FnNonVirtual);
310 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000311 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000312
313 // We're done.
314 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000315 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000316 Callee->addIncoming(VirtualFn, FnVirtual);
317 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
318 return Callee;
319}
John McCall3023def2010-08-22 03:04:22 +0000320
John McCall6c2ab1d2010-08-31 21:07:20 +0000321/// Compute an l-value by applying the given pointer-to-member to a
322/// base object.
323llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
324 llvm::Value *Base,
325 llvm::Value *MemPtr,
326 const MemberPointerType *MPT) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000327 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall6c2ab1d2010-08-31 21:07:20 +0000328
329 CGBuilderTy &Builder = CGF.Builder;
330
Micah Villmow956a5a12012-10-25 15:39:14 +0000331 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000332
333 // Cast to char*.
334 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
335
336 // Apply the offset, which we assume is non-null.
337 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
338
339 // Cast the address to the appropriate pointer type, adopting the
340 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000341 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000342 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000343 return Builder.CreateBitCast(Addr, PType);
344}
345
John McCall4d4e5c12012-02-15 01:22:51 +0000346/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
347/// conversion.
348///
349/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000350///
351/// Obligatory offset/adjustment diagram:
352/// <-- offset --> <-- adjustment -->
353/// |--------------------------|----------------------|--------------------|
354/// ^Derived address point ^Base address point ^Member address point
355///
356/// So when converting a base member pointer to a derived member pointer,
357/// we add the offset to the adjustment because the address point has
358/// decreased; and conversely, when converting a derived MP to a base MP
359/// we subtract the offset from the adjustment because the address point
360/// has increased.
361///
362/// The standard forbids (at compile time) conversion to and from
363/// virtual bases, which is why we don't have to consider them here.
364///
365/// The standard forbids (at run time) casting a derived MP to a base
366/// MP when the derived MP does not point to a member of the base.
367/// This is why -1 is a reasonable choice for null data member
368/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000369llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000370ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
371 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000372 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000373 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000374 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
375 E->getCastKind() == CK_ReinterpretMemberPointer);
376
377 // Under Itanium, reinterprets don't require any additional processing.
378 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
379
380 // Use constant emission if we can.
381 if (isa<llvm::Constant>(src))
382 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
383
384 llvm::Constant *adj = getMemberPointerAdjustment(E);
385 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000386
387 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000388 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000389
John McCall4d4e5c12012-02-15 01:22:51 +0000390 const MemberPointerType *destTy =
391 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000392
John McCall0bab0cd2010-08-23 01:21:21 +0000393 // For member data pointers, this is just a matter of adding the
394 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000395 if (destTy->isMemberDataPointer()) {
396 llvm::Value *dst;
397 if (isDerivedToBase)
398 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000399 else
John McCall4d4e5c12012-02-15 01:22:51 +0000400 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000401
402 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000403 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
404 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
405 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000406 }
407
John McCalld608cdb2010-08-22 10:59:02 +0000408 // The this-adjustment is left-shifted by 1 on ARM.
409 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000410 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
411 offset <<= 1;
412 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000413 }
414
John McCall4d4e5c12012-02-15 01:22:51 +0000415 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
416 llvm::Value *dstAdj;
417 if (isDerivedToBase)
418 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000419 else
John McCall4d4e5c12012-02-15 01:22:51 +0000420 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000421
John McCall4d4e5c12012-02-15 01:22:51 +0000422 return Builder.CreateInsertValue(src, dstAdj, 1);
423}
424
425llvm::Constant *
426ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
427 llvm::Constant *src) {
428 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
429 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
430 E->getCastKind() == CK_ReinterpretMemberPointer);
431
432 // Under Itanium, reinterprets don't require any additional processing.
433 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
434
435 // If the adjustment is trivial, we don't need to do anything.
436 llvm::Constant *adj = getMemberPointerAdjustment(E);
437 if (!adj) return src;
438
439 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
440
441 const MemberPointerType *destTy =
442 E->getType()->castAs<MemberPointerType>();
443
444 // For member data pointers, this is just a matter of adding the
445 // offset if the source is non-null.
446 if (destTy->isMemberDataPointer()) {
447 // null maps to null.
448 if (src->isAllOnesValue()) return src;
449
450 if (isDerivedToBase)
451 return llvm::ConstantExpr::getNSWSub(src, adj);
452 else
453 return llvm::ConstantExpr::getNSWAdd(src, adj);
454 }
455
456 // The this-adjustment is left-shifted by 1 on ARM.
457 if (IsARM) {
458 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
459 offset <<= 1;
460 adj = llvm::ConstantInt::get(adj->getType(), offset);
461 }
462
463 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
464 llvm::Constant *dstAdj;
465 if (isDerivedToBase)
466 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
467 else
468 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
469
470 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000471}
John McCallcf2c85e2010-08-22 04:16:24 +0000472
473llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000474ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall0bab0cd2010-08-23 01:21:21 +0000475 // Itanium C++ ABI 2.3:
476 // A NULL pointer is represented as -1.
477 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000478 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000479
Reid Kleckner92e44d92013-03-22 16:13:10 +0000480 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalld608cdb2010-08-22 10:59:02 +0000481 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000482 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000483}
484
John McCall5808ce42011-02-03 08:15:49 +0000485llvm::Constant *
486ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
487 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000488 // Itanium C++ ABI 2.3:
489 // A pointer to data member is an offset from the base address of
490 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner92e44d92013-03-22 16:13:10 +0000491 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000492}
493
John McCall755d8492011-04-12 00:42:48 +0000494llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000495 return BuildMemberPointer(MD, CharUnits::Zero());
496}
497
498llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
499 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000500 assert(MD->isInstance() && "Member function must not be static!");
501 MD = MD->getCanonicalDecl();
502
503 CodeGenTypes &Types = CGM.getTypes();
John McCalld608cdb2010-08-22 10:59:02 +0000504
505 // Get the function pointer (or index if this is a virtual function).
506 llvm::Constant *MemPtr[2];
507 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000508 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000509
Ken Dyck1246ba62011-04-09 01:30:02 +0000510 const ASTContext &Context = getContext();
511 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000512 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000513 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000514
515 if (IsARM) {
516 // ARM C++ ABI 3.2.1:
517 // This ABI specifies that adj contains twice the this
518 // adjustment, plus 1 if the member function is virtual. The
519 // least significant bit of adj then makes exactly the same
520 // discrimination as the least significant bit of ptr does for
521 // Itanium.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000522 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
523 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000524 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000525 } else {
526 // Itanium C++ ABI 2.3:
527 // For a virtual function, [the pointer field] is 1 plus the
528 // virtual table offset (in bytes) of the function,
529 // represented as a ptrdiff_t.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000530 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
531 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000532 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000533 }
534 } else {
John McCall755d8492011-04-12 00:42:48 +0000535 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000536 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000537 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000538 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000539 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000540 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000541 } else {
John McCall755d8492011-04-12 00:42:48 +0000542 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
543 // function type is incomplete.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000544 Ty = CGM.PtrDiffTy;
John McCalld608cdb2010-08-22 10:59:02 +0000545 }
John McCall755d8492011-04-12 00:42:48 +0000546 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000547
Reid Kleckner92e44d92013-03-22 16:13:10 +0000548 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
549 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, (IsARM ? 2 : 1) *
Richard Smith2d6a5672012-01-14 04:30:29 +0000550 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000551 }
John McCall875ab102010-08-22 06:43:33 +0000552
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000553 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000554}
555
Richard Smith2d6a5672012-01-14 04:30:29 +0000556llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
557 QualType MPType) {
558 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
559 const ValueDecl *MPD = MP.getMemberPointerDecl();
560 if (!MPD)
561 return EmitNullMemberPointer(MPT);
562
Reid Klecknerf6327302013-05-09 21:01:17 +0000563 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smith2d6a5672012-01-14 04:30:29 +0000564
565 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
566 return BuildMemberPointer(MD, ThisAdjustment);
567
568 CharUnits FieldOffset =
569 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
570 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
571}
572
John McCalle9fd7eb2010-08-22 08:30:07 +0000573/// The comparison algorithm is pretty easy: the member pointers are
574/// the same if they're either bitwise identical *or* both null.
575///
576/// ARM is different here only because null-ness is more complicated.
577llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000578ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
579 llvm::Value *L,
580 llvm::Value *R,
581 const MemberPointerType *MPT,
582 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000583 CGBuilderTy &Builder = CGF.Builder;
584
John McCalle9fd7eb2010-08-22 08:30:07 +0000585 llvm::ICmpInst::Predicate Eq;
586 llvm::Instruction::BinaryOps And, Or;
587 if (Inequality) {
588 Eq = llvm::ICmpInst::ICMP_NE;
589 And = llvm::Instruction::Or;
590 Or = llvm::Instruction::And;
591 } else {
592 Eq = llvm::ICmpInst::ICMP_EQ;
593 And = llvm::Instruction::And;
594 Or = llvm::Instruction::Or;
595 }
596
John McCall0bab0cd2010-08-23 01:21:21 +0000597 // Member data pointers are easy because there's a unique null
598 // value, so it just comes down to bitwise equality.
599 if (MPT->isMemberDataPointer())
600 return Builder.CreateICmp(Eq, L, R);
601
602 // For member function pointers, the tautologies are more complex.
603 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000604 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000605 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000606 // (L == R) <==> (L.ptr == R.ptr &&
607 // (L.adj == R.adj ||
608 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000609 // The inequality tautologies have exactly the same structure, except
610 // applying De Morgan's laws.
611
612 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
613 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
614
John McCalle9fd7eb2010-08-22 08:30:07 +0000615 // This condition tests whether L.ptr == R.ptr. This must always be
616 // true for equality to hold.
617 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
618
619 // This condition, together with the assumption that L.ptr == R.ptr,
620 // tests whether the pointers are both null. ARM imposes an extra
621 // condition.
622 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
623 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
624
625 // This condition tests whether L.adj == R.adj. If this isn't
626 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000627 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
628 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000629 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
630
631 // Null member function pointers on ARM clear the low bit of Adj,
632 // so the zero condition has to check that neither low bit is set.
633 if (IsARM) {
634 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
635
636 // Compute (l.adj | r.adj) & 1 and test it against zero.
637 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
638 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
639 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
640 "cmp.or.adj");
641 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
642 }
643
644 // Tie together all our conditions.
645 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
646 Result = Builder.CreateBinOp(And, PtrEq, Result,
647 Inequality ? "memptr.ne" : "memptr.eq");
648 return Result;
649}
650
651llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000652ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
653 llvm::Value *MemPtr,
654 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000655 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000656
657 /// For member data pointers, this is just a check against -1.
658 if (MPT->isMemberDataPointer()) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000659 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall0bab0cd2010-08-23 01:21:21 +0000660 llvm::Value *NegativeOne =
661 llvm::Constant::getAllOnesValue(MemPtr->getType());
662 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
663 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000664
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000665 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000666 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000667
668 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
669 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
670
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000671 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
672 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000673 if (IsARM) {
674 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000675 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000676 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000677 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
678 "memptr.isvirtual");
679 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000680 }
681
682 return Result;
683}
John McCall875ab102010-08-22 06:43:33 +0000684
John McCallf16aa102010-08-22 21:01:12 +0000685/// The Itanium ABI requires non-zero initialization only for data
686/// member pointers, for which '0' is a valid offset.
687bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
688 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000689}
John McCall4c40d982010-08-31 07:33:07 +0000690
John McCallecd03b42012-09-25 10:10:39 +0000691/// The Itanium ABI always places an offset to the complete object
692/// at entry -2 in the vtable.
693llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
694 llvm::Value *ptr,
695 QualType type) {
696 // Grab the vtable pointer as an intptr_t*.
697 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
698
699 // Track back to entry -2 and pull out the offset there.
700 llvm::Value *offsetPtr =
701 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
702 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
703 offset->setAlignment(CGF.PointerAlignInBytes);
704
705 // Apply the offset.
706 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
707 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
708}
709
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000710llvm::Value *
711ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
712 llvm::Value *This,
713 const CXXRecordDecl *ClassDecl,
714 const CXXRecordDecl *BaseClassDecl) {
715 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
716 CharUnits VBaseOffsetOffset =
717 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
718
719 llvm::Value *VBaseOffsetPtr =
720 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
721 "vbase.offset.ptr");
722 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
723 CGM.PtrDiffTy->getPointerTo());
724
725 llvm::Value *VBaseOffset =
726 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
727
728 return VBaseOffset;
729}
730
John McCall4c40d982010-08-31 07:33:07 +0000731/// The generic ABI passes 'this', plus a VTT if it's initializing a
732/// base subobject.
733void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
734 CXXCtorType Type,
735 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000736 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000737 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000738
Stephen Lind4c0cd02013-06-18 17:00:49 +0000739 // 'this' parameter is already there, as well as 'this' return if
740 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000741
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
John McCall4c40d982010-08-31 07:33:07 +0000747/// The generic ABI passes 'this', plus a VTT if it's destroying a
748/// base subobject.
749void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
750 CXXDtorType Type,
751 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000752 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000753 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000754
Stephen Lind4c0cd02013-06-18 17:00:49 +0000755 // 'this' parameter is already there, as well as 'this' return if
756 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000757
758 // Check if we need to add a VTT parameter (which has type void **).
759 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
760 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
761}
762
John McCall4c40d982010-08-31 07:33:07 +0000763void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
764 QualType &ResTy,
765 FunctionArgList &Params) {
766 /// Create the 'this' variable.
767 BuildThisParam(CGF, Params);
768
769 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
770 assert(MD->isInstance());
771
772 // Check if we need a VTT parameter as well.
773 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000774 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000775
776 // FIXME: avoid the fake decl
777 QualType T = Context.getPointerType(Context.VoidPtrTy);
778 ImplicitParamDecl *VTTDecl
779 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
780 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000781 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000782 getVTTDecl(CGF) = VTTDecl;
783 }
784}
785
John McCall4c40d982010-08-31 07:33:07 +0000786void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
787 /// Initialize the 'this' slot.
788 EmitThisParam(CGF);
789
790 /// Initialize the 'vtt' slot if needed.
791 if (getVTTDecl(CGF)) {
792 getVTTValue(CGF)
793 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
794 "vtt");
795 }
John McCall4c40d982010-08-31 07:33:07 +0000796
Stephen Lind4c0cd02013-06-18 17:00:49 +0000797 /// If this is a function that the ABI specifies returns 'this', initialize
798 /// the return slot to 'this' at the start of the function.
799 ///
800 /// Unlike the setting of return types, this is done within the ABI
801 /// implementation instead of by clients of CGCXXABI because:
802 /// 1) getThisValue is currently protected
803 /// 2) in theory, an ABI could implement 'this' returns some other way;
804 /// HasThisReturn only specifies a contract, not the implementation
John McCall4c40d982010-08-31 07:33:07 +0000805 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000806 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000807}
808
Stephen Lind4c0cd02013-06-18 17:00:49 +0000809RValue ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000810 const CXXConstructorDecl *D,
Stephen Lind4c0cd02013-06-18 17:00:49 +0000811 CXXCtorType Type,
812 bool ForVirtualBase, bool Delegating,
813 ReturnValueSlot ReturnValue,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000814 llvm::Value *This,
815 CallExpr::const_arg_iterator ArgBeg,
816 CallExpr::const_arg_iterator ArgEnd) {
817 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
818 Delegating);
819 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
820 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
821
822 // FIXME: Provide a source location here.
Stephen Lind4c0cd02013-06-18 17:00:49 +0000823 return CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValue,
824 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000825}
826
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000827RValue ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
828 const CXXDestructorDecl *Dtor,
829 CXXDtorType DtorType,
830 SourceLocation CallLoc,
831 ReturnValueSlot ReturnValue,
832 llvm::Value *This) {
833 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
834
835 const CGFunctionInfo *FInfo
836 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
837 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
838 llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, DtorType, This, Ty);
839
840 return CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValue, This,
841 /*ImplicitParam=*/0, QualType(), 0, 0);
842}
843
John McCall4c40d982010-08-31 07:33:07 +0000844void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
845 RValue RV, QualType ResultType) {
846 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
847 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
848
849 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000850 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000851 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
852 RValue Undef = RValue::get(llvm::UndefValue::get(T));
853 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
854}
John McCall1e7fe752010-09-02 09:58:18 +0000855
856/************************** Array allocation cookies **************************/
857
John McCalle2b45e22012-05-01 05:23:51 +0000858CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
859 // The array cookie is a size_t; pad that up to the element alignment.
860 // The cookie is actually right-justified in that space.
861 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
862 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000863}
864
865llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
866 llvm::Value *NewPtr,
867 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000868 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000869 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000870 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000871
Micah Villmow956a5a12012-10-25 15:39:14 +0000872 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000873
John McCall9cb2cee2010-09-02 10:25:57 +0000874 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000875 QualType SizeTy = Ctx.getSizeType();
876 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
877
878 // The size of the cookie.
879 CharUnits CookieSize =
880 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000881 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000882
883 // Compute an offset to the cookie.
884 llvm::Value *CookiePtr = NewPtr;
885 CharUnits CookieOffset = CookieSize - SizeSize;
886 if (!CookieOffset.isZero())
887 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
888 CookieOffset.getQuantity());
889
890 // Write the number of elements into the appropriate slot.
891 llvm::Value *NumElementsPtr
892 = CGF.Builder.CreateBitCast(CookiePtr,
893 CGF.ConvertType(SizeTy)->getPointerTo(AS));
894 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
895
896 // Finally, compute a pointer to the actual data buffer by skipping
897 // over the cookie completely.
898 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
899 CookieSize.getQuantity());
900}
901
John McCalle2b45e22012-05-01 05:23:51 +0000902llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
903 llvm::Value *allocPtr,
904 CharUnits cookieSize) {
905 // The element size is right-justified in the cookie.
906 llvm::Value *numElementsPtr = allocPtr;
907 CharUnits numElementsOffset =
908 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
909 if (!numElementsOffset.isZero())
910 numElementsPtr =
911 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
912 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000913
Micah Villmow956a5a12012-10-25 15:39:14 +0000914 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000915 numElementsPtr =
916 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
917 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000918}
919
John McCalle2b45e22012-05-01 05:23:51 +0000920CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +0000921 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +0000922 // struct array_cookie {
923 // std::size_t element_size; // element_size != 0
924 // std::size_t element_count;
925 // };
John McCallf3bbb152013-01-25 23:36:19 +0000926 // But the base ABI doesn't give anything an alignment greater than
927 // 8, so we can dismiss this as typical ABI-author blindness to
928 // actual language complexity and round up to the element alignment.
929 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
930 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000931}
932
933llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +0000934 llvm::Value *newPtr,
935 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +0000936 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +0000937 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000938 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000939
John McCallf3bbb152013-01-25 23:36:19 +0000940 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
941 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000942
943 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +0000944 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +0000945
946 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +0000947 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
948 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
949 getContext().getTypeSizeInChars(elementType).getQuantity());
950 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000951
952 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +0000953 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
954 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000955
956 // Finally, compute a pointer to the actual data buffer by skipping
957 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +0000958 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
959 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
960 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000961}
962
John McCalle2b45e22012-05-01 05:23:51 +0000963llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
964 llvm::Value *allocPtr,
965 CharUnits cookieSize) {
966 // The number of elements is at offset sizeof(size_t) relative to
967 // the allocated pointer.
968 llvm::Value *numElementsPtr
969 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000970
Micah Villmow956a5a12012-10-25 15:39:14 +0000971 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000972 numElementsPtr =
973 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
974 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000975}
976
John McCall5cd91b52010-09-08 01:44:27 +0000977/*********************** Static local initialization **************************/
978
979static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000980 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000981 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000982 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +0000983 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +0000984 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000985 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +0000986 llvm::AttributeSet::get(CGM.getLLVMContext(),
987 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +0000988 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000989}
990
991static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000992 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000993 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000994 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000995 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000996 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +0000997 llvm::AttributeSet::get(CGM.getLLVMContext(),
998 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +0000999 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001000}
1001
1002static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001003 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001004 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001005 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001006 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001007 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001008 llvm::AttributeSet::get(CGM.getLLVMContext(),
1009 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001010 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001011}
1012
1013namespace {
1014 struct CallGuardAbort : EHScopeStack::Cleanup {
1015 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001016 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001017
John McCallad346f42011-07-12 20:27:29 +00001018 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbd7370a2013-02-28 19:01:20 +00001019 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1020 Guard);
John McCall5cd91b52010-09-08 01:44:27 +00001021 }
1022 };
1023}
1024
1025/// The ARM code here follows the Itanium code closely enough that we
1026/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001027void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1028 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001029 llvm::GlobalVariable *var,
1030 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001031 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001032
Richard Smith04e51762013-04-14 23:01:42 +00001033 // We only need to use thread-safe statics for local non-TLS variables;
John McCall3030eb82010-11-06 09:44:32 +00001034 // global initialization is always single-threaded.
Richard Smith04e51762013-04-14 23:01:42 +00001035 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1036 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlsson173d5122011-04-27 04:37:08 +00001037
Anders Carlsson173d5122011-04-27 04:37:08 +00001038 // If we have a global variable with internal linkage and thread-safe statics
1039 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001040 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1041
1042 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001043 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001044 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001045 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001046 // Guard variables are 64 bits in the generic ABI and size width on ARM
1047 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1048 guardTy = (IsARM ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001049 }
John McCall355bba72012-03-30 21:00:39 +00001050 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001051
John McCall355bba72012-03-30 21:00:39 +00001052 // Create the guard variable if we don't already have it (as we
1053 // might if we're double-emitting this function body).
1054 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1055 if (!guard) {
1056 // Mangle the name for the guard.
1057 SmallString<256> guardName;
1058 {
1059 llvm::raw_svector_ostream out(guardName);
1060 getMangleContext().mangleItaniumGuardVariable(&D, out);
1061 out.flush();
1062 }
John McCall112c9672010-11-02 21:04:24 +00001063
John McCall355bba72012-03-30 21:00:39 +00001064 // Create the guard variable with a zero-initializer.
1065 // Just absorb linkage and visibility from the guarded variable.
1066 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1067 false, var->getLinkage(),
1068 llvm::ConstantInt::get(guardTy, 0),
1069 guardName.str());
1070 guard->setVisibility(var->getVisibility());
Richard Smith04e51762013-04-14 23:01:42 +00001071 // If the variable is thread-local, so is its guard variable.
1072 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall355bba72012-03-30 21:00:39 +00001073
1074 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1075 }
John McCall49d26d22012-03-30 07:09:50 +00001076
John McCall5cd91b52010-09-08 01:44:27 +00001077 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001078 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001079
1080 // ARM C++ ABI 3.2.3.1:
1081 // To support the potential use of initialization guard variables
1082 // as semaphores that are the target of ARM SWP and LDREX/STREX
1083 // synchronizing instructions we define a static initialization
1084 // guard variable to be a 4-byte aligned, 4- byte word with the
1085 // following inline access protocol.
1086 // #define INITIALIZED 1
1087 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1088 // if (__cxa_guard_acquire(&obj_guard))
1089 // ...
1090 // }
John McCall0502a222011-06-17 07:33:57 +00001091 if (IsARM && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001092 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001093 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1094 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001095 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001096
1097 // Itanium C++ ABI 3.3.2:
1098 // The following is pseudo-code showing how these functions can be used:
1099 // if (obj_guard.first_byte == 0) {
1100 // if ( __cxa_guard_acquire (&obj_guard) ) {
1101 // try {
1102 // ... initialize the object ...;
1103 // } catch (...) {
1104 // __cxa_guard_abort (&obj_guard);
1105 // throw;
1106 // }
1107 // ... queue object destructor with __cxa_atexit() ...;
1108 // __cxa_guard_release (&obj_guard);
1109 // }
1110 // }
1111 } else {
1112 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001113 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001114 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001115 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001116
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001117 // Itanium ABI:
1118 // An implementation supporting thread-safety on multiprocessor
1119 // systems must also guarantee that references to the initialized
1120 // object do not occur before the load of the initialization flag.
1121 //
1122 // In LLVM, we do this by marking the load Acquire.
1123 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001124 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001125
John McCall355bba72012-03-30 21:00:39 +00001126 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001127 }
1128
1129 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1130 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1131
1132 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001133 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001134
1135 CGF.EmitBlock(InitCheckBlock);
1136
1137 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001138 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001139 // Call __cxa_guard_acquire.
1140 llvm::Value *V
John McCallbd7370a2013-02-28 19:01:20 +00001141 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001142
1143 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1144
1145 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1146 InitBlock, EndBlock);
1147
1148 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001149 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001150
1151 CGF.EmitBlock(InitBlock);
1152 }
1153
1154 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001155 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001156
John McCall0502a222011-06-17 07:33:57 +00001157 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001158 // Pop the guard-abort cleanup if we pushed one.
1159 CGF.PopCleanupBlock();
1160
1161 // Call __cxa_guard_release. This cannot throw.
John McCallbd7370a2013-02-28 19:01:20 +00001162 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001163 } else {
John McCall355bba72012-03-30 21:00:39 +00001164 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001165 }
1166
1167 CGF.EmitBlock(EndBlock);
1168}
John McCall20bb1752012-05-01 06:13:13 +00001169
1170/// Register a global destructor using __cxa_atexit.
1171static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1172 llvm::Constant *dtor,
Richard Smith04e51762013-04-14 23:01:42 +00001173 llvm::Constant *addr,
1174 bool TLS) {
Bill Wendling4e3b54b2013-05-02 19:18:03 +00001175 const char *Name = "__cxa_atexit";
1176 if (TLS) {
1177 const llvm::Triple &T = CGF.getTarget().getTriple();
1178 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1179 }
Richard Smith04e51762013-04-14 23:01:42 +00001180
John McCall20bb1752012-05-01 06:13:13 +00001181 // We're assuming that the destructor function is something we can
1182 // reasonably call with the default CC. Go ahead and cast it to the
1183 // right prototype.
1184 llvm::Type *dtorTy =
1185 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1186
1187 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1188 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1189 llvm::FunctionType *atexitTy =
1190 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1191
1192 // Fetch the actual function.
Richard Smith04e51762013-04-14 23:01:42 +00001193 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCall20bb1752012-05-01 06:13:13 +00001194 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1195 fn->setDoesNotThrow();
1196
1197 // Create a variable that binds the atexit to this shared object.
1198 llvm::Constant *handle =
1199 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1200
1201 llvm::Value *args[] = {
1202 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1203 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1204 handle
1205 };
John McCallbd7370a2013-02-28 19:01:20 +00001206 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCall20bb1752012-05-01 06:13:13 +00001207}
1208
1209/// Register a global destructor as best as we know how.
1210void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smith04e51762013-04-14 23:01:42 +00001211 const VarDecl &D,
John McCall20bb1752012-05-01 06:13:13 +00001212 llvm::Constant *dtor,
1213 llvm::Constant *addr) {
1214 // Use __cxa_atexit if available.
Richard Smith04e51762013-04-14 23:01:42 +00001215 if (CGM.getCodeGenOpts().CXAAtExit)
1216 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1217
1218 if (D.getTLSKind())
1219 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCall20bb1752012-05-01 06:13:13 +00001220
1221 // In Apple kexts, we want to add a global destructor entry.
1222 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001223 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001224 // Generate a global destructor entry.
1225 return CGM.AddCXXDtorEntry(dtor, addr);
1226 }
1227
1228 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1229}
Richard Smithb80a16e2013-04-19 16:42:07 +00001230
1231/// Get the appropriate linkage for the wrapper function. This is essentially
1232/// the weak form of the variable's linkage; every translation unit which wneeds
1233/// the wrapper emits a copy, and we want the linker to merge them.
1234static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1235 llvm::GlobalValue::LinkageTypes VarLinkage) {
1236 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1237 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1238 // For internal linkage variables, we don't need an external or weak wrapper.
1239 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1240 return VarLinkage;
1241 return llvm::GlobalValue::WeakODRLinkage;
1242}
1243
1244llvm::Function *
1245ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1246 llvm::GlobalVariable *Var) {
1247 // Mangle the name for the thread_local wrapper function.
1248 SmallString<256> WrapperName;
1249 {
1250 llvm::raw_svector_ostream Out(WrapperName);
1251 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1252 Out.flush();
1253 }
1254
1255 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1256 return cast<llvm::Function>(V);
1257
1258 llvm::Type *RetTy = Var->getType();
1259 if (VD->getType()->isReferenceType())
1260 RetTy = RetTy->getPointerElementType();
1261
1262 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1263 llvm::Function *Wrapper = llvm::Function::Create(
1264 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1265 &CGM.getModule());
1266 // Always resolve references to the wrapper at link time.
1267 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1268 return Wrapper;
1269}
1270
1271void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1272 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1273 llvm::Function *InitFunc) {
1274 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1275 const VarDecl *VD = Decls[I].first;
1276 llvm::GlobalVariable *Var = Decls[I].second;
1277
1278 // Mangle the name for the thread_local initialization function.
1279 SmallString<256> InitFnName;
1280 {
1281 llvm::raw_svector_ostream Out(InitFnName);
1282 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1283 Out.flush();
1284 }
1285
1286 // If we have a definition for the variable, emit the initialization
1287 // function as an alias to the global Init function (if any). Otherwise,
1288 // produce a declaration of the initialization function.
1289 llvm::GlobalValue *Init = 0;
1290 bool InitIsInitFunc = false;
1291 if (VD->hasDefinition()) {
1292 InitIsInitFunc = true;
1293 if (InitFunc)
1294 Init =
1295 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1296 InitFnName.str(), InitFunc, &CGM.getModule());
1297 } else {
1298 // Emit a weak global function referring to the initialization function.
1299 // This function will not exist if the TU defining the thread_local
1300 // variable in question does not need any dynamic initialization for
1301 // its thread_local variables.
1302 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1303 Init = llvm::Function::Create(
1304 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1305 &CGM.getModule());
1306 }
1307
1308 if (Init)
1309 Init->setVisibility(Var->getVisibility());
1310
1311 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1312 llvm::LLVMContext &Context = CGM.getModule().getContext();
1313 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1314 CGBuilderTy Builder(Entry);
1315 if (InitIsInitFunc) {
1316 if (Init)
1317 Builder.CreateCall(Init);
1318 } else {
1319 // Don't know whether we have an init function. Call it if it exists.
1320 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1321 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1322 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1323 Builder.CreateCondBr(Have, InitBB, ExitBB);
1324
1325 Builder.SetInsertPoint(InitBB);
1326 Builder.CreateCall(Init);
1327 Builder.CreateBr(ExitBB);
1328
1329 Builder.SetInsertPoint(ExitBB);
1330 }
1331
1332 // For a reference, the result of the wrapper function is a pointer to
1333 // the referenced object.
1334 llvm::Value *Val = Var;
1335 if (VD->getType()->isReferenceType()) {
1336 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1337 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1338 Val = LI;
1339 }
1340
1341 Builder.CreateRet(Val);
1342 }
1343}
1344
1345LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1346 const DeclRefExpr *DRE) {
1347 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1348 QualType T = VD->getType();
1349 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1350 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1351 llvm::Function *Wrapper =
1352 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1353
1354 Val = CGF.Builder.CreateCall(Wrapper);
1355
1356 LValue LV;
1357 if (VD->getType()->isReferenceType())
1358 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1359 else
1360 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1361 CGF.getContext().getDeclAlign(VD));
1362 // FIXME: need setObjCGCLValueClass?
1363 return LV;
1364}