blob: 51c1dc5e59089cda5d7516774de17980386a5db1 [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 Lin4444dbb2013-06-19 18:10:35 +0000122 void EmitConstructorCall(CodeGenFunction &CGF,
123 const CXXConstructorDecl *D, CXXCtorType Type,
124 bool ForVirtualBase, bool Delegating,
125 llvm::Value *This,
126 CallExpr::const_arg_iterator ArgBeg,
127 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000128
Stephen Lin4444dbb2013-06-19 18:10:35 +0000129 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
130 const CXXDestructorDecl *Dtor,
131 CXXDtorType DtorType, SourceLocation CallLoc,
132 llvm::Value *This);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000133
Reid Kleckner90633022013-06-19 15:20:38 +0000134 void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage,
135 const CXXRecordDecl *RD);
136
Joao Matos285baac2012-07-17 17:10:11 +0000137 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000138 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000139
John McCalle2b45e22012-05-01 05:23:51 +0000140 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000141 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
142 llvm::Value *NewPtr,
143 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000144 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000145 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000146 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
147 llvm::Value *allocPtr,
148 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000149
John McCall3030eb82010-11-06 09:44:32 +0000150 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000151 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smith04e51762013-04-14 23:01:42 +0000152 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
153 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smithb80a16e2013-04-19 16:42:07 +0000154
155 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
156 llvm::GlobalVariable *Var);
157 void EmitThreadLocalInitFuncs(
158 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
159 llvm::Function *InitFunc);
160 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
161 const DeclRefExpr *DRE);
Charles Davis3a811f12010-05-25 19:52:27 +0000162};
John McCallee79a4c2010-08-21 22:46:04 +0000163
164class ARMCXXABI : public ItaniumCXXABI {
165public:
John McCallbabc9a92010-08-22 00:59:17 +0000166 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000167
Stephen Lind4c0cd02013-06-18 17:00:49 +0000168 bool HasThisReturn(GlobalDecl GD) const {
169 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
170 isa<CXXDestructorDecl>(GD.getDecl()) &&
171 GD.getDtorType() != Dtor_Deleting));
172 }
John McCall4c40d982010-08-31 07:33:07 +0000173
174 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
175
John McCalle2b45e22012-05-01 05:23:51 +0000176 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000177 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
178 llvm::Value *NewPtr,
179 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000180 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000181 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000182 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
183 CharUnits cookieSize);
John McCallee79a4c2010-08-21 22:46:04 +0000184};
Charles Davis3a811f12010-05-25 19:52:27 +0000185}
186
Charles Davis071cc7d2010-08-16 03:33:14 +0000187CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +0000188 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall96fcde02013-01-25 23:36:14 +0000189 // For IR-generation purposes, there's no significant difference
190 // between the ARM and iOS ABIs.
191 case TargetCXXABI::GenericARM:
192 case TargetCXXABI::iOS:
193 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000194
Tim Northoverc264e162013-01-31 12:13:10 +0000195 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
196 // include the other 32-bit ARM oddities: constructor/destructor return values
197 // and array cookies.
198 case TargetCXXABI::GenericAArch64:
199 return new ItaniumCXXABI(CGM, /*IsARM = */ true);
200
John McCall96fcde02013-01-25 23:36:14 +0000201 case TargetCXXABI::GenericItanium:
202 return new ItaniumCXXABI(CGM);
203
204 case TargetCXXABI::Microsoft:
205 llvm_unreachable("Microsoft ABI is not Itanium-based");
206 }
207 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000208}
209
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000210llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000211ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
212 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000213 return CGM.PtrDiffTy;
214 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall875ab102010-08-22 06:43:33 +0000215}
216
John McCallbabc9a92010-08-22 00:59:17 +0000217/// In the Itanium and ARM ABIs, method pointers have the form:
218/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
219///
220/// In the Itanium ABI:
221/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
222/// - the this-adjustment is (memptr.adj)
223/// - the virtual offset is (memptr.ptr - 1)
224///
225/// In the ARM ABI:
226/// - method pointers are virtual if (memptr.adj & 1) is nonzero
227/// - the this-adjustment is (memptr.adj >> 1)
228/// - the virtual offset is (memptr.ptr)
229/// ARM uses 'adj' for the virtual flag because Thumb functions
230/// may be only single-byte aligned.
231///
232/// If the member is virtual, the adjusted 'this' pointer points
233/// to a vtable pointer from which the virtual offset is applied.
234///
235/// If the member is non-virtual, memptr.ptr is the address of
236/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000237llvm::Value *
238ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
239 llvm::Value *&This,
240 llvm::Value *MemFnPtr,
241 const MemberPointerType *MPT) {
242 CGBuilderTy &Builder = CGF.Builder;
243
244 const FunctionProtoType *FPT =
245 MPT->getPointeeType()->getAs<FunctionProtoType>();
246 const CXXRecordDecl *RD =
247 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
248
Chris Lattner2acc6e32011-07-18 04:24:23 +0000249 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000250 CGM.getTypes().GetFunctionType(
251 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000252
Reid Kleckner92e44d92013-03-22 16:13:10 +0000253 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall93d557b2010-08-22 00:05:51 +0000254
John McCallbabc9a92010-08-22 00:59:17 +0000255 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
256 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
257 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
258
John McCalld608cdb2010-08-22 10:59:02 +0000259 // Extract memptr.adj, which is in the second field.
260 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000261
262 // Compute the true adjustment.
263 llvm::Value *Adj = RawAdj;
264 if (IsARM)
265 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000266
267 // Apply the adjustment and cast back to the original struct type
268 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000269 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
270 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
271 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000272
273 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000274 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000275
276 // If the LSB in the function pointer is 1, the function pointer points to
277 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000278 llvm::Value *IsVirtual;
279 if (IsARM)
280 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
281 else
282 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
283 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000284 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
285
286 // In the virtual path, the adjustment left 'This' pointing to the
287 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000288 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000289 CGF.EmitBlock(FnVirtual);
290
291 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000292 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000293 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000294 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000295
296 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000297 llvm::Value *VTableOffset = FnAsInt;
298 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
299 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000300
301 // Load the virtual function to call.
302 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000303 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000304 CGF.EmitBranch(FnEnd);
305
306 // In the non-virtual path, the function pointer is actually a
307 // function pointer.
308 CGF.EmitBlock(FnNonVirtual);
309 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000310 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000311
312 // We're done.
313 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000314 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000315 Callee->addIncoming(VirtualFn, FnVirtual);
316 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
317 return Callee;
318}
John McCall3023def2010-08-22 03:04:22 +0000319
John McCall6c2ab1d2010-08-31 21:07:20 +0000320/// Compute an l-value by applying the given pointer-to-member to a
321/// base object.
322llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
323 llvm::Value *Base,
324 llvm::Value *MemPtr,
325 const MemberPointerType *MPT) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000326 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall6c2ab1d2010-08-31 21:07:20 +0000327
328 CGBuilderTy &Builder = CGF.Builder;
329
Micah Villmow956a5a12012-10-25 15:39:14 +0000330 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000331
332 // Cast to char*.
333 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
334
335 // Apply the offset, which we assume is non-null.
336 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
337
338 // Cast the address to the appropriate pointer type, adopting the
339 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000340 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000341 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000342 return Builder.CreateBitCast(Addr, PType);
343}
344
John McCall4d4e5c12012-02-15 01:22:51 +0000345/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
346/// conversion.
347///
348/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000349///
350/// Obligatory offset/adjustment diagram:
351/// <-- offset --> <-- adjustment -->
352/// |--------------------------|----------------------|--------------------|
353/// ^Derived address point ^Base address point ^Member address point
354///
355/// So when converting a base member pointer to a derived member pointer,
356/// we add the offset to the adjustment because the address point has
357/// decreased; and conversely, when converting a derived MP to a base MP
358/// we subtract the offset from the adjustment because the address point
359/// has increased.
360///
361/// The standard forbids (at compile time) conversion to and from
362/// virtual bases, which is why we don't have to consider them here.
363///
364/// The standard forbids (at run time) casting a derived MP to a base
365/// MP when the derived MP does not point to a member of the base.
366/// This is why -1 is a reasonable choice for null data member
367/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000368llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000369ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
370 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000371 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000372 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000373 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
374 E->getCastKind() == CK_ReinterpretMemberPointer);
375
376 // Under Itanium, reinterprets don't require any additional processing.
377 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
378
379 // Use constant emission if we can.
380 if (isa<llvm::Constant>(src))
381 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
382
383 llvm::Constant *adj = getMemberPointerAdjustment(E);
384 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000385
386 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000387 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000388
John McCall4d4e5c12012-02-15 01:22:51 +0000389 const MemberPointerType *destTy =
390 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000391
John McCall0bab0cd2010-08-23 01:21:21 +0000392 // For member data pointers, this is just a matter of adding the
393 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000394 if (destTy->isMemberDataPointer()) {
395 llvm::Value *dst;
396 if (isDerivedToBase)
397 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000398 else
John McCall4d4e5c12012-02-15 01:22:51 +0000399 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000400
401 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000402 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
403 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
404 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000405 }
406
John McCalld608cdb2010-08-22 10:59:02 +0000407 // The this-adjustment is left-shifted by 1 on ARM.
408 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000409 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
410 offset <<= 1;
411 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000412 }
413
John McCall4d4e5c12012-02-15 01:22:51 +0000414 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
415 llvm::Value *dstAdj;
416 if (isDerivedToBase)
417 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000418 else
John McCall4d4e5c12012-02-15 01:22:51 +0000419 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000420
John McCall4d4e5c12012-02-15 01:22:51 +0000421 return Builder.CreateInsertValue(src, dstAdj, 1);
422}
423
424llvm::Constant *
425ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
426 llvm::Constant *src) {
427 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
428 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
429 E->getCastKind() == CK_ReinterpretMemberPointer);
430
431 // Under Itanium, reinterprets don't require any additional processing.
432 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
433
434 // If the adjustment is trivial, we don't need to do anything.
435 llvm::Constant *adj = getMemberPointerAdjustment(E);
436 if (!adj) return src;
437
438 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
439
440 const MemberPointerType *destTy =
441 E->getType()->castAs<MemberPointerType>();
442
443 // For member data pointers, this is just a matter of adding the
444 // offset if the source is non-null.
445 if (destTy->isMemberDataPointer()) {
446 // null maps to null.
447 if (src->isAllOnesValue()) return src;
448
449 if (isDerivedToBase)
450 return llvm::ConstantExpr::getNSWSub(src, adj);
451 else
452 return llvm::ConstantExpr::getNSWAdd(src, adj);
453 }
454
455 // The this-adjustment is left-shifted by 1 on ARM.
456 if (IsARM) {
457 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
458 offset <<= 1;
459 adj = llvm::ConstantInt::get(adj->getType(), offset);
460 }
461
462 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
463 llvm::Constant *dstAdj;
464 if (isDerivedToBase)
465 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
466 else
467 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
468
469 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000470}
John McCallcf2c85e2010-08-22 04:16:24 +0000471
472llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000473ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall0bab0cd2010-08-23 01:21:21 +0000474 // Itanium C++ ABI 2.3:
475 // A NULL pointer is represented as -1.
476 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000477 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000478
Reid Kleckner92e44d92013-03-22 16:13:10 +0000479 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalld608cdb2010-08-22 10:59:02 +0000480 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000481 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000482}
483
John McCall5808ce42011-02-03 08:15:49 +0000484llvm::Constant *
485ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
486 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000487 // Itanium C++ ABI 2.3:
488 // A pointer to data member is an offset from the base address of
489 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner92e44d92013-03-22 16:13:10 +0000490 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000491}
492
John McCall755d8492011-04-12 00:42:48 +0000493llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000494 return BuildMemberPointer(MD, CharUnits::Zero());
495}
496
497llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
498 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000499 assert(MD->isInstance() && "Member function must not be static!");
500 MD = MD->getCanonicalDecl();
501
502 CodeGenTypes &Types = CGM.getTypes();
John McCalld608cdb2010-08-22 10:59:02 +0000503
504 // Get the function pointer (or index if this is a virtual function).
505 llvm::Constant *MemPtr[2];
506 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000507 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000508
Ken Dyck1246ba62011-04-09 01:30:02 +0000509 const ASTContext &Context = getContext();
510 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000511 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000512 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000513
514 if (IsARM) {
515 // ARM C++ ABI 3.2.1:
516 // This ABI specifies that adj contains twice the this
517 // adjustment, plus 1 if the member function is virtual. The
518 // least significant bit of adj then makes exactly the same
519 // discrimination as the least significant bit of ptr does for
520 // Itanium.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000521 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
522 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000523 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000524 } else {
525 // Itanium C++ ABI 2.3:
526 // For a virtual function, [the pointer field] is 1 plus the
527 // virtual table offset (in bytes) of the function,
528 // represented as a ptrdiff_t.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000529 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
530 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000531 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000532 }
533 } else {
John McCall755d8492011-04-12 00:42:48 +0000534 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000535 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000536 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000537 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000538 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000539 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000540 } else {
John McCall755d8492011-04-12 00:42:48 +0000541 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
542 // function type is incomplete.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000543 Ty = CGM.PtrDiffTy;
John McCalld608cdb2010-08-22 10:59:02 +0000544 }
John McCall755d8492011-04-12 00:42:48 +0000545 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000546
Reid Kleckner92e44d92013-03-22 16:13:10 +0000547 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
548 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, (IsARM ? 2 : 1) *
Richard Smith2d6a5672012-01-14 04:30:29 +0000549 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000550 }
John McCall875ab102010-08-22 06:43:33 +0000551
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000552 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000553}
554
Richard Smith2d6a5672012-01-14 04:30:29 +0000555llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
556 QualType MPType) {
557 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
558 const ValueDecl *MPD = MP.getMemberPointerDecl();
559 if (!MPD)
560 return EmitNullMemberPointer(MPT);
561
Reid Klecknerf6327302013-05-09 21:01:17 +0000562 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smith2d6a5672012-01-14 04:30:29 +0000563
564 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
565 return BuildMemberPointer(MD, ThisAdjustment);
566
567 CharUnits FieldOffset =
568 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
569 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
570}
571
John McCalle9fd7eb2010-08-22 08:30:07 +0000572/// The comparison algorithm is pretty easy: the member pointers are
573/// the same if they're either bitwise identical *or* both null.
574///
575/// ARM is different here only because null-ness is more complicated.
576llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000577ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
578 llvm::Value *L,
579 llvm::Value *R,
580 const MemberPointerType *MPT,
581 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000582 CGBuilderTy &Builder = CGF.Builder;
583
John McCalle9fd7eb2010-08-22 08:30:07 +0000584 llvm::ICmpInst::Predicate Eq;
585 llvm::Instruction::BinaryOps And, Or;
586 if (Inequality) {
587 Eq = llvm::ICmpInst::ICMP_NE;
588 And = llvm::Instruction::Or;
589 Or = llvm::Instruction::And;
590 } else {
591 Eq = llvm::ICmpInst::ICMP_EQ;
592 And = llvm::Instruction::And;
593 Or = llvm::Instruction::Or;
594 }
595
John McCall0bab0cd2010-08-23 01:21:21 +0000596 // Member data pointers are easy because there's a unique null
597 // value, so it just comes down to bitwise equality.
598 if (MPT->isMemberDataPointer())
599 return Builder.CreateICmp(Eq, L, R);
600
601 // For member function pointers, the tautologies are more complex.
602 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000603 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000604 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000605 // (L == R) <==> (L.ptr == R.ptr &&
606 // (L.adj == R.adj ||
607 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000608 // The inequality tautologies have exactly the same structure, except
609 // applying De Morgan's laws.
610
611 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
612 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
613
John McCalle9fd7eb2010-08-22 08:30:07 +0000614 // This condition tests whether L.ptr == R.ptr. This must always be
615 // true for equality to hold.
616 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
617
618 // This condition, together with the assumption that L.ptr == R.ptr,
619 // tests whether the pointers are both null. ARM imposes an extra
620 // condition.
621 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
622 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
623
624 // This condition tests whether L.adj == R.adj. If this isn't
625 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000626 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
627 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000628 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
629
630 // Null member function pointers on ARM clear the low bit of Adj,
631 // so the zero condition has to check that neither low bit is set.
632 if (IsARM) {
633 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
634
635 // Compute (l.adj | r.adj) & 1 and test it against zero.
636 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
637 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
638 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
639 "cmp.or.adj");
640 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
641 }
642
643 // Tie together all our conditions.
644 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
645 Result = Builder.CreateBinOp(And, PtrEq, Result,
646 Inequality ? "memptr.ne" : "memptr.eq");
647 return Result;
648}
649
650llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000651ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
652 llvm::Value *MemPtr,
653 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000654 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000655
656 /// For member data pointers, this is just a check against -1.
657 if (MPT->isMemberDataPointer()) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000658 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall0bab0cd2010-08-23 01:21:21 +0000659 llvm::Value *NegativeOne =
660 llvm::Constant::getAllOnesValue(MemPtr->getType());
661 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
662 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000663
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000664 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000665 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000666
667 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
668 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
669
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000670 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
671 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000672 if (IsARM) {
673 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000674 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000675 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000676 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
677 "memptr.isvirtual");
678 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000679 }
680
681 return Result;
682}
John McCall875ab102010-08-22 06:43:33 +0000683
John McCallf16aa102010-08-22 21:01:12 +0000684/// The Itanium ABI requires non-zero initialization only for data
685/// member pointers, for which '0' is a valid offset.
686bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
687 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000688}
John McCall4c40d982010-08-31 07:33:07 +0000689
John McCallecd03b42012-09-25 10:10:39 +0000690/// The Itanium ABI always places an offset to the complete object
691/// at entry -2 in the vtable.
692llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
693 llvm::Value *ptr,
694 QualType type) {
695 // Grab the vtable pointer as an intptr_t*.
696 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
697
698 // Track back to entry -2 and pull out the offset there.
699 llvm::Value *offsetPtr =
700 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
701 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
702 offset->setAlignment(CGF.PointerAlignInBytes);
703
704 // Apply the offset.
705 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
706 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
707}
708
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000709llvm::Value *
710ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
711 llvm::Value *This,
712 const CXXRecordDecl *ClassDecl,
713 const CXXRecordDecl *BaseClassDecl) {
714 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
715 CharUnits VBaseOffsetOffset =
716 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
717
718 llvm::Value *VBaseOffsetPtr =
719 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
720 "vbase.offset.ptr");
721 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
722 CGM.PtrDiffTy->getPointerTo());
723
724 llvm::Value *VBaseOffset =
725 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
726
727 return VBaseOffset;
728}
729
John McCall4c40d982010-08-31 07:33:07 +0000730/// The generic ABI passes 'this', plus a VTT if it's initializing a
731/// base subobject.
732void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
733 CXXCtorType Type,
734 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000735 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000736 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000737
Stephen Lind4c0cd02013-06-18 17:00:49 +0000738 // 'this' parameter is already there, as well as 'this' return if
739 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000740
741 // Check if we need to add a VTT parameter (which has type void **).
742 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
743 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
744}
745
John McCall4c40d982010-08-31 07:33:07 +0000746/// The generic ABI passes 'this', plus a VTT if it's destroying a
747/// base subobject.
748void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
749 CXXDtorType Type,
750 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000751 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000752 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000753
Stephen Lind4c0cd02013-06-18 17:00:49 +0000754 // 'this' parameter is already there, as well as 'this' return if
755 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000756
757 // Check if we need to add a VTT parameter (which has type void **).
758 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
759 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
760}
761
John McCall4c40d982010-08-31 07:33:07 +0000762void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
763 QualType &ResTy,
764 FunctionArgList &Params) {
765 /// Create the 'this' variable.
766 BuildThisParam(CGF, Params);
767
768 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
769 assert(MD->isInstance());
770
771 // Check if we need a VTT parameter as well.
772 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000773 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000774
775 // FIXME: avoid the fake decl
776 QualType T = Context.getPointerType(Context.VoidPtrTy);
777 ImplicitParamDecl *VTTDecl
778 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
779 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000780 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000781 getVTTDecl(CGF) = VTTDecl;
782 }
783}
784
John McCall4c40d982010-08-31 07:33:07 +0000785void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
786 /// Initialize the 'this' slot.
787 EmitThisParam(CGF);
788
789 /// Initialize the 'vtt' slot if needed.
790 if (getVTTDecl(CGF)) {
791 getVTTValue(CGF)
792 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
793 "vtt");
794 }
John McCall4c40d982010-08-31 07:33:07 +0000795
Stephen Lind4c0cd02013-06-18 17:00:49 +0000796 /// If this is a function that the ABI specifies returns 'this', initialize
797 /// the return slot to 'this' at the start of the function.
798 ///
799 /// Unlike the setting of return types, this is done within the ABI
800 /// implementation instead of by clients of CGCXXABI because:
801 /// 1) getThisValue is currently protected
802 /// 2) in theory, an ABI could implement 'this' returns some other way;
803 /// HasThisReturn only specifies a contract, not the implementation
John McCall4c40d982010-08-31 07:33:07 +0000804 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000805 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000806}
807
Stephen Lin4444dbb2013-06-19 18:10:35 +0000808void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000809 const CXXConstructorDecl *D,
Stephen Lind4c0cd02013-06-18 17:00:49 +0000810 CXXCtorType Type,
811 bool ForVirtualBase, bool Delegating,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000812 llvm::Value *This,
813 CallExpr::const_arg_iterator ArgBeg,
814 CallExpr::const_arg_iterator ArgEnd) {
815 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
816 Delegating);
817 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
818 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
819
820 // FIXME: Provide a source location here.
Stephen Lin4444dbb2013-06-19 18:10:35 +0000821 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
822 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000823}
824
Stephen Lin4444dbb2013-06-19 18:10:35 +0000825void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
826 const CXXDestructorDecl *Dtor,
827 CXXDtorType DtorType,
828 SourceLocation CallLoc,
829 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000830 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
831
832 const CGFunctionInfo *FInfo
833 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
834 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
835 llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, DtorType, This, Ty);
836
Stephen Lin4444dbb2013-06-19 18:10:35 +0000837 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
838 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000839}
840
Reid Kleckner90633022013-06-19 15:20:38 +0000841void ItaniumCXXABI::EmitVirtualInheritanceTables(
842 llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) {
843 CodeGenVTables &VTables = CGM.getVTables();
844 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
845 VTables.EmitVTTDefinition(VTT, Linkage, RD);
846}
847
John McCall4c40d982010-08-31 07:33:07 +0000848void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
849 RValue RV, QualType ResultType) {
850 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
851 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
852
853 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000854 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000855 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
856 RValue Undef = RValue::get(llvm::UndefValue::get(T));
857 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
858}
John McCall1e7fe752010-09-02 09:58:18 +0000859
860/************************** Array allocation cookies **************************/
861
John McCalle2b45e22012-05-01 05:23:51 +0000862CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
863 // The array cookie is a size_t; pad that up to the element alignment.
864 // The cookie is actually right-justified in that space.
865 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
866 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000867}
868
869llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
870 llvm::Value *NewPtr,
871 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000872 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000873 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000874 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000875
Micah Villmow956a5a12012-10-25 15:39:14 +0000876 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000877
John McCall9cb2cee2010-09-02 10:25:57 +0000878 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000879 QualType SizeTy = Ctx.getSizeType();
880 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
881
882 // The size of the cookie.
883 CharUnits CookieSize =
884 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000885 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000886
887 // Compute an offset to the cookie.
888 llvm::Value *CookiePtr = NewPtr;
889 CharUnits CookieOffset = CookieSize - SizeSize;
890 if (!CookieOffset.isZero())
891 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
892 CookieOffset.getQuantity());
893
894 // Write the number of elements into the appropriate slot.
895 llvm::Value *NumElementsPtr
896 = CGF.Builder.CreateBitCast(CookiePtr,
897 CGF.ConvertType(SizeTy)->getPointerTo(AS));
898 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
899
900 // Finally, compute a pointer to the actual data buffer by skipping
901 // over the cookie completely.
902 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
903 CookieSize.getQuantity());
904}
905
John McCalle2b45e22012-05-01 05:23:51 +0000906llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
907 llvm::Value *allocPtr,
908 CharUnits cookieSize) {
909 // The element size is right-justified in the cookie.
910 llvm::Value *numElementsPtr = allocPtr;
911 CharUnits numElementsOffset =
912 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
913 if (!numElementsOffset.isZero())
914 numElementsPtr =
915 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
916 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000917
Micah Villmow956a5a12012-10-25 15:39:14 +0000918 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000919 numElementsPtr =
920 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
921 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000922}
923
John McCalle2b45e22012-05-01 05:23:51 +0000924CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +0000925 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +0000926 // struct array_cookie {
927 // std::size_t element_size; // element_size != 0
928 // std::size_t element_count;
929 // };
John McCallf3bbb152013-01-25 23:36:19 +0000930 // But the base ABI doesn't give anything an alignment greater than
931 // 8, so we can dismiss this as typical ABI-author blindness to
932 // actual language complexity and round up to the element alignment.
933 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
934 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000935}
936
937llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +0000938 llvm::Value *newPtr,
939 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +0000940 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +0000941 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000942 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000943
John McCallf3bbb152013-01-25 23:36:19 +0000944 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
945 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000946
947 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +0000948 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +0000949
950 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +0000951 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
952 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
953 getContext().getTypeSizeInChars(elementType).getQuantity());
954 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000955
956 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +0000957 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
958 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000959
960 // Finally, compute a pointer to the actual data buffer by skipping
961 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +0000962 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
963 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
964 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000965}
966
John McCalle2b45e22012-05-01 05:23:51 +0000967llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
968 llvm::Value *allocPtr,
969 CharUnits cookieSize) {
970 // The number of elements is at offset sizeof(size_t) relative to
971 // the allocated pointer.
972 llvm::Value *numElementsPtr
973 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000974
Micah Villmow956a5a12012-10-25 15:39:14 +0000975 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000976 numElementsPtr =
977 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
978 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000979}
980
John McCall5cd91b52010-09-08 01:44:27 +0000981/*********************** Static local initialization **************************/
982
983static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000984 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000985 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000986 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +0000987 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +0000988 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000989 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +0000990 llvm::AttributeSet::get(CGM.getLLVMContext(),
991 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +0000992 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000993}
994
995static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000996 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000997 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000998 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000999 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001000 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001001 llvm::AttributeSet::get(CGM.getLLVMContext(),
1002 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001003 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001004}
1005
1006static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001007 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001008 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001009 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001010 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001011 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001012 llvm::AttributeSet::get(CGM.getLLVMContext(),
1013 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001014 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001015}
1016
1017namespace {
1018 struct CallGuardAbort : EHScopeStack::Cleanup {
1019 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001020 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001021
John McCallad346f42011-07-12 20:27:29 +00001022 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbd7370a2013-02-28 19:01:20 +00001023 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1024 Guard);
John McCall5cd91b52010-09-08 01:44:27 +00001025 }
1026 };
1027}
1028
1029/// The ARM code here follows the Itanium code closely enough that we
1030/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001031void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1032 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001033 llvm::GlobalVariable *var,
1034 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001035 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001036
Richard Smith04e51762013-04-14 23:01:42 +00001037 // We only need to use thread-safe statics for local non-TLS variables;
John McCall3030eb82010-11-06 09:44:32 +00001038 // global initialization is always single-threaded.
Richard Smith04e51762013-04-14 23:01:42 +00001039 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1040 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlsson173d5122011-04-27 04:37:08 +00001041
Anders Carlsson173d5122011-04-27 04:37:08 +00001042 // If we have a global variable with internal linkage and thread-safe statics
1043 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001044 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1045
1046 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001047 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001048 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001049 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001050 // Guard variables are 64 bits in the generic ABI and size width on ARM
1051 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1052 guardTy = (IsARM ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001053 }
John McCall355bba72012-03-30 21:00:39 +00001054 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001055
John McCall355bba72012-03-30 21:00:39 +00001056 // Create the guard variable if we don't already have it (as we
1057 // might if we're double-emitting this function body).
1058 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1059 if (!guard) {
1060 // Mangle the name for the guard.
1061 SmallString<256> guardName;
1062 {
1063 llvm::raw_svector_ostream out(guardName);
1064 getMangleContext().mangleItaniumGuardVariable(&D, out);
1065 out.flush();
1066 }
John McCall112c9672010-11-02 21:04:24 +00001067
John McCall355bba72012-03-30 21:00:39 +00001068 // Create the guard variable with a zero-initializer.
1069 // Just absorb linkage and visibility from the guarded variable.
1070 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1071 false, var->getLinkage(),
1072 llvm::ConstantInt::get(guardTy, 0),
1073 guardName.str());
1074 guard->setVisibility(var->getVisibility());
Richard Smith04e51762013-04-14 23:01:42 +00001075 // If the variable is thread-local, so is its guard variable.
1076 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall355bba72012-03-30 21:00:39 +00001077
1078 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1079 }
John McCall49d26d22012-03-30 07:09:50 +00001080
John McCall5cd91b52010-09-08 01:44:27 +00001081 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001082 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001083
1084 // ARM C++ ABI 3.2.3.1:
1085 // To support the potential use of initialization guard variables
1086 // as semaphores that are the target of ARM SWP and LDREX/STREX
1087 // synchronizing instructions we define a static initialization
1088 // guard variable to be a 4-byte aligned, 4- byte word with the
1089 // following inline access protocol.
1090 // #define INITIALIZED 1
1091 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1092 // if (__cxa_guard_acquire(&obj_guard))
1093 // ...
1094 // }
John McCall0502a222011-06-17 07:33:57 +00001095 if (IsARM && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001096 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001097 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1098 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001099 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001100
1101 // Itanium C++ ABI 3.3.2:
1102 // The following is pseudo-code showing how these functions can be used:
1103 // if (obj_guard.first_byte == 0) {
1104 // if ( __cxa_guard_acquire (&obj_guard) ) {
1105 // try {
1106 // ... initialize the object ...;
1107 // } catch (...) {
1108 // __cxa_guard_abort (&obj_guard);
1109 // throw;
1110 // }
1111 // ... queue object destructor with __cxa_atexit() ...;
1112 // __cxa_guard_release (&obj_guard);
1113 // }
1114 // }
1115 } else {
1116 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001117 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001118 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001119 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001120
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001121 // Itanium ABI:
1122 // An implementation supporting thread-safety on multiprocessor
1123 // systems must also guarantee that references to the initialized
1124 // object do not occur before the load of the initialization flag.
1125 //
1126 // In LLVM, we do this by marking the load Acquire.
1127 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001128 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001129
John McCall355bba72012-03-30 21:00:39 +00001130 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001131 }
1132
1133 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1134 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1135
1136 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001137 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001138
1139 CGF.EmitBlock(InitCheckBlock);
1140
1141 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001142 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001143 // Call __cxa_guard_acquire.
1144 llvm::Value *V
John McCallbd7370a2013-02-28 19:01:20 +00001145 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001146
1147 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1148
1149 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1150 InitBlock, EndBlock);
1151
1152 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001153 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001154
1155 CGF.EmitBlock(InitBlock);
1156 }
1157
1158 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001159 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001160
John McCall0502a222011-06-17 07:33:57 +00001161 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001162 // Pop the guard-abort cleanup if we pushed one.
1163 CGF.PopCleanupBlock();
1164
1165 // Call __cxa_guard_release. This cannot throw.
John McCallbd7370a2013-02-28 19:01:20 +00001166 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001167 } else {
John McCall355bba72012-03-30 21:00:39 +00001168 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001169 }
1170
1171 CGF.EmitBlock(EndBlock);
1172}
John McCall20bb1752012-05-01 06:13:13 +00001173
1174/// Register a global destructor using __cxa_atexit.
1175static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1176 llvm::Constant *dtor,
Richard Smith04e51762013-04-14 23:01:42 +00001177 llvm::Constant *addr,
1178 bool TLS) {
Bill Wendling4e3b54b2013-05-02 19:18:03 +00001179 const char *Name = "__cxa_atexit";
1180 if (TLS) {
1181 const llvm::Triple &T = CGF.getTarget().getTriple();
1182 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1183 }
Richard Smith04e51762013-04-14 23:01:42 +00001184
John McCall20bb1752012-05-01 06:13:13 +00001185 // We're assuming that the destructor function is something we can
1186 // reasonably call with the default CC. Go ahead and cast it to the
1187 // right prototype.
1188 llvm::Type *dtorTy =
1189 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1190
1191 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1192 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1193 llvm::FunctionType *atexitTy =
1194 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1195
1196 // Fetch the actual function.
Richard Smith04e51762013-04-14 23:01:42 +00001197 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCall20bb1752012-05-01 06:13:13 +00001198 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1199 fn->setDoesNotThrow();
1200
1201 // Create a variable that binds the atexit to this shared object.
1202 llvm::Constant *handle =
1203 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1204
1205 llvm::Value *args[] = {
1206 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1207 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1208 handle
1209 };
John McCallbd7370a2013-02-28 19:01:20 +00001210 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCall20bb1752012-05-01 06:13:13 +00001211}
1212
1213/// Register a global destructor as best as we know how.
1214void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smith04e51762013-04-14 23:01:42 +00001215 const VarDecl &D,
John McCall20bb1752012-05-01 06:13:13 +00001216 llvm::Constant *dtor,
1217 llvm::Constant *addr) {
1218 // Use __cxa_atexit if available.
Richard Smith04e51762013-04-14 23:01:42 +00001219 if (CGM.getCodeGenOpts().CXAAtExit)
1220 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1221
1222 if (D.getTLSKind())
1223 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCall20bb1752012-05-01 06:13:13 +00001224
1225 // In Apple kexts, we want to add a global destructor entry.
1226 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001227 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001228 // Generate a global destructor entry.
1229 return CGM.AddCXXDtorEntry(dtor, addr);
1230 }
1231
1232 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1233}
Richard Smithb80a16e2013-04-19 16:42:07 +00001234
1235/// Get the appropriate linkage for the wrapper function. This is essentially
1236/// the weak form of the variable's linkage; every translation unit which wneeds
1237/// the wrapper emits a copy, and we want the linker to merge them.
1238static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1239 llvm::GlobalValue::LinkageTypes VarLinkage) {
1240 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1241 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1242 // For internal linkage variables, we don't need an external or weak wrapper.
1243 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1244 return VarLinkage;
1245 return llvm::GlobalValue::WeakODRLinkage;
1246}
1247
1248llvm::Function *
1249ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1250 llvm::GlobalVariable *Var) {
1251 // Mangle the name for the thread_local wrapper function.
1252 SmallString<256> WrapperName;
1253 {
1254 llvm::raw_svector_ostream Out(WrapperName);
1255 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1256 Out.flush();
1257 }
1258
1259 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1260 return cast<llvm::Function>(V);
1261
1262 llvm::Type *RetTy = Var->getType();
1263 if (VD->getType()->isReferenceType())
1264 RetTy = RetTy->getPointerElementType();
1265
1266 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1267 llvm::Function *Wrapper = llvm::Function::Create(
1268 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1269 &CGM.getModule());
1270 // Always resolve references to the wrapper at link time.
1271 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1272 return Wrapper;
1273}
1274
1275void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1276 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1277 llvm::Function *InitFunc) {
1278 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1279 const VarDecl *VD = Decls[I].first;
1280 llvm::GlobalVariable *Var = Decls[I].second;
1281
1282 // Mangle the name for the thread_local initialization function.
1283 SmallString<256> InitFnName;
1284 {
1285 llvm::raw_svector_ostream Out(InitFnName);
1286 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1287 Out.flush();
1288 }
1289
1290 // If we have a definition for the variable, emit the initialization
1291 // function as an alias to the global Init function (if any). Otherwise,
1292 // produce a declaration of the initialization function.
1293 llvm::GlobalValue *Init = 0;
1294 bool InitIsInitFunc = false;
1295 if (VD->hasDefinition()) {
1296 InitIsInitFunc = true;
1297 if (InitFunc)
1298 Init =
1299 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1300 InitFnName.str(), InitFunc, &CGM.getModule());
1301 } else {
1302 // Emit a weak global function referring to the initialization function.
1303 // This function will not exist if the TU defining the thread_local
1304 // variable in question does not need any dynamic initialization for
1305 // its thread_local variables.
1306 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1307 Init = llvm::Function::Create(
1308 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1309 &CGM.getModule());
1310 }
1311
1312 if (Init)
1313 Init->setVisibility(Var->getVisibility());
1314
1315 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1316 llvm::LLVMContext &Context = CGM.getModule().getContext();
1317 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1318 CGBuilderTy Builder(Entry);
1319 if (InitIsInitFunc) {
1320 if (Init)
1321 Builder.CreateCall(Init);
1322 } else {
1323 // Don't know whether we have an init function. Call it if it exists.
1324 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1325 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1326 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1327 Builder.CreateCondBr(Have, InitBB, ExitBB);
1328
1329 Builder.SetInsertPoint(InitBB);
1330 Builder.CreateCall(Init);
1331 Builder.CreateBr(ExitBB);
1332
1333 Builder.SetInsertPoint(ExitBB);
1334 }
1335
1336 // For a reference, the result of the wrapper function is a pointer to
1337 // the referenced object.
1338 llvm::Value *Val = Var;
1339 if (VD->getType()->isReferenceType()) {
1340 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1341 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1342 Val = LI;
1343 }
1344
1345 Builder.CreateRet(Val);
1346 }
1347}
1348
1349LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1350 const DeclRefExpr *DRE) {
1351 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1352 QualType T = VD->getType();
1353 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1354 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1355 llvm::Function *Wrapper =
1356 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1357
1358 Val = CGF.Builder.CreateCall(Wrapper);
1359
1360 LValue LV;
1361 if (VD->getType()->isReferenceType())
1362 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1363 else
1364 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1365 CGF.getContext().getDeclAlign(VD));
1366 // FIXME: need setObjCGCLValueClass?
1367 return LV;
1368}