blob: 1648c3bf8528cba6732a3506179005d0e9254d63 [file] [log] [blame]
Charles Davis4e786dd2010-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 Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-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 McCall86353412010-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 Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
John McCall7a9aac22010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000026#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000031
32using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000033using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000034
35namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000036class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000037 /// VTables - All the vtables which have been defined.
38 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
39
John McCall475999d2010-08-22 00:05:51 +000040protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000041 bool UseARMMethodPtrABI;
42 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000043
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000044 ItaniumMangleContext &getMangleContext() {
45 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
46 }
47
Charles Davis4e786dd2010-05-25 19:52:27 +000048public:
Mark Seabornedf0d382013-07-24 16:25:13 +000049 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
50 bool UseARMMethodPtrABI = false,
51 bool UseARMGuardVarABI = false) :
52 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
53 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000054
Craig Topper4f12f102014-03-12 06:41:41 +000055 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const override {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000056 // Structures with either a non-trivial destructor or a non-trivial
57 // copy constructor are always indirect.
58 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
59 }
60
Craig Topper4f12f102014-03-12 06:41:41 +000061 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000062 // Structures with either a non-trivial destructor or a non-trivial
63 // copy constructor are always indirect.
64 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
65 return RAA_Indirect;
66 return RAA_Default;
67 }
68
Craig Topper4f12f102014-03-12 06:41:41 +000069 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000070
Craig Topper4f12f102014-03-12 06:41:41 +000071 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +000072
Craig Topper4f12f102014-03-12 06:41:41 +000073 llvm::Value *
74 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
75 const Expr *E,
76 llvm::Value *&This,
77 llvm::Value *MemFnPtr,
78 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +000079
Craig Topper4f12f102014-03-12 06:41:41 +000080 llvm::Value *
81 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
82 llvm::Value *Base,
83 llvm::Value *MemPtr,
84 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +000085
John McCall7a9aac22010-08-23 01:21:21 +000086 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
87 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000088 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +000089 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000090 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +000091
Craig Topper4f12f102014-03-12 06:41:41 +000092 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000093
Craig Topper4f12f102014-03-12 06:41:41 +000094 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000095 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000096 CharUnits offset) override;
97 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +000098 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
99 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000100
John McCall7a9aac22010-08-23 01:21:21 +0000101 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000102 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000103 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000104 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000105
John McCall7a9aac22010-08-23 01:21:21 +0000106 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000107 llvm::Value *Addr,
108 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000109
Craig Topper4f12f102014-03-12 06:41:41 +0000110 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr,
111 QualType type) override;
John McCall82fb8922012-09-25 10:10:39 +0000112
Craig Topper4f12f102014-03-12 06:41:41 +0000113 llvm::Value *
114 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
115 const CXXRecordDecl *ClassDecl,
116 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000117
John McCall5d865c322010-08-31 07:33:07 +0000118 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
Craig Topper4f12f102014-03-12 06:41:41 +0000119 CXXCtorType T, CanQualType &ResTy,
120 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000121
Craig Topper4f12f102014-03-12 06:41:41 +0000122 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000123
John McCall5d865c322010-08-31 07:33:07 +0000124 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000125 CXXDtorType T, CanQualType &ResTy,
126 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000127
Reid Klecknere7de47e2013-07-22 13:51:44 +0000128 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000129 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000130 // Itanium does not emit any destructor variant as an inline thunk.
131 // Delegating may occur as an optimization, but all variants are either
132 // emitted with external linkage or as linkonce if they are inline and used.
133 return false;
134 }
135
Craig Topper4f12f102014-03-12 06:41:41 +0000136 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000137
Reid Kleckner89077a12013-12-17 19:46:40 +0000138 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000139 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000140
Craig Topper4f12f102014-03-12 06:41:41 +0000141 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000142
Reid Kleckner89077a12013-12-17 19:46:40 +0000143 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
144 const CXXConstructorDecl *D,
145 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000146 bool Delegating,
147 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000148
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000149 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
150 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000151 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000152
Craig Topper4f12f102014-03-12 06:41:41 +0000153 void emitVTableDefinitions(CodeGenVTables &CGVT,
154 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000155
156 llvm::Value *getVTableAddressPointInStructor(
157 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
158 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000159 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000160
161 llvm::Constant *
162 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000163 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000164
165 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000166 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000167
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000168 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000169 llvm::Value *This,
170 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000171
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000172 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
173 const CXXDestructorDecl *Dtor,
174 CXXDtorType DtorType, SourceLocation CallLoc,
Craig Topper4f12f102014-03-12 06:41:41 +0000175 llvm::Value *This) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000176
Craig Topper4f12f102014-03-12 06:41:41 +0000177 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000178
Craig Topper4f12f102014-03-12 06:41:41 +0000179 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000180 // Allow inlining of thunks by emitting them with available_externally
181 // linkage together with vtables when needed.
182 if (ForVTable)
183 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
184 }
185
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000186 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000187 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000188
189 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000190 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000191
Craig Topper4f12f102014-03-12 06:41:41 +0000192 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
193 StringRef GetDeletedVirtualCallName() override
194 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000195
Craig Topper4f12f102014-03-12 06:41:41 +0000196 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000197 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
198 llvm::Value *NewPtr,
199 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000200 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000201 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000202 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
203 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000204 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000205
John McCallcdf7ef52010-11-06 09:44:32 +0000206 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000207 llvm::GlobalVariable *DeclPtr,
208 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000209 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000210 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000211
212 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
213 llvm::GlobalVariable *Var);
214 void EmitThreadLocalInitFuncs(
215 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Craig Topper4f12f102014-03-12 06:41:41 +0000216 llvm::Function *InitFunc) override;
Richard Smith0f383742014-03-26 22:48:22 +0000217 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
218 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000219
Craig Topper4f12f102014-03-12 06:41:41 +0000220 bool NeedsVTTParameter(GlobalDecl GD) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000221};
John McCall86353412010-08-21 22:46:04 +0000222
223class ARMCXXABI : public ItaniumCXXABI {
224public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000225 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
226 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
227 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000228
Craig Topper4f12f102014-03-12 06:41:41 +0000229 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000230 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
231 isa<CXXDestructorDecl>(GD.getDecl()) &&
232 GD.getDtorType() != Dtor_Deleting));
233 }
John McCall5d865c322010-08-31 07:33:07 +0000234
Craig Topper4f12f102014-03-12 06:41:41 +0000235 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
236 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000239 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
240 llvm::Value *NewPtr,
241 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000242 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000243 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000244 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000245 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000246};
Tim Northovera2ee4332014-03-29 15:09:45 +0000247
248class iOS64CXXABI : public ARMCXXABI {
249public:
250 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
251};
Charles Davis4e786dd2010-05-25 19:52:27 +0000252}
253
Charles Davis53c59df2010-08-16 03:33:14 +0000254CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000255 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000256 // For IR-generation purposes, there's no significant difference
257 // between the ARM and iOS ABIs.
258 case TargetCXXABI::GenericARM:
259 case TargetCXXABI::iOS:
260 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000261
Tim Northovera2ee4332014-03-29 15:09:45 +0000262 case TargetCXXABI::iOS64:
263 return new iOS64CXXABI(CGM);
264
Tim Northover9bb857a2013-01-31 12:13:10 +0000265 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
266 // include the other 32-bit ARM oddities: constructor/destructor return values
267 // and array cookies.
268 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000269 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
270 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000271
John McCall57625922013-01-25 23:36:14 +0000272 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000273 if (CGM.getContext().getTargetInfo().getTriple().getArch()
274 == llvm::Triple::le32) {
275 // For PNaCl, use ARM-style method pointers so that PNaCl code
276 // does not assume anything about the alignment of function
277 // pointers.
278 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
279 /* UseARMGuardVarABI = */ false);
280 }
John McCall57625922013-01-25 23:36:14 +0000281 return new ItaniumCXXABI(CGM);
282
283 case TargetCXXABI::Microsoft:
284 llvm_unreachable("Microsoft ABI is not Itanium-based");
285 }
286 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000287}
288
Chris Lattnera5f58b02011-07-09 17:41:47 +0000289llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000290ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
291 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000292 return CGM.PtrDiffTy;
293 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000294}
295
John McCalld9c6c0b2010-08-22 00:59:17 +0000296/// In the Itanium and ARM ABIs, method pointers have the form:
297/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
298///
299/// In the Itanium ABI:
300/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
301/// - the this-adjustment is (memptr.adj)
302/// - the virtual offset is (memptr.ptr - 1)
303///
304/// In the ARM ABI:
305/// - method pointers are virtual if (memptr.adj & 1) is nonzero
306/// - the this-adjustment is (memptr.adj >> 1)
307/// - the virtual offset is (memptr.ptr)
308/// ARM uses 'adj' for the virtual flag because Thumb functions
309/// may be only single-byte aligned.
310///
311/// If the member is virtual, the adjusted 'this' pointer points
312/// to a vtable pointer from which the virtual offset is applied.
313///
314/// If the member is non-virtual, memptr.ptr is the address of
315/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000316llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
317 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
318 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000319 CGBuilderTy &Builder = CGF.Builder;
320
321 const FunctionProtoType *FPT =
322 MPT->getPointeeType()->getAs<FunctionProtoType>();
323 const CXXRecordDecl *RD =
324 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
325
Chris Lattner2192fe52011-07-18 04:24:23 +0000326 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000327 CGM.getTypes().GetFunctionType(
328 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000329
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000330 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000331
John McCalld9c6c0b2010-08-22 00:59:17 +0000332 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
333 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
334 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
335
John McCalla1dee5302010-08-22 10:59:02 +0000336 // Extract memptr.adj, which is in the second field.
337 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000338
339 // Compute the true adjustment.
340 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000341 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000342 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000343
344 // Apply the adjustment and cast back to the original struct type
345 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000346 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
347 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
348 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000349
350 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000351 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000352
353 // If the LSB in the function pointer is 1, the function pointer points to
354 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000355 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000356 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000357 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
358 else
359 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
360 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000361 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
362
363 // In the virtual path, the adjustment left 'This' pointing to the
364 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000365 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000366 CGF.EmitBlock(FnVirtual);
367
368 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000369 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000370 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000371
372 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000373 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000374 if (!UseARMMethodPtrABI)
375 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000376 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000377
378 // Load the virtual function to call.
379 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000380 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000381 CGF.EmitBranch(FnEnd);
382
383 // In the non-virtual path, the function pointer is actually a
384 // function pointer.
385 CGF.EmitBlock(FnNonVirtual);
386 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000387 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000388
389 // We're done.
390 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000391 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000392 Callee->addIncoming(VirtualFn, FnVirtual);
393 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
394 return Callee;
395}
John McCalla8bbb822010-08-22 03:04:22 +0000396
John McCallc134eb52010-08-31 21:07:20 +0000397/// Compute an l-value by applying the given pointer-to-member to a
398/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000399llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
400 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
401 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000402 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000403
404 CGBuilderTy &Builder = CGF.Builder;
405
Micah Villmowea2fea22012-10-25 15:39:14 +0000406 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000407
408 // Cast to char*.
409 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
410
411 // Apply the offset, which we assume is non-null.
412 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
413
414 // Cast the address to the appropriate pointer type, adopting the
415 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000416 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000417 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000418 return Builder.CreateBitCast(Addr, PType);
419}
420
John McCallc62bb392012-02-15 01:22:51 +0000421/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
422/// conversion.
423///
424/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000425///
426/// Obligatory offset/adjustment diagram:
427/// <-- offset --> <-- adjustment -->
428/// |--------------------------|----------------------|--------------------|
429/// ^Derived address point ^Base address point ^Member address point
430///
431/// So when converting a base member pointer to a derived member pointer,
432/// we add the offset to the adjustment because the address point has
433/// decreased; and conversely, when converting a derived MP to a base MP
434/// we subtract the offset from the adjustment because the address point
435/// has increased.
436///
437/// The standard forbids (at compile time) conversion to and from
438/// virtual bases, which is why we don't have to consider them here.
439///
440/// The standard forbids (at run time) casting a derived MP to a base
441/// MP when the derived MP does not point to a member of the base.
442/// This is why -1 is a reasonable choice for null data member
443/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000444llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000445ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
446 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000447 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000448 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000449 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
450 E->getCastKind() == CK_ReinterpretMemberPointer);
451
452 // Under Itanium, reinterprets don't require any additional processing.
453 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
454
455 // Use constant emission if we can.
456 if (isa<llvm::Constant>(src))
457 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
458
459 llvm::Constant *adj = getMemberPointerAdjustment(E);
460 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000461
462 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000463 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000464
John McCallc62bb392012-02-15 01:22:51 +0000465 const MemberPointerType *destTy =
466 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000467
John McCall7a9aac22010-08-23 01:21:21 +0000468 // For member data pointers, this is just a matter of adding the
469 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000470 if (destTy->isMemberDataPointer()) {
471 llvm::Value *dst;
472 if (isDerivedToBase)
473 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000474 else
John McCallc62bb392012-02-15 01:22:51 +0000475 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000476
477 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000478 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
479 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
480 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000481 }
482
John McCalla1dee5302010-08-22 10:59:02 +0000483 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000484 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000485 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
486 offset <<= 1;
487 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000488 }
489
John McCallc62bb392012-02-15 01:22:51 +0000490 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
491 llvm::Value *dstAdj;
492 if (isDerivedToBase)
493 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000494 else
John McCallc62bb392012-02-15 01:22:51 +0000495 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000496
John McCallc62bb392012-02-15 01:22:51 +0000497 return Builder.CreateInsertValue(src, dstAdj, 1);
498}
499
500llvm::Constant *
501ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
502 llvm::Constant *src) {
503 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
504 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
505 E->getCastKind() == CK_ReinterpretMemberPointer);
506
507 // Under Itanium, reinterprets don't require any additional processing.
508 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
509
510 // If the adjustment is trivial, we don't need to do anything.
511 llvm::Constant *adj = getMemberPointerAdjustment(E);
512 if (!adj) return src;
513
514 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
515
516 const MemberPointerType *destTy =
517 E->getType()->castAs<MemberPointerType>();
518
519 // For member data pointers, this is just a matter of adding the
520 // offset if the source is non-null.
521 if (destTy->isMemberDataPointer()) {
522 // null maps to null.
523 if (src->isAllOnesValue()) return src;
524
525 if (isDerivedToBase)
526 return llvm::ConstantExpr::getNSWSub(src, adj);
527 else
528 return llvm::ConstantExpr::getNSWAdd(src, adj);
529 }
530
531 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000532 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000533 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
534 offset <<= 1;
535 adj = llvm::ConstantInt::get(adj->getType(), offset);
536 }
537
538 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
539 llvm::Constant *dstAdj;
540 if (isDerivedToBase)
541 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
542 else
543 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
544
545 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000546}
John McCall84fa5102010-08-22 04:16:24 +0000547
548llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000549ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000550 // Itanium C++ ABI 2.3:
551 // A NULL pointer is represented as -1.
552 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000553 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000554
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000555 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000556 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000557 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000558}
559
John McCallf3a88602011-02-03 08:15:49 +0000560llvm::Constant *
561ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
562 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000563 // Itanium C++ ABI 2.3:
564 // A pointer to data member is an offset from the base address of
565 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000566 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000567}
568
John McCall2979fe02011-04-12 00:42:48 +0000569llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000570 return BuildMemberPointer(MD, CharUnits::Zero());
571}
572
573llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
574 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000575 assert(MD->isInstance() && "Member function must not be static!");
576 MD = MD->getCanonicalDecl();
577
578 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000579
580 // Get the function pointer (or index if this is a virtual function).
581 llvm::Constant *MemPtr[2];
582 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000583 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000584
Ken Dyckdf016282011-04-09 01:30:02 +0000585 const ASTContext &Context = getContext();
586 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000587 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000588 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000589
Mark Seabornedf0d382013-07-24 16:25:13 +0000590 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000591 // ARM C++ ABI 3.2.1:
592 // This ABI specifies that adj contains twice the this
593 // adjustment, plus 1 if the member function is virtual. The
594 // least significant bit of adj then makes exactly the same
595 // discrimination as the least significant bit of ptr does for
596 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000597 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
598 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000599 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000600 } else {
601 // Itanium C++ ABI 2.3:
602 // For a virtual function, [the pointer field] is 1 plus the
603 // virtual table offset (in bytes) of the function,
604 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000605 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
606 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000607 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000608 }
609 } else {
John McCall2979fe02011-04-12 00:42:48 +0000610 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000611 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000612 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000613 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000614 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000615 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000616 } else {
John McCall2979fe02011-04-12 00:42:48 +0000617 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
618 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000619 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000620 }
John McCall2979fe02011-04-12 00:42:48 +0000621 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000622
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000623 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000624 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
625 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000626 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000627 }
John McCall1c456c82010-08-22 06:43:33 +0000628
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000629 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000630}
631
Richard Smithdafff942012-01-14 04:30:29 +0000632llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
633 QualType MPType) {
634 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
635 const ValueDecl *MPD = MP.getMemberPointerDecl();
636 if (!MPD)
637 return EmitNullMemberPointer(MPT);
638
Reid Kleckner452abac2013-05-09 21:01:17 +0000639 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000640
641 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
642 return BuildMemberPointer(MD, ThisAdjustment);
643
644 CharUnits FieldOffset =
645 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
646 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
647}
648
John McCall131d97d2010-08-22 08:30:07 +0000649/// The comparison algorithm is pretty easy: the member pointers are
650/// the same if they're either bitwise identical *or* both null.
651///
652/// ARM is different here only because null-ness is more complicated.
653llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000654ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
655 llvm::Value *L,
656 llvm::Value *R,
657 const MemberPointerType *MPT,
658 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000659 CGBuilderTy &Builder = CGF.Builder;
660
John McCall131d97d2010-08-22 08:30:07 +0000661 llvm::ICmpInst::Predicate Eq;
662 llvm::Instruction::BinaryOps And, Or;
663 if (Inequality) {
664 Eq = llvm::ICmpInst::ICMP_NE;
665 And = llvm::Instruction::Or;
666 Or = llvm::Instruction::And;
667 } else {
668 Eq = llvm::ICmpInst::ICMP_EQ;
669 And = llvm::Instruction::And;
670 Or = llvm::Instruction::Or;
671 }
672
John McCall7a9aac22010-08-23 01:21:21 +0000673 // Member data pointers are easy because there's a unique null
674 // value, so it just comes down to bitwise equality.
675 if (MPT->isMemberDataPointer())
676 return Builder.CreateICmp(Eq, L, R);
677
678 // For member function pointers, the tautologies are more complex.
679 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000680 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000681 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000682 // (L == R) <==> (L.ptr == R.ptr &&
683 // (L.adj == R.adj ||
684 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000685 // The inequality tautologies have exactly the same structure, except
686 // applying De Morgan's laws.
687
688 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
689 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
690
John McCall131d97d2010-08-22 08:30:07 +0000691 // This condition tests whether L.ptr == R.ptr. This must always be
692 // true for equality to hold.
693 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
694
695 // This condition, together with the assumption that L.ptr == R.ptr,
696 // tests whether the pointers are both null. ARM imposes an extra
697 // condition.
698 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
699 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
700
701 // This condition tests whether L.adj == R.adj. If this isn't
702 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000703 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
704 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000705 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
706
707 // Null member function pointers on ARM clear the low bit of Adj,
708 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000709 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000710 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
711
712 // Compute (l.adj | r.adj) & 1 and test it against zero.
713 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
714 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
715 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
716 "cmp.or.adj");
717 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
718 }
719
720 // Tie together all our conditions.
721 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
722 Result = Builder.CreateBinOp(And, PtrEq, Result,
723 Inequality ? "memptr.ne" : "memptr.eq");
724 return Result;
725}
726
727llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000728ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
729 llvm::Value *MemPtr,
730 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000731 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000732
733 /// For member data pointers, this is just a check against -1.
734 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000735 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000736 llvm::Value *NegativeOne =
737 llvm::Constant::getAllOnesValue(MemPtr->getType());
738 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
739 }
John McCall131d97d2010-08-22 08:30:07 +0000740
Daniel Dunbar914bc412011-04-19 23:10:47 +0000741 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000742 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000743
744 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
745 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
746
Daniel Dunbar914bc412011-04-19 23:10:47 +0000747 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
748 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000749 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000750 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000751 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000752 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000753 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
754 "memptr.isvirtual");
755 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000756 }
757
758 return Result;
759}
John McCall1c456c82010-08-22 06:43:33 +0000760
John McCall614dbdc2010-08-22 21:01:12 +0000761/// The Itanium ABI requires non-zero initialization only for data
762/// member pointers, for which '0' is a valid offset.
763bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
764 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000765}
John McCall5d865c322010-08-31 07:33:07 +0000766
John McCall82fb8922012-09-25 10:10:39 +0000767/// The Itanium ABI always places an offset to the complete object
768/// at entry -2 in the vtable.
769llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
770 llvm::Value *ptr,
771 QualType type) {
772 // Grab the vtable pointer as an intptr_t*.
773 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
774
775 // Track back to entry -2 and pull out the offset there.
776 llvm::Value *offsetPtr =
777 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
778 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
779 offset->setAlignment(CGF.PointerAlignInBytes);
780
781 // Apply the offset.
782 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
783 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
784}
785
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000786llvm::Value *
787ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
788 llvm::Value *This,
789 const CXXRecordDecl *ClassDecl,
790 const CXXRecordDecl *BaseClassDecl) {
791 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
792 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000793 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
794 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000795
796 llvm::Value *VBaseOffsetPtr =
797 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
798 "vbase.offset.ptr");
799 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
800 CGM.PtrDiffTy->getPointerTo());
801
802 llvm::Value *VBaseOffset =
803 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
804
805 return VBaseOffset;
806}
807
John McCall5d865c322010-08-31 07:33:07 +0000808/// The generic ABI passes 'this', plus a VTT if it's initializing a
809/// base subobject.
Reid Kleckner89077a12013-12-17 19:46:40 +0000810void
811ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
812 CXXCtorType Type, CanQualType &ResTy,
813 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000814 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000815
Reid Kleckner89077a12013-12-17 19:46:40 +0000816 // All parameters are already in place except VTT, which goes after 'this'.
817 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +0000818
819 // Check if we need to add a VTT parameter (which has type void **).
820 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
Reid Kleckner89077a12013-12-17 19:46:40 +0000821 ArgTys.insert(ArgTys.begin() + 1,
822 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +0000823}
824
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000825void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
826 // Just make sure we're in sync with TargetCXXABI.
827 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
828
Rafael Espindolac3cde362013-12-09 14:51:17 +0000829 // The constructor used for constructing this as a base class;
830 // ignores virtual bases.
831 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
832
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000833 // The constructor used for constructing this as a complete class;
834 // constucts the virtual bases, then calls the base constructor.
835 if (!D->getParent()->isAbstract()) {
836 // We don't need to emit the complete ctor if the class is abstract.
837 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
838 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000839}
840
John McCall5d865c322010-08-31 07:33:07 +0000841/// The generic ABI passes 'this', plus a VTT if it's destroying a
842/// base subobject.
843void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
844 CXXDtorType Type,
845 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000846 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000847 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000848
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000849 // 'this' parameter is already there, as well as 'this' return if
850 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000851
852 // Check if we need to add a VTT parameter (which has type void **).
853 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
854 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
855}
856
Reid Klecknere7de47e2013-07-22 13:51:44 +0000857void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +0000858 // The destructor used for destructing this as a base class; ignores
859 // virtual bases.
860 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000861
862 // The destructor used for destructing this as a most-derived class;
863 // call the base destructor and then destructs any virtual bases.
864 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
865
Rafael Espindolac3cde362013-12-09 14:51:17 +0000866 // The destructor in a virtual table is always a 'deleting'
867 // destructor, which calls the complete destructor and then uses the
868 // appropriate operator delete.
869 if (D->isVirtual())
870 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000871}
872
Reid Kleckner89077a12013-12-17 19:46:40 +0000873void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
874 QualType &ResTy,
875 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +0000876 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +0000877 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +0000878
879 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000880 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +0000881 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000882
883 // FIXME: avoid the fake decl
884 QualType T = Context.getPointerType(Context.VoidPtrTy);
885 ImplicitParamDecl *VTTDecl
886 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
887 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +0000888 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +0000889 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +0000890 }
891}
892
John McCall5d865c322010-08-31 07:33:07 +0000893void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
894 /// Initialize the 'this' slot.
895 EmitThisParam(CGF);
896
897 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +0000898 if (getStructorImplicitParamDecl(CGF)) {
899 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
900 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +0000901 }
John McCall5d865c322010-08-31 07:33:07 +0000902
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000903 /// If this is a function that the ABI specifies returns 'this', initialize
904 /// the return slot to 'this' at the start of the function.
905 ///
906 /// Unlike the setting of return types, this is done within the ABI
907 /// implementation instead of by clients of CGCXXABI because:
908 /// 1) getThisValue is currently protected
909 /// 2) in theory, an ABI could implement 'this' returns some other way;
910 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +0000911 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +0000912 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +0000913}
914
Reid Kleckner89077a12013-12-17 19:46:40 +0000915unsigned ItaniumCXXABI::addImplicitConstructorArgs(
916 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
917 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
918 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
919 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000920
Reid Kleckner89077a12013-12-17 19:46:40 +0000921 // Insert the implicit 'vtt' argument as the second argument.
922 llvm::Value *VTT =
923 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
924 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
925 Args.insert(Args.begin() + 1,
926 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
927 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000928}
929
930void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
931 const CXXDestructorDecl *DD,
932 CXXDtorType Type, bool ForVirtualBase,
933 bool Delegating, llvm::Value *This) {
934 GlobalDecl GD(DD, Type);
935 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
936 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
937
938 llvm::Value *Callee = 0;
939 if (getContext().getLangOpts().AppleKext)
940 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
941
942 if (!Callee)
943 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
944
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000945 // FIXME: Provide a source location here.
946 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
947 VTT, VTTTy, 0, 0);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000948}
949
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000950void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
951 const CXXRecordDecl *RD) {
952 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
953 if (VTable->hasInitializer())
954 return;
955
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000956 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000957 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
958 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
959
960 // Create and set the initializer.
961 llvm::Constant *Init = CGVT.CreateVTableInitializer(
962 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
963 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
964 VTable->setInitializer(Init);
965
966 // Set the correct linkage.
967 VTable->setLinkage(Linkage);
968
969 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +0000970 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000971
972 // If this is the magic class __cxxabiv1::__fundamental_type_info,
973 // we will emit the typeinfo for the fundamental types. This is the
974 // same behaviour as GCC.
975 const DeclContext *DC = RD->getDeclContext();
976 if (RD->getIdentifier() &&
977 RD->getIdentifier()->isStr("__fundamental_type_info") &&
978 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
979 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
980 DC->getParent()->isTranslationUnit())
981 CGM.EmitFundamentalRTTIDescriptors();
982}
983
984llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
985 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
986 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
987 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
988 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
989
990 llvm::Value *VTableAddressPoint;
991 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
992 // Get the secondary vpointer index.
993 uint64_t VirtualPointerIndex =
994 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
995
996 /// Load the VTT.
997 llvm::Value *VTT = CGF.LoadCXXVTT();
998 if (VirtualPointerIndex)
999 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1000
1001 // And load the address point from the VTT.
1002 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1003 } else {
1004 llvm::Constant *VTable =
1005 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001006 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1007 .getVTableLayout(VTableClass)
1008 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001009 VTableAddressPoint =
1010 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1011 }
1012
1013 return VTableAddressPoint;
1014}
1015
1016llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1017 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1018 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1019
1020 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001021 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1022 .getVTableLayout(VTableClass)
1023 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001024 llvm::Value *Indices[] = {
1025 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1026 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1027 };
1028
1029 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1030}
1031
1032llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1033 CharUnits VPtrOffset) {
1034 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1035
1036 llvm::GlobalVariable *&VTable = VTables[RD];
1037 if (VTable)
1038 return VTable;
1039
1040 // Queue up this v-table for possible deferred emission.
1041 CGM.addDeferredVTable(RD);
1042
1043 SmallString<256> OutName;
1044 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001045 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001046 Out.flush();
1047 StringRef Name = OutName.str();
1048
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001049 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001050 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1051 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1052
1053 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1054 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1055 VTable->setUnnamedAddr(true);
1056 return VTable;
1057}
1058
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001059llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1060 GlobalDecl GD,
1061 llvm::Value *This,
1062 llvm::Type *Ty) {
1063 GD = GD.getCanonicalDecl();
1064 Ty = Ty->getPointerTo()->getPointerTo();
1065 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1066
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001067 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001068 llvm::Value *VFuncPtr =
1069 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1070 return CGF.Builder.CreateLoad(VFuncPtr);
1071}
1072
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001073void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1074 const CXXDestructorDecl *Dtor,
1075 CXXDtorType DtorType,
1076 SourceLocation CallLoc,
1077 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001078 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1079
1080 const CGFunctionInfo *FInfo
1081 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1082 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001083 llvm::Value *Callee =
1084 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001085
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001086 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1087 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001088}
1089
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001090void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001091 CodeGenVTables &VTables = CGM.getVTables();
1092 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001093 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001094}
1095
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001096static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1097 llvm::Value *Ptr,
1098 int64_t NonVirtualAdjustment,
1099 int64_t VirtualAdjustment,
1100 bool IsReturnAdjustment) {
1101 if (!NonVirtualAdjustment && !VirtualAdjustment)
1102 return Ptr;
1103
1104 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1105 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1106
1107 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1108 // Perform the non-virtual adjustment for a base-to-derived cast.
1109 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1110 }
1111
1112 if (VirtualAdjustment) {
1113 llvm::Type *PtrDiffTy =
1114 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1115
1116 // Perform the virtual adjustment.
1117 llvm::Value *VTablePtrPtr =
1118 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1119
1120 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1121
1122 llvm::Value *OffsetPtr =
1123 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1124
1125 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1126
1127 // Load the adjustment offset from the vtable.
1128 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1129
1130 // Adjust our pointer.
1131 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1132 }
1133
1134 if (NonVirtualAdjustment && IsReturnAdjustment) {
1135 // Perform the non-virtual adjustment for a derived-to-base cast.
1136 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1137 }
1138
1139 // Cast back to the original type.
1140 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1141}
1142
1143llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1144 llvm::Value *This,
1145 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001146 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1147 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001148 /*IsReturnAdjustment=*/false);
1149}
1150
1151llvm::Value *
1152ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1153 const ReturnAdjustment &RA) {
1154 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1155 RA.Virtual.Itanium.VBaseOffsetOffset,
1156 /*IsReturnAdjustment=*/true);
1157}
1158
John McCall5d865c322010-08-31 07:33:07 +00001159void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1160 RValue RV, QualType ResultType) {
1161 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1162 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1163
1164 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001165 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001166 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1167 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1168 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1169}
John McCall8ed55a52010-09-02 09:58:18 +00001170
1171/************************** Array allocation cookies **************************/
1172
John McCallb91cd662012-05-01 05:23:51 +00001173CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1174 // The array cookie is a size_t; pad that up to the element alignment.
1175 // The cookie is actually right-justified in that space.
1176 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1177 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001178}
1179
1180llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1181 llvm::Value *NewPtr,
1182 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001183 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001184 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001185 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001186
Micah Villmowea2fea22012-10-25 15:39:14 +00001187 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001188
John McCall9bca9232010-09-02 10:25:57 +00001189 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001190 QualType SizeTy = Ctx.getSizeType();
1191 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1192
1193 // The size of the cookie.
1194 CharUnits CookieSize =
1195 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001196 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001197
1198 // Compute an offset to the cookie.
1199 llvm::Value *CookiePtr = NewPtr;
1200 CharUnits CookieOffset = CookieSize - SizeSize;
1201 if (!CookieOffset.isZero())
1202 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1203 CookieOffset.getQuantity());
1204
1205 // Write the number of elements into the appropriate slot.
1206 llvm::Value *NumElementsPtr
1207 = CGF.Builder.CreateBitCast(CookiePtr,
1208 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1209 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1210
1211 // Finally, compute a pointer to the actual data buffer by skipping
1212 // over the cookie completely.
1213 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1214 CookieSize.getQuantity());
1215}
1216
John McCallb91cd662012-05-01 05:23:51 +00001217llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1218 llvm::Value *allocPtr,
1219 CharUnits cookieSize) {
1220 // The element size is right-justified in the cookie.
1221 llvm::Value *numElementsPtr = allocPtr;
1222 CharUnits numElementsOffset =
1223 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1224 if (!numElementsOffset.isZero())
1225 numElementsPtr =
1226 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1227 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001228
Micah Villmowea2fea22012-10-25 15:39:14 +00001229 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001230 numElementsPtr =
1231 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1232 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001233}
1234
John McCallb91cd662012-05-01 05:23:51 +00001235CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001236 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001237 // struct array_cookie {
1238 // std::size_t element_size; // element_size != 0
1239 // std::size_t element_count;
1240 // };
John McCallc19c7062013-01-25 23:36:19 +00001241 // But the base ABI doesn't give anything an alignment greater than
1242 // 8, so we can dismiss this as typical ABI-author blindness to
1243 // actual language complexity and round up to the element alignment.
1244 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1245 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001246}
1247
1248llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001249 llvm::Value *newPtr,
1250 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001251 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001252 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001253 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001254
John McCallc19c7062013-01-25 23:36:19 +00001255 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1256 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001257
1258 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001259 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001260
1261 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001262 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1263 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1264 getContext().getTypeSizeInChars(elementType).getQuantity());
1265 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001266
1267 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001268 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1269 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001270
1271 // Finally, compute a pointer to the actual data buffer by skipping
1272 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001273 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1274 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1275 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001276}
1277
John McCallb91cd662012-05-01 05:23:51 +00001278llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1279 llvm::Value *allocPtr,
1280 CharUnits cookieSize) {
1281 // The number of elements is at offset sizeof(size_t) relative to
1282 // the allocated pointer.
1283 llvm::Value *numElementsPtr
1284 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001285
Micah Villmowea2fea22012-10-25 15:39:14 +00001286 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001287 numElementsPtr =
1288 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1289 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001290}
1291
John McCall68ff0372010-09-08 01:44:27 +00001292/*********************** Static local initialization **************************/
1293
1294static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001295 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001296 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001297 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001298 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001299 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001300 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001301 llvm::AttributeSet::get(CGM.getLLVMContext(),
1302 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001303 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001304}
1305
1306static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001307 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001308 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001309 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001310 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001311 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001312 llvm::AttributeSet::get(CGM.getLLVMContext(),
1313 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001314 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001315}
1316
1317static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001318 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001319 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001320 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001321 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001322 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001323 llvm::AttributeSet::get(CGM.getLLVMContext(),
1324 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001325 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001326}
1327
1328namespace {
1329 struct CallGuardAbort : EHScopeStack::Cleanup {
1330 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001331 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001332
Craig Topper4f12f102014-03-12 06:41:41 +00001333 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001334 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1335 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001336 }
1337 };
1338}
1339
1340/// The ARM code here follows the Itanium code closely enough that we
1341/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001342void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1343 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001344 llvm::GlobalVariable *var,
1345 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001346 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001347
Richard Smithdbf74ba2013-04-14 23:01:42 +00001348 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001349 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001350 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1351 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001352
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001353 // If we have a global variable with internal linkage and thread-safe statics
1354 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001355 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1356
1357 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001358 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001359 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001360 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001361 // Guard variables are 64 bits in the generic ABI and size width on ARM
1362 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001363 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001364 }
John McCallb88a5662012-03-30 21:00:39 +00001365 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001366
John McCallb88a5662012-03-30 21:00:39 +00001367 // Create the guard variable if we don't already have it (as we
1368 // might if we're double-emitting this function body).
1369 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1370 if (!guard) {
1371 // Mangle the name for the guard.
1372 SmallString<256> guardName;
1373 {
1374 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001375 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001376 out.flush();
1377 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001378
John McCallb88a5662012-03-30 21:00:39 +00001379 // Create the guard variable with a zero-initializer.
1380 // Just absorb linkage and visibility from the guarded variable.
1381 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1382 false, var->getLinkage(),
1383 llvm::ConstantInt::get(guardTy, 0),
1384 guardName.str());
1385 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001386 // If the variable is thread-local, so is its guard variable.
1387 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001388
1389 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1390 }
John McCall87590e62012-03-30 07:09:50 +00001391
John McCall68ff0372010-09-08 01:44:27 +00001392 // Test whether the variable has completed initialization.
John McCallb88a5662012-03-30 21:00:39 +00001393 llvm::Value *isInitialized;
John McCall68ff0372010-09-08 01:44:27 +00001394
1395 // ARM C++ ABI 3.2.3.1:
1396 // To support the potential use of initialization guard variables
1397 // as semaphores that are the target of ARM SWP and LDREX/STREX
1398 // synchronizing instructions we define a static initialization
1399 // guard variable to be a 4-byte aligned, 4- byte word with the
1400 // following inline access protocol.
1401 // #define INITIALIZED 1
1402 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1403 // if (__cxa_guard_acquire(&obj_guard))
1404 // ...
1405 // }
Mark Seabornedf0d382013-07-24 16:25:13 +00001406 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001407 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northover9bb857a2013-01-31 12:13:10 +00001408 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1409 V = Builder.CreateAnd(V, Test1);
John McCallb88a5662012-03-30 21:00:39 +00001410 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001411
1412 // Itanium C++ ABI 3.3.2:
1413 // The following is pseudo-code showing how these functions can be used:
1414 // if (obj_guard.first_byte == 0) {
1415 // if ( __cxa_guard_acquire (&obj_guard) ) {
1416 // try {
1417 // ... initialize the object ...;
1418 // } catch (...) {
1419 // __cxa_guard_abort (&obj_guard);
1420 // throw;
1421 // }
1422 // ... queue object destructor with __cxa_atexit() ...;
1423 // __cxa_guard_release (&obj_guard);
1424 // }
1425 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001426
1427 // ARM64 C++ ABI 3.2.2:
1428 // This ABI instead only specifies the value bit 0 of the static guard
1429 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1430 // variable is not initialized and 1 when it is.
1431 // FIXME: Reading one bit is no more efficient than reading one byte so
1432 // the codegen is same as generic Itanium ABI.
John McCall68ff0372010-09-08 01:44:27 +00001433 } else {
1434 // Load the first byte of the guard variable.
Chandler Carruth84537952012-03-30 19:44:53 +00001435 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001436 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth84537952012-03-30 19:44:53 +00001437 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001438
Eli Friedman84d28122011-09-13 22:21:56 +00001439 // Itanium ABI:
1440 // An implementation supporting thread-safety on multiprocessor
1441 // systems must also guarantee that references to the initialized
1442 // object do not occur before the load of the initialization flag.
1443 //
1444 // In LLVM, we do this by marking the load Acquire.
1445 if (threadsafe)
Chandler Carruth84537952012-03-30 19:44:53 +00001446 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001447
John McCallb88a5662012-03-30 21:00:39 +00001448 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001449 }
1450
1451 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1452 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1453
1454 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001455 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001456
1457 CGF.EmitBlock(InitCheckBlock);
1458
1459 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001460 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001461 // Call __cxa_guard_acquire.
1462 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001463 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001464
1465 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1466
1467 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1468 InitBlock, EndBlock);
1469
1470 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001471 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001472
1473 CGF.EmitBlock(InitBlock);
1474 }
1475
1476 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001477 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001478
John McCall5aa52592011-06-17 07:33:57 +00001479 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001480 // Pop the guard-abort cleanup if we pushed one.
1481 CGF.PopCleanupBlock();
1482
1483 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001484 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001485 } else {
John McCallb88a5662012-03-30 21:00:39 +00001486 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001487 }
1488
1489 CGF.EmitBlock(EndBlock);
1490}
John McCallc84ed6a2012-05-01 06:13:13 +00001491
1492/// Register a global destructor using __cxa_atexit.
1493static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1494 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001495 llvm::Constant *addr,
1496 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001497 const char *Name = "__cxa_atexit";
1498 if (TLS) {
1499 const llvm::Triple &T = CGF.getTarget().getTriple();
1500 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1501 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001502
John McCallc84ed6a2012-05-01 06:13:13 +00001503 // We're assuming that the destructor function is something we can
1504 // reasonably call with the default CC. Go ahead and cast it to the
1505 // right prototype.
1506 llvm::Type *dtorTy =
1507 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1508
1509 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1510 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1511 llvm::FunctionType *atexitTy =
1512 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1513
1514 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001515 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001516 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1517 fn->setDoesNotThrow();
1518
1519 // Create a variable that binds the atexit to this shared object.
1520 llvm::Constant *handle =
1521 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1522
1523 llvm::Value *args[] = {
1524 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1525 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1526 handle
1527 };
John McCall882987f2013-02-28 19:01:20 +00001528 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001529}
1530
1531/// Register a global destructor as best as we know how.
1532void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001533 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001534 llvm::Constant *dtor,
1535 llvm::Constant *addr) {
1536 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001537 if (CGM.getCodeGenOpts().CXAAtExit)
1538 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1539
1540 if (D.getTLSKind())
1541 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001542
1543 // In Apple kexts, we want to add a global destructor entry.
1544 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001545 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001546 // Generate a global destructor entry.
1547 return CGM.AddCXXDtorEntry(dtor, addr);
1548 }
1549
David Blaikieebe87e12013-08-27 23:57:18 +00001550 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001551}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001552
1553/// Get the appropriate linkage for the wrapper function. This is essentially
1554/// the weak form of the variable's linkage; every translation unit which wneeds
1555/// the wrapper emits a copy, and we want the linker to merge them.
1556static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1557 llvm::GlobalValue::LinkageTypes VarLinkage) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001558 // For internal linkage variables, we don't need an external or weak wrapper.
1559 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1560 return VarLinkage;
1561 return llvm::GlobalValue::WeakODRLinkage;
1562}
1563
1564llvm::Function *
1565ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1566 llvm::GlobalVariable *Var) {
1567 // Mangle the name for the thread_local wrapper function.
1568 SmallString<256> WrapperName;
1569 {
1570 llvm::raw_svector_ostream Out(WrapperName);
1571 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1572 Out.flush();
1573 }
1574
1575 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1576 return cast<llvm::Function>(V);
1577
1578 llvm::Type *RetTy = Var->getType();
1579 if (VD->getType()->isReferenceType())
1580 RetTy = RetTy->getPointerElementType();
1581
1582 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1583 llvm::Function *Wrapper = llvm::Function::Create(
1584 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1585 &CGM.getModule());
1586 // Always resolve references to the wrapper at link time.
1587 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1588 return Wrapper;
1589}
1590
1591void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1592 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1593 llvm::Function *InitFunc) {
1594 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1595 const VarDecl *VD = Decls[I].first;
1596 llvm::GlobalVariable *Var = Decls[I].second;
1597
1598 // Mangle the name for the thread_local initialization function.
1599 SmallString<256> InitFnName;
1600 {
1601 llvm::raw_svector_ostream Out(InitFnName);
1602 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1603 Out.flush();
1604 }
1605
1606 // If we have a definition for the variable, emit the initialization
1607 // function as an alias to the global Init function (if any). Otherwise,
1608 // produce a declaration of the initialization function.
1609 llvm::GlobalValue *Init = 0;
1610 bool InitIsInitFunc = false;
1611 if (VD->hasDefinition()) {
1612 InitIsInitFunc = true;
1613 if (InitFunc)
1614 Init =
1615 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1616 InitFnName.str(), InitFunc, &CGM.getModule());
1617 } else {
1618 // Emit a weak global function referring to the initialization function.
1619 // This function will not exist if the TU defining the thread_local
1620 // variable in question does not need any dynamic initialization for
1621 // its thread_local variables.
1622 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1623 Init = llvm::Function::Create(
1624 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1625 &CGM.getModule());
1626 }
1627
1628 if (Init)
1629 Init->setVisibility(Var->getVisibility());
1630
1631 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1632 llvm::LLVMContext &Context = CGM.getModule().getContext();
1633 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1634 CGBuilderTy Builder(Entry);
1635 if (InitIsInitFunc) {
1636 if (Init)
1637 Builder.CreateCall(Init);
1638 } else {
1639 // Don't know whether we have an init function. Call it if it exists.
1640 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1641 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1642 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1643 Builder.CreateCondBr(Have, InitBB, ExitBB);
1644
1645 Builder.SetInsertPoint(InitBB);
1646 Builder.CreateCall(Init);
1647 Builder.CreateBr(ExitBB);
1648
1649 Builder.SetInsertPoint(ExitBB);
1650 }
1651
1652 // For a reference, the result of the wrapper function is a pointer to
1653 // the referenced object.
1654 llvm::Value *Val = Var;
1655 if (VD->getType()->isReferenceType()) {
1656 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1657 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1658 Val = LI;
1659 }
1660
1661 Builder.CreateRet(Val);
1662 }
1663}
1664
Richard Smith0f383742014-03-26 22:48:22 +00001665LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1666 const VarDecl *VD,
1667 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001668 QualType T = VD->getType();
1669 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1670 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1671 llvm::Function *Wrapper =
1672 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1673
1674 Val = CGF.Builder.CreateCall(Wrapper);
1675
1676 LValue LV;
1677 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00001678 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001679 else
Richard Smith0f383742014-03-26 22:48:22 +00001680 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001681 // FIXME: need setObjCGCLValueClass?
1682 return LV;
1683}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001684
1685/// Return whether the given global decl needs a VTT parameter, which it does
1686/// if it's a base constructor or destructor with virtual bases.
1687bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1688 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1689
1690 // We don't have any virtual bases, just return early.
1691 if (!MD->getParent()->getNumVBases())
1692 return false;
1693
1694 // Check if we have a base constructor.
1695 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1696 return true;
1697
1698 // Check if we have a base destructor.
1699 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1700 return true;
1701
1702 return false;
1703}