blob: f3ac03dbce0b0dfacc73be1546af476196db8a02 [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:
Mark Seaborn21fe4502013-07-24 16:25:13 +000038 bool UseARMMethodPtrABI;
39 bool UseARMGuardVarABI;
John McCall0bab0cd2010-08-23 01:21:21 +000040
Charles Davis3a811f12010-05-25 19:52:27 +000041public:
Mark Seaborn21fe4502013-07-24 16:25:13 +000042 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
43 bool UseARMMethodPtrABI = false,
44 bool UseARMGuardVarABI = false) :
45 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
46 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall93d557b2010-08-22 00:05:51 +000047
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000048 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
49 // Structures with either a non-trivial destructor or a non-trivial
50 // copy constructor are always indirect.
51 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
52 }
53
54 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
55 // Structures with either a non-trivial destructor or a non-trivial
56 // copy constructor are always indirect.
57 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
58 return RAA_Indirect;
59 return RAA_Default;
60 }
61
John McCallf16aa102010-08-22 21:01:12 +000062 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000063
Chris Lattner9cbe4f02011-07-09 17:41:47 +000064 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000065
John McCall93d557b2010-08-22 00:05:51 +000066 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
67 llvm::Value *&This,
68 llvm::Value *MemFnPtr,
69 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000070
John McCall6c2ab1d2010-08-31 21:07:20 +000071 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
72 llvm::Value *Base,
73 llvm::Value *MemPtr,
74 const MemberPointerType *MPT);
75
John McCall0bab0cd2010-08-23 01:21:21 +000076 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
77 const CastExpr *E,
78 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000079 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
80 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000081
John McCall0bab0cd2010-08-23 01:21:21 +000082 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000083
John McCall755d8492011-04-12 00:42:48 +000084 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000085 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
86 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000087 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
88 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
89 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000090
John McCall0bab0cd2010-08-23 01:21:21 +000091 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
92 llvm::Value *L,
93 llvm::Value *R,
94 const MemberPointerType *MPT,
95 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000096
John McCall0bab0cd2010-08-23 01:21:21 +000097 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
98 llvm::Value *Addr,
99 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +0000100
John McCallecd03b42012-09-25 10:10:39 +0000101 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
102 llvm::Value *ptr,
103 QualType type);
104
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000105 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
106 llvm::Value *This,
107 const CXXRecordDecl *ClassDecl,
108 const CXXRecordDecl *BaseClassDecl);
109
John McCall4c40d982010-08-31 07:33:07 +0000110 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
111 CXXCtorType T,
112 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000113 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000114
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000115 void EmitCXXConstructors(const CXXConstructorDecl *D);
116
John McCall4c40d982010-08-31 07:33:07 +0000117 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
118 CXXDtorType T,
119 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000121
Reid Klecknera4130ba2013-07-22 13:51:44 +0000122 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
123 CXXDtorType DT) const {
124 // Itanium does not emit any destructor variant as an inline thunk.
125 // Delegating may occur as an optimization, but all variants are either
126 // emitted with external linkage or as linkonce if they are inline and used.
127 return false;
128 }
129
130 void EmitCXXDestructors(const CXXDestructorDecl *D);
131
John McCall4c40d982010-08-31 07:33:07 +0000132 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
133 QualType &ResTy,
134 FunctionArgList &Params);
135
136 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000137
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000138 void EmitConstructorCall(CodeGenFunction &CGF,
139 const CXXConstructorDecl *D, CXXCtorType Type,
140 bool ForVirtualBase, bool Delegating,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000141 llvm::Value *This,
142 CallExpr::const_arg_iterator ArgBeg,
143 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000144
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000145 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
146 const CXXDestructorDecl *Dtor,
147 CXXDtorType DtorType, SourceLocation CallLoc,
148 llvm::Value *This);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000149
Reid Kleckner90633022013-06-19 15:20:38 +0000150 void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage,
151 const CXXRecordDecl *RD);
152
Joao Matos285baac2012-07-17 17:10:11 +0000153 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000154 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000155
John McCalle2b45e22012-05-01 05:23:51 +0000156 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000157 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
158 llvm::Value *NewPtr,
159 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000160 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000161 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000162 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
163 llvm::Value *allocPtr,
164 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000165
John McCall3030eb82010-11-06 09:44:32 +0000166 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000167 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smith04e51762013-04-14 23:01:42 +0000168 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
169 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smithb80a16e2013-04-19 16:42:07 +0000170
171 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
172 llvm::GlobalVariable *Var);
173 void EmitThreadLocalInitFuncs(
174 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
175 llvm::Function *InitFunc);
176 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
177 const DeclRefExpr *DRE);
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000178
179 bool NeedsVTTParameter(GlobalDecl GD);
Charles Davis3a811f12010-05-25 19:52:27 +0000180};
John McCallee79a4c2010-08-21 22:46:04 +0000181
182class ARMCXXABI : public ItaniumCXXABI {
183public:
Mark Seaborn21fe4502013-07-24 16:25:13 +0000184 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
185 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
186 /* UseARMGuardVarABI = */ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000187
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000188 bool HasThisReturn(GlobalDecl GD) const {
189 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
190 isa<CXXDestructorDecl>(GD.getDecl()) &&
191 GD.getDtorType() != Dtor_Deleting));
192 }
John McCall4c40d982010-08-31 07:33:07 +0000193
194 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
195
John McCalle2b45e22012-05-01 05:23:51 +0000196 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000197 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
198 llvm::Value *NewPtr,
199 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000200 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000201 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000202 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
203 CharUnits cookieSize);
John McCallee79a4c2010-08-21 22:46:04 +0000204};
Charles Davis3a811f12010-05-25 19:52:27 +0000205}
206
Charles Davis071cc7d2010-08-16 03:33:14 +0000207CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +0000208 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall96fcde02013-01-25 23:36:14 +0000209 // For IR-generation purposes, there's no significant difference
210 // between the ARM and iOS ABIs.
211 case TargetCXXABI::GenericARM:
212 case TargetCXXABI::iOS:
213 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000214
Tim Northoverc264e162013-01-31 12:13:10 +0000215 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
216 // include the other 32-bit ARM oddities: constructor/destructor return values
217 // and array cookies.
218 case TargetCXXABI::GenericAArch64:
Mark Seaborn21fe4502013-07-24 16:25:13 +0000219 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
220 /* UseARMGuardVarABI = */ true);
Tim Northoverc264e162013-01-31 12:13:10 +0000221
John McCall96fcde02013-01-25 23:36:14 +0000222 case TargetCXXABI::GenericItanium:
Mark Seaborn21fe4502013-07-24 16:25:13 +0000223 if (CGM.getContext().getTargetInfo().getTriple().getArch()
224 == llvm::Triple::le32) {
225 // For PNaCl, use ARM-style method pointers so that PNaCl code
226 // does not assume anything about the alignment of function
227 // pointers.
228 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
229 /* UseARMGuardVarABI = */ false);
230 }
John McCall96fcde02013-01-25 23:36:14 +0000231 return new ItaniumCXXABI(CGM);
232
233 case TargetCXXABI::Microsoft:
234 llvm_unreachable("Microsoft ABI is not Itanium-based");
235 }
236 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000237}
238
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000239llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000240ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
241 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000242 return CGM.PtrDiffTy;
243 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall875ab102010-08-22 06:43:33 +0000244}
245
John McCallbabc9a92010-08-22 00:59:17 +0000246/// In the Itanium and ARM ABIs, method pointers have the form:
247/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
248///
249/// In the Itanium ABI:
250/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
251/// - the this-adjustment is (memptr.adj)
252/// - the virtual offset is (memptr.ptr - 1)
253///
254/// In the ARM ABI:
255/// - method pointers are virtual if (memptr.adj & 1) is nonzero
256/// - the this-adjustment is (memptr.adj >> 1)
257/// - the virtual offset is (memptr.ptr)
258/// ARM uses 'adj' for the virtual flag because Thumb functions
259/// may be only single-byte aligned.
260///
261/// If the member is virtual, the adjusted 'this' pointer points
262/// to a vtable pointer from which the virtual offset is applied.
263///
264/// If the member is non-virtual, memptr.ptr is the address of
265/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000266llvm::Value *
267ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
268 llvm::Value *&This,
269 llvm::Value *MemFnPtr,
270 const MemberPointerType *MPT) {
271 CGBuilderTy &Builder = CGF.Builder;
272
273 const FunctionProtoType *FPT =
274 MPT->getPointeeType()->getAs<FunctionProtoType>();
275 const CXXRecordDecl *RD =
276 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
277
Chris Lattner2acc6e32011-07-18 04:24:23 +0000278 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000279 CGM.getTypes().GetFunctionType(
280 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000281
Reid Kleckner92e44d92013-03-22 16:13:10 +0000282 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall93d557b2010-08-22 00:05:51 +0000283
John McCallbabc9a92010-08-22 00:59:17 +0000284 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
285 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
286 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
287
John McCalld608cdb2010-08-22 10:59:02 +0000288 // Extract memptr.adj, which is in the second field.
289 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000290
291 // Compute the true adjustment.
292 llvm::Value *Adj = RawAdj;
Mark Seaborn21fe4502013-07-24 16:25:13 +0000293 if (UseARMMethodPtrABI)
John McCallbabc9a92010-08-22 00:59:17 +0000294 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000295
296 // Apply the adjustment and cast back to the original struct type
297 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000298 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
299 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
300 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000301
302 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000303 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000304
305 // If the LSB in the function pointer is 1, the function pointer points to
306 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000307 llvm::Value *IsVirtual;
Mark Seaborn21fe4502013-07-24 16:25:13 +0000308 if (UseARMMethodPtrABI)
John McCallbabc9a92010-08-22 00:59:17 +0000309 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
310 else
311 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
312 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000313 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
314
315 // In the virtual path, the adjustment left 'This' pointing to the
316 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000317 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000318 CGF.EmitBlock(FnVirtual);
319
320 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000321 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000322 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000323 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000324
325 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000326 llvm::Value *VTableOffset = FnAsInt;
Mark Seaborn21fe4502013-07-24 16:25:13 +0000327 if (!UseARMMethodPtrABI)
328 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCallbabc9a92010-08-22 00:59:17 +0000329 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000330
331 // Load the virtual function to call.
332 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000333 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000334 CGF.EmitBranch(FnEnd);
335
336 // In the non-virtual path, the function pointer is actually a
337 // function pointer.
338 CGF.EmitBlock(FnNonVirtual);
339 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000340 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000341
342 // We're done.
343 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000344 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000345 Callee->addIncoming(VirtualFn, FnVirtual);
346 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
347 return Callee;
348}
John McCall3023def2010-08-22 03:04:22 +0000349
John McCall6c2ab1d2010-08-31 21:07:20 +0000350/// Compute an l-value by applying the given pointer-to-member to a
351/// base object.
352llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
353 llvm::Value *Base,
354 llvm::Value *MemPtr,
355 const MemberPointerType *MPT) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000356 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall6c2ab1d2010-08-31 21:07:20 +0000357
358 CGBuilderTy &Builder = CGF.Builder;
359
Micah Villmow956a5a12012-10-25 15:39:14 +0000360 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000361
362 // Cast to char*.
363 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
364
365 // Apply the offset, which we assume is non-null.
366 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
367
368 // Cast the address to the appropriate pointer type, adopting the
369 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000370 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000371 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000372 return Builder.CreateBitCast(Addr, PType);
373}
374
John McCall4d4e5c12012-02-15 01:22:51 +0000375/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
376/// conversion.
377///
378/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000379///
380/// Obligatory offset/adjustment diagram:
381/// <-- offset --> <-- adjustment -->
382/// |--------------------------|----------------------|--------------------|
383/// ^Derived address point ^Base address point ^Member address point
384///
385/// So when converting a base member pointer to a derived member pointer,
386/// we add the offset to the adjustment because the address point has
387/// decreased; and conversely, when converting a derived MP to a base MP
388/// we subtract the offset from the adjustment because the address point
389/// has increased.
390///
391/// The standard forbids (at compile time) conversion to and from
392/// virtual bases, which is why we don't have to consider them here.
393///
394/// The standard forbids (at run time) casting a derived MP to a base
395/// MP when the derived MP does not point to a member of the base.
396/// This is why -1 is a reasonable choice for null data member
397/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000398llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000399ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
400 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000401 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000402 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000403 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
404 E->getCastKind() == CK_ReinterpretMemberPointer);
405
406 // Under Itanium, reinterprets don't require any additional processing.
407 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
408
409 // Use constant emission if we can.
410 if (isa<llvm::Constant>(src))
411 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
412
413 llvm::Constant *adj = getMemberPointerAdjustment(E);
414 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000415
416 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000417 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000418
John McCall4d4e5c12012-02-15 01:22:51 +0000419 const MemberPointerType *destTy =
420 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000421
John McCall0bab0cd2010-08-23 01:21:21 +0000422 // For member data pointers, this is just a matter of adding the
423 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000424 if (destTy->isMemberDataPointer()) {
425 llvm::Value *dst;
426 if (isDerivedToBase)
427 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000428 else
John McCall4d4e5c12012-02-15 01:22:51 +0000429 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000430
431 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000432 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
433 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
434 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000435 }
436
John McCalld608cdb2010-08-22 10:59:02 +0000437 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000438 if (UseARMMethodPtrABI) {
John McCall4d4e5c12012-02-15 01:22:51 +0000439 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
440 offset <<= 1;
441 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000442 }
443
John McCall4d4e5c12012-02-15 01:22:51 +0000444 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
445 llvm::Value *dstAdj;
446 if (isDerivedToBase)
447 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000448 else
John McCall4d4e5c12012-02-15 01:22:51 +0000449 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000450
John McCall4d4e5c12012-02-15 01:22:51 +0000451 return Builder.CreateInsertValue(src, dstAdj, 1);
452}
453
454llvm::Constant *
455ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
456 llvm::Constant *src) {
457 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
458 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
459 E->getCastKind() == CK_ReinterpretMemberPointer);
460
461 // Under Itanium, reinterprets don't require any additional processing.
462 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
463
464 // If the adjustment is trivial, we don't need to do anything.
465 llvm::Constant *adj = getMemberPointerAdjustment(E);
466 if (!adj) return src;
467
468 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
469
470 const MemberPointerType *destTy =
471 E->getType()->castAs<MemberPointerType>();
472
473 // For member data pointers, this is just a matter of adding the
474 // offset if the source is non-null.
475 if (destTy->isMemberDataPointer()) {
476 // null maps to null.
477 if (src->isAllOnesValue()) return src;
478
479 if (isDerivedToBase)
480 return llvm::ConstantExpr::getNSWSub(src, adj);
481 else
482 return llvm::ConstantExpr::getNSWAdd(src, adj);
483 }
484
485 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000486 if (UseARMMethodPtrABI) {
John McCall4d4e5c12012-02-15 01:22:51 +0000487 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
488 offset <<= 1;
489 adj = llvm::ConstantInt::get(adj->getType(), offset);
490 }
491
492 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
493 llvm::Constant *dstAdj;
494 if (isDerivedToBase)
495 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
496 else
497 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
498
499 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000500}
John McCallcf2c85e2010-08-22 04:16:24 +0000501
502llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000503ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall0bab0cd2010-08-23 01:21:21 +0000504 // Itanium C++ ABI 2.3:
505 // A NULL pointer is represented as -1.
506 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000507 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000508
Reid Kleckner92e44d92013-03-22 16:13:10 +0000509 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalld608cdb2010-08-22 10:59:02 +0000510 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000511 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000512}
513
John McCall5808ce42011-02-03 08:15:49 +0000514llvm::Constant *
515ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
516 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000517 // Itanium C++ ABI 2.3:
518 // A pointer to data member is an offset from the base address of
519 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner92e44d92013-03-22 16:13:10 +0000520 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000521}
522
John McCall755d8492011-04-12 00:42:48 +0000523llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000524 return BuildMemberPointer(MD, CharUnits::Zero());
525}
526
527llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
528 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000529 assert(MD->isInstance() && "Member function must not be static!");
530 MD = MD->getCanonicalDecl();
531
532 CodeGenTypes &Types = CGM.getTypes();
John McCalld608cdb2010-08-22 10:59:02 +0000533
534 // Get the function pointer (or index if this is a virtual function).
535 llvm::Constant *MemPtr[2];
536 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000537 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000538
Ken Dyck1246ba62011-04-09 01:30:02 +0000539 const ASTContext &Context = getContext();
540 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000541 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000542 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000543
Mark Seaborn21fe4502013-07-24 16:25:13 +0000544 if (UseARMMethodPtrABI) {
John McCalld608cdb2010-08-22 10:59:02 +0000545 // ARM C++ ABI 3.2.1:
546 // This ABI specifies that adj contains twice the this
547 // adjustment, plus 1 if the member function is virtual. The
548 // least significant bit of adj then makes exactly the same
549 // discrimination as the least significant bit of ptr does for
550 // Itanium.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000551 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
552 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000553 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000554 } else {
555 // Itanium C++ ABI 2.3:
556 // For a virtual function, [the pointer field] is 1 plus the
557 // virtual table offset (in bytes) of the function,
558 // represented as a ptrdiff_t.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000559 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
560 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000561 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000562 }
563 } else {
John McCall755d8492011-04-12 00:42:48 +0000564 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000565 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000566 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000567 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000568 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000569 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000570 } else {
John McCall755d8492011-04-12 00:42:48 +0000571 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
572 // function type is incomplete.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000573 Ty = CGM.PtrDiffTy;
John McCalld608cdb2010-08-22 10:59:02 +0000574 }
John McCall755d8492011-04-12 00:42:48 +0000575 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000576
Reid Kleckner92e44d92013-03-22 16:13:10 +0000577 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seaborn21fe4502013-07-24 16:25:13 +0000578 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
579 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smith2d6a5672012-01-14 04:30:29 +0000580 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000581 }
John McCall875ab102010-08-22 06:43:33 +0000582
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000583 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000584}
585
Richard Smith2d6a5672012-01-14 04:30:29 +0000586llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
587 QualType MPType) {
588 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
589 const ValueDecl *MPD = MP.getMemberPointerDecl();
590 if (!MPD)
591 return EmitNullMemberPointer(MPT);
592
Reid Klecknerf6327302013-05-09 21:01:17 +0000593 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smith2d6a5672012-01-14 04:30:29 +0000594
595 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
596 return BuildMemberPointer(MD, ThisAdjustment);
597
598 CharUnits FieldOffset =
599 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
600 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
601}
602
John McCalle9fd7eb2010-08-22 08:30:07 +0000603/// The comparison algorithm is pretty easy: the member pointers are
604/// the same if they're either bitwise identical *or* both null.
605///
606/// ARM is different here only because null-ness is more complicated.
607llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000608ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
609 llvm::Value *L,
610 llvm::Value *R,
611 const MemberPointerType *MPT,
612 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000613 CGBuilderTy &Builder = CGF.Builder;
614
John McCalle9fd7eb2010-08-22 08:30:07 +0000615 llvm::ICmpInst::Predicate Eq;
616 llvm::Instruction::BinaryOps And, Or;
617 if (Inequality) {
618 Eq = llvm::ICmpInst::ICMP_NE;
619 And = llvm::Instruction::Or;
620 Or = llvm::Instruction::And;
621 } else {
622 Eq = llvm::ICmpInst::ICMP_EQ;
623 And = llvm::Instruction::And;
624 Or = llvm::Instruction::Or;
625 }
626
John McCall0bab0cd2010-08-23 01:21:21 +0000627 // Member data pointers are easy because there's a unique null
628 // value, so it just comes down to bitwise equality.
629 if (MPT->isMemberDataPointer())
630 return Builder.CreateICmp(Eq, L, R);
631
632 // For member function pointers, the tautologies are more complex.
633 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000634 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000635 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000636 // (L == R) <==> (L.ptr == R.ptr &&
637 // (L.adj == R.adj ||
638 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000639 // The inequality tautologies have exactly the same structure, except
640 // applying De Morgan's laws.
641
642 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
643 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
644
John McCalle9fd7eb2010-08-22 08:30:07 +0000645 // This condition tests whether L.ptr == R.ptr. This must always be
646 // true for equality to hold.
647 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
648
649 // This condition, together with the assumption that L.ptr == R.ptr,
650 // tests whether the pointers are both null. ARM imposes an extra
651 // condition.
652 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
653 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
654
655 // This condition tests whether L.adj == R.adj. If this isn't
656 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000657 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
658 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000659 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
660
661 // Null member function pointers on ARM clear the low bit of Adj,
662 // so the zero condition has to check that neither low bit is set.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000663 if (UseARMMethodPtrABI) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000664 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
665
666 // Compute (l.adj | r.adj) & 1 and test it against zero.
667 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
668 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
669 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
670 "cmp.or.adj");
671 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
672 }
673
674 // Tie together all our conditions.
675 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
676 Result = Builder.CreateBinOp(And, PtrEq, Result,
677 Inequality ? "memptr.ne" : "memptr.eq");
678 return Result;
679}
680
681llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000682ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
683 llvm::Value *MemPtr,
684 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000685 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000686
687 /// For member data pointers, this is just a check against -1.
688 if (MPT->isMemberDataPointer()) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000689 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall0bab0cd2010-08-23 01:21:21 +0000690 llvm::Value *NegativeOne =
691 llvm::Constant::getAllOnesValue(MemPtr->getType());
692 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
693 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000694
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000695 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000696 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000697
698 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
699 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
700
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000701 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
702 // (the virtual bit) is set.
Mark Seaborn21fe4502013-07-24 16:25:13 +0000703 if (UseARMMethodPtrABI) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000704 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000705 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000706 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000707 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
708 "memptr.isvirtual");
709 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000710 }
711
712 return Result;
713}
John McCall875ab102010-08-22 06:43:33 +0000714
John McCallf16aa102010-08-22 21:01:12 +0000715/// The Itanium ABI requires non-zero initialization only for data
716/// member pointers, for which '0' is a valid offset.
717bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
718 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000719}
John McCall4c40d982010-08-31 07:33:07 +0000720
John McCallecd03b42012-09-25 10:10:39 +0000721/// The Itanium ABI always places an offset to the complete object
722/// at entry -2 in the vtable.
723llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
724 llvm::Value *ptr,
725 QualType type) {
726 // Grab the vtable pointer as an intptr_t*.
727 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
728
729 // Track back to entry -2 and pull out the offset there.
730 llvm::Value *offsetPtr =
731 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
732 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
733 offset->setAlignment(CGF.PointerAlignInBytes);
734
735 // Apply the offset.
736 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
737 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
738}
739
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000740llvm::Value *
741ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
742 llvm::Value *This,
743 const CXXRecordDecl *ClassDecl,
744 const CXXRecordDecl *BaseClassDecl) {
745 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
746 CharUnits VBaseOffsetOffset =
747 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
748
749 llvm::Value *VBaseOffsetPtr =
750 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
751 "vbase.offset.ptr");
752 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
753 CGM.PtrDiffTy->getPointerTo());
754
755 llvm::Value *VBaseOffset =
756 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
757
758 return VBaseOffset;
759}
760
John McCall4c40d982010-08-31 07:33:07 +0000761/// The generic ABI passes 'this', plus a VTT if it's initializing a
762/// base subobject.
763void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
764 CXXCtorType Type,
765 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000766 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000767 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000768
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000769 // 'this' parameter is already there, as well as 'this' return if
770 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000771
772 // Check if we need to add a VTT parameter (which has type void **).
773 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
774 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
775}
776
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000777void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
778 // Just make sure we're in sync with TargetCXXABI.
779 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
780
781 // The constructor used for constructing this as a complete class;
782 // constucts the virtual bases, then calls the base constructor.
783 if (!D->getParent()->isAbstract()) {
784 // We don't need to emit the complete ctor if the class is abstract.
785 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
786 }
787
788 // The constructor used for constructing this as a base class;
789 // ignores virtual bases.
790 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
791}
792
John McCall4c40d982010-08-31 07:33:07 +0000793/// The generic ABI passes 'this', plus a VTT if it's destroying a
794/// base subobject.
795void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
796 CXXDtorType Type,
797 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000798 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000799 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000800
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000801 // 'this' parameter is already there, as well as 'this' return if
802 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000803
804 // Check if we need to add a VTT parameter (which has type void **).
805 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
806 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
807}
808
Reid Klecknera4130ba2013-07-22 13:51:44 +0000809void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
810 // The destructor in a virtual table is always a 'deleting'
811 // destructor, which calls the complete destructor and then uses the
812 // appropriate operator delete.
813 if (D->isVirtual())
814 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
815
816 // The destructor used for destructing this as a most-derived class;
817 // call the base destructor and then destructs any virtual bases.
818 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
819
820 // The destructor used for destructing this as a base class; ignores
821 // virtual bases.
822 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
823}
824
John McCall4c40d982010-08-31 07:33:07 +0000825void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
826 QualType &ResTy,
827 FunctionArgList &Params) {
828 /// Create the 'this' variable.
829 BuildThisParam(CGF, Params);
830
831 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
832 assert(MD->isInstance());
833
834 // Check if we need a VTT parameter as well.
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000835 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000836 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000837
838 // FIXME: avoid the fake decl
839 QualType T = Context.getPointerType(Context.VoidPtrTy);
840 ImplicitParamDecl *VTTDecl
841 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
842 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000843 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000844 getVTTDecl(CGF) = VTTDecl;
845 }
846}
847
John McCall4c40d982010-08-31 07:33:07 +0000848void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
849 /// Initialize the 'this' slot.
850 EmitThisParam(CGF);
851
852 /// Initialize the 'vtt' slot if needed.
853 if (getVTTDecl(CGF)) {
854 getVTTValue(CGF)
855 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
856 "vtt");
857 }
John McCall4c40d982010-08-31 07:33:07 +0000858
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000859 /// If this is a function that the ABI specifies returns 'this', initialize
860 /// the return slot to 'this' at the start of the function.
861 ///
862 /// Unlike the setting of return types, this is done within the ABI
863 /// implementation instead of by clients of CGCXXABI because:
864 /// 1) getThisValue is currently protected
865 /// 2) in theory, an ABI could implement 'this' returns some other way;
866 /// HasThisReturn only specifies a contract, not the implementation
John McCall4c40d982010-08-31 07:33:07 +0000867 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000868 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000869}
870
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000871void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000872 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000873 CXXCtorType Type,
874 bool ForVirtualBase, bool Delegating,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000875 llvm::Value *This,
876 CallExpr::const_arg_iterator ArgBeg,
877 CallExpr::const_arg_iterator ArgEnd) {
878 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
879 Delegating);
880 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
881 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
882
883 // FIXME: Provide a source location here.
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000884 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
885 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000886}
887
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000888void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
889 const CXXDestructorDecl *Dtor,
890 CXXDtorType DtorType,
891 SourceLocation CallLoc,
892 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000893 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
894
895 const CGFunctionInfo *FInfo
896 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
897 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000898 llvm::Value *Callee
899 = CGF.BuildVirtualCall(GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000900
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000901 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
902 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000903}
904
Reid Kleckner90633022013-06-19 15:20:38 +0000905void ItaniumCXXABI::EmitVirtualInheritanceTables(
906 llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) {
907 CodeGenVTables &VTables = CGM.getVTables();
908 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
909 VTables.EmitVTTDefinition(VTT, Linkage, RD);
910}
911
John McCall4c40d982010-08-31 07:33:07 +0000912void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
913 RValue RV, QualType ResultType) {
914 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
915 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
916
917 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000918 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000919 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
920 RValue Undef = RValue::get(llvm::UndefValue::get(T));
921 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
922}
John McCall1e7fe752010-09-02 09:58:18 +0000923
924/************************** Array allocation cookies **************************/
925
John McCalle2b45e22012-05-01 05:23:51 +0000926CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
927 // The array cookie is a size_t; pad that up to the element alignment.
928 // The cookie is actually right-justified in that space.
929 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
930 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000931}
932
933llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
934 llvm::Value *NewPtr,
935 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000936 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000937 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000938 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000939
Micah Villmow956a5a12012-10-25 15:39:14 +0000940 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000941
John McCall9cb2cee2010-09-02 10:25:57 +0000942 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000943 QualType SizeTy = Ctx.getSizeType();
944 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
945
946 // The size of the cookie.
947 CharUnits CookieSize =
948 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000949 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000950
951 // Compute an offset to the cookie.
952 llvm::Value *CookiePtr = NewPtr;
953 CharUnits CookieOffset = CookieSize - SizeSize;
954 if (!CookieOffset.isZero())
955 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
956 CookieOffset.getQuantity());
957
958 // Write the number of elements into the appropriate slot.
959 llvm::Value *NumElementsPtr
960 = CGF.Builder.CreateBitCast(CookiePtr,
961 CGF.ConvertType(SizeTy)->getPointerTo(AS));
962 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
963
964 // Finally, compute a pointer to the actual data buffer by skipping
965 // over the cookie completely.
966 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
967 CookieSize.getQuantity());
968}
969
John McCalle2b45e22012-05-01 05:23:51 +0000970llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
971 llvm::Value *allocPtr,
972 CharUnits cookieSize) {
973 // The element size is right-justified in the cookie.
974 llvm::Value *numElementsPtr = allocPtr;
975 CharUnits numElementsOffset =
976 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
977 if (!numElementsOffset.isZero())
978 numElementsPtr =
979 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
980 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000981
Micah Villmow956a5a12012-10-25 15:39:14 +0000982 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000983 numElementsPtr =
984 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
985 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000986}
987
John McCalle2b45e22012-05-01 05:23:51 +0000988CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +0000989 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +0000990 // struct array_cookie {
991 // std::size_t element_size; // element_size != 0
992 // std::size_t element_count;
993 // };
John McCallf3bbb152013-01-25 23:36:19 +0000994 // But the base ABI doesn't give anything an alignment greater than
995 // 8, so we can dismiss this as typical ABI-author blindness to
996 // actual language complexity and round up to the element alignment.
997 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
998 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000999}
1000
1001llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +00001002 llvm::Value *newPtr,
1003 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +00001004 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +00001005 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +00001006 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +00001007
John McCallf3bbb152013-01-25 23:36:19 +00001008 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1009 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +00001010
1011 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +00001012 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +00001013
1014 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +00001015 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1016 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1017 getContext().getTypeSizeInChars(elementType).getQuantity());
1018 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +00001019
1020 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +00001021 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1022 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +00001023
1024 // Finally, compute a pointer to the actual data buffer by skipping
1025 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +00001026 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1027 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1028 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +00001029}
1030
John McCalle2b45e22012-05-01 05:23:51 +00001031llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1032 llvm::Value *allocPtr,
1033 CharUnits cookieSize) {
1034 // The number of elements is at offset sizeof(size_t) relative to
1035 // the allocated pointer.
1036 llvm::Value *numElementsPtr
1037 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +00001038
Micah Villmow956a5a12012-10-25 15:39:14 +00001039 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +00001040 numElementsPtr =
1041 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1042 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +00001043}
1044
John McCall5cd91b52010-09-08 01:44:27 +00001045/*********************** Static local initialization **************************/
1046
1047static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001048 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001049 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001050 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +00001051 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +00001052 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001053 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001054 llvm::AttributeSet::get(CGM.getLLVMContext(),
1055 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001056 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001057}
1058
1059static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001060 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001061 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001062 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001063 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001064 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001065 llvm::AttributeSet::get(CGM.getLLVMContext(),
1066 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001067 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001068}
1069
1070static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001071 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001072 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001073 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001074 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001075 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001076 llvm::AttributeSet::get(CGM.getLLVMContext(),
1077 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001078 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001079}
1080
1081namespace {
1082 struct CallGuardAbort : EHScopeStack::Cleanup {
1083 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001084 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001085
John McCallad346f42011-07-12 20:27:29 +00001086 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbd7370a2013-02-28 19:01:20 +00001087 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1088 Guard);
John McCall5cd91b52010-09-08 01:44:27 +00001089 }
1090 };
1091}
1092
1093/// The ARM code here follows the Itanium code closely enough that we
1094/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001095void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1096 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001097 llvm::GlobalVariable *var,
1098 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001099 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001100
Richard Smith04e51762013-04-14 23:01:42 +00001101 // We only need to use thread-safe statics for local non-TLS variables;
John McCall3030eb82010-11-06 09:44:32 +00001102 // global initialization is always single-threaded.
Richard Smith04e51762013-04-14 23:01:42 +00001103 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1104 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlsson173d5122011-04-27 04:37:08 +00001105
Anders Carlsson173d5122011-04-27 04:37:08 +00001106 // If we have a global variable with internal linkage and thread-safe statics
1107 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001108 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1109
1110 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001111 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001112 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001113 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001114 // Guard variables are 64 bits in the generic ABI and size width on ARM
1115 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seaborn21fe4502013-07-24 16:25:13 +00001116 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001117 }
John McCall355bba72012-03-30 21:00:39 +00001118 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001119
John McCall355bba72012-03-30 21:00:39 +00001120 // Create the guard variable if we don't already have it (as we
1121 // might if we're double-emitting this function body).
1122 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1123 if (!guard) {
1124 // Mangle the name for the guard.
1125 SmallString<256> guardName;
1126 {
1127 llvm::raw_svector_ostream out(guardName);
1128 getMangleContext().mangleItaniumGuardVariable(&D, out);
1129 out.flush();
1130 }
John McCall112c9672010-11-02 21:04:24 +00001131
John McCall355bba72012-03-30 21:00:39 +00001132 // Create the guard variable with a zero-initializer.
1133 // Just absorb linkage and visibility from the guarded variable.
1134 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1135 false, var->getLinkage(),
1136 llvm::ConstantInt::get(guardTy, 0),
1137 guardName.str());
1138 guard->setVisibility(var->getVisibility());
Richard Smith04e51762013-04-14 23:01:42 +00001139 // If the variable is thread-local, so is its guard variable.
1140 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall355bba72012-03-30 21:00:39 +00001141
1142 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1143 }
John McCall49d26d22012-03-30 07:09:50 +00001144
John McCall5cd91b52010-09-08 01:44:27 +00001145 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001146 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001147
1148 // ARM C++ ABI 3.2.3.1:
1149 // To support the potential use of initialization guard variables
1150 // as semaphores that are the target of ARM SWP and LDREX/STREX
1151 // synchronizing instructions we define a static initialization
1152 // guard variable to be a 4-byte aligned, 4- byte word with the
1153 // following inline access protocol.
1154 // #define INITIALIZED 1
1155 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1156 // if (__cxa_guard_acquire(&obj_guard))
1157 // ...
1158 // }
Mark Seaborn21fe4502013-07-24 16:25:13 +00001159 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001160 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001161 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1162 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001163 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001164
1165 // Itanium C++ ABI 3.3.2:
1166 // The following is pseudo-code showing how these functions can be used:
1167 // if (obj_guard.first_byte == 0) {
1168 // if ( __cxa_guard_acquire (&obj_guard) ) {
1169 // try {
1170 // ... initialize the object ...;
1171 // } catch (...) {
1172 // __cxa_guard_abort (&obj_guard);
1173 // throw;
1174 // }
1175 // ... queue object destructor with __cxa_atexit() ...;
1176 // __cxa_guard_release (&obj_guard);
1177 // }
1178 // }
1179 } else {
1180 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001181 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001182 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001183 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001184
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001185 // Itanium ABI:
1186 // An implementation supporting thread-safety on multiprocessor
1187 // systems must also guarantee that references to the initialized
1188 // object do not occur before the load of the initialization flag.
1189 //
1190 // In LLVM, we do this by marking the load Acquire.
1191 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001192 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001193
John McCall355bba72012-03-30 21:00:39 +00001194 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001195 }
1196
1197 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1198 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1199
1200 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001201 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001202
1203 CGF.EmitBlock(InitCheckBlock);
1204
1205 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001206 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001207 // Call __cxa_guard_acquire.
1208 llvm::Value *V
John McCallbd7370a2013-02-28 19:01:20 +00001209 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001210
1211 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1212
1213 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1214 InitBlock, EndBlock);
1215
1216 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001217 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001218
1219 CGF.EmitBlock(InitBlock);
1220 }
1221
1222 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001223 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001224
John McCall0502a222011-06-17 07:33:57 +00001225 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001226 // Pop the guard-abort cleanup if we pushed one.
1227 CGF.PopCleanupBlock();
1228
1229 // Call __cxa_guard_release. This cannot throw.
John McCallbd7370a2013-02-28 19:01:20 +00001230 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001231 } else {
John McCall355bba72012-03-30 21:00:39 +00001232 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001233 }
1234
1235 CGF.EmitBlock(EndBlock);
1236}
John McCall20bb1752012-05-01 06:13:13 +00001237
1238/// Register a global destructor using __cxa_atexit.
1239static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1240 llvm::Constant *dtor,
Richard Smith04e51762013-04-14 23:01:42 +00001241 llvm::Constant *addr,
1242 bool TLS) {
Bill Wendling4e3b54b2013-05-02 19:18:03 +00001243 const char *Name = "__cxa_atexit";
1244 if (TLS) {
1245 const llvm::Triple &T = CGF.getTarget().getTriple();
1246 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1247 }
Richard Smith04e51762013-04-14 23:01:42 +00001248
John McCall20bb1752012-05-01 06:13:13 +00001249 // We're assuming that the destructor function is something we can
1250 // reasonably call with the default CC. Go ahead and cast it to the
1251 // right prototype.
1252 llvm::Type *dtorTy =
1253 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1254
1255 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1256 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1257 llvm::FunctionType *atexitTy =
1258 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1259
1260 // Fetch the actual function.
Richard Smith04e51762013-04-14 23:01:42 +00001261 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCall20bb1752012-05-01 06:13:13 +00001262 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1263 fn->setDoesNotThrow();
1264
1265 // Create a variable that binds the atexit to this shared object.
1266 llvm::Constant *handle =
1267 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1268
1269 llvm::Value *args[] = {
1270 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1271 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1272 handle
1273 };
John McCallbd7370a2013-02-28 19:01:20 +00001274 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCall20bb1752012-05-01 06:13:13 +00001275}
1276
1277/// Register a global destructor as best as we know how.
1278void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smith04e51762013-04-14 23:01:42 +00001279 const VarDecl &D,
John McCall20bb1752012-05-01 06:13:13 +00001280 llvm::Constant *dtor,
1281 llvm::Constant *addr) {
1282 // Use __cxa_atexit if available.
Richard Smith04e51762013-04-14 23:01:42 +00001283 if (CGM.getCodeGenOpts().CXAAtExit)
1284 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1285
1286 if (D.getTLSKind())
1287 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCall20bb1752012-05-01 06:13:13 +00001288
1289 // In Apple kexts, we want to add a global destructor entry.
1290 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001291 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001292 // Generate a global destructor entry.
1293 return CGM.AddCXXDtorEntry(dtor, addr);
1294 }
1295
1296 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1297}
Richard Smithb80a16e2013-04-19 16:42:07 +00001298
1299/// Get the appropriate linkage for the wrapper function. This is essentially
1300/// the weak form of the variable's linkage; every translation unit which wneeds
1301/// the wrapper emits a copy, and we want the linker to merge them.
1302static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1303 llvm::GlobalValue::LinkageTypes VarLinkage) {
1304 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1305 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1306 // For internal linkage variables, we don't need an external or weak wrapper.
1307 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1308 return VarLinkage;
1309 return llvm::GlobalValue::WeakODRLinkage;
1310}
1311
1312llvm::Function *
1313ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1314 llvm::GlobalVariable *Var) {
1315 // Mangle the name for the thread_local wrapper function.
1316 SmallString<256> WrapperName;
1317 {
1318 llvm::raw_svector_ostream Out(WrapperName);
1319 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1320 Out.flush();
1321 }
1322
1323 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1324 return cast<llvm::Function>(V);
1325
1326 llvm::Type *RetTy = Var->getType();
1327 if (VD->getType()->isReferenceType())
1328 RetTy = RetTy->getPointerElementType();
1329
1330 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1331 llvm::Function *Wrapper = llvm::Function::Create(
1332 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1333 &CGM.getModule());
1334 // Always resolve references to the wrapper at link time.
1335 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1336 return Wrapper;
1337}
1338
1339void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1340 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1341 llvm::Function *InitFunc) {
1342 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1343 const VarDecl *VD = Decls[I].first;
1344 llvm::GlobalVariable *Var = Decls[I].second;
1345
1346 // Mangle the name for the thread_local initialization function.
1347 SmallString<256> InitFnName;
1348 {
1349 llvm::raw_svector_ostream Out(InitFnName);
1350 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1351 Out.flush();
1352 }
1353
1354 // If we have a definition for the variable, emit the initialization
1355 // function as an alias to the global Init function (if any). Otherwise,
1356 // produce a declaration of the initialization function.
1357 llvm::GlobalValue *Init = 0;
1358 bool InitIsInitFunc = false;
1359 if (VD->hasDefinition()) {
1360 InitIsInitFunc = true;
1361 if (InitFunc)
1362 Init =
1363 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1364 InitFnName.str(), InitFunc, &CGM.getModule());
1365 } else {
1366 // Emit a weak global function referring to the initialization function.
1367 // This function will not exist if the TU defining the thread_local
1368 // variable in question does not need any dynamic initialization for
1369 // its thread_local variables.
1370 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1371 Init = llvm::Function::Create(
1372 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1373 &CGM.getModule());
1374 }
1375
1376 if (Init)
1377 Init->setVisibility(Var->getVisibility());
1378
1379 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1380 llvm::LLVMContext &Context = CGM.getModule().getContext();
1381 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1382 CGBuilderTy Builder(Entry);
1383 if (InitIsInitFunc) {
1384 if (Init)
1385 Builder.CreateCall(Init);
1386 } else {
1387 // Don't know whether we have an init function. Call it if it exists.
1388 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1389 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1390 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1391 Builder.CreateCondBr(Have, InitBB, ExitBB);
1392
1393 Builder.SetInsertPoint(InitBB);
1394 Builder.CreateCall(Init);
1395 Builder.CreateBr(ExitBB);
1396
1397 Builder.SetInsertPoint(ExitBB);
1398 }
1399
1400 // For a reference, the result of the wrapper function is a pointer to
1401 // the referenced object.
1402 llvm::Value *Val = Var;
1403 if (VD->getType()->isReferenceType()) {
1404 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1405 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1406 Val = LI;
1407 }
1408
1409 Builder.CreateRet(Val);
1410 }
1411}
1412
1413LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1414 const DeclRefExpr *DRE) {
1415 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1416 QualType T = VD->getType();
1417 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1418 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1419 llvm::Function *Wrapper =
1420 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1421
1422 Val = CGF.Builder.CreateCall(Wrapper);
1423
1424 LValue LV;
1425 if (VD->getType()->isReferenceType())
1426 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1427 else
1428 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1429 CGF.getContext().getDeclAlign(VD));
1430 // FIXME: need setObjCGCLValueClass?
1431 return LV;
1432}
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001433
1434/// Return whether the given global decl needs a VTT parameter, which it does
1435/// if it's a base constructor or destructor with virtual bases.
1436bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1437 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1438
1439 // We don't have any virtual bases, just return early.
1440 if (!MD->getParent()->getNumVBases())
1441 return false;
1442
1443 // Check if we have a base constructor.
1444 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1445 return true;
1446
1447 // Check if we have a base destructor.
1448 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1449 return true;
1450
1451 return false;
1452}