blob: f6e9d9d7681140141cd5e587f2954b0ca119fe83 [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 Smith2fd1d7a2013-04-19 16:42:07 +0000217 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000218 const DeclRefExpr *DRE) 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};
Charles Davis4e786dd2010-05-25 19:52:27 +0000247}
248
Charles Davis53c59df2010-08-16 03:33:14 +0000249CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000250 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000251 // For IR-generation purposes, there's no significant difference
252 // between the ARM and iOS ABIs.
253 case TargetCXXABI::GenericARM:
254 case TargetCXXABI::iOS:
255 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000256
Tim Northover9bb857a2013-01-31 12:13:10 +0000257 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
258 // include the other 32-bit ARM oddities: constructor/destructor return values
259 // and array cookies.
260 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000261 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
262 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000263
John McCall57625922013-01-25 23:36:14 +0000264 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000265 if (CGM.getContext().getTargetInfo().getTriple().getArch()
266 == llvm::Triple::le32) {
267 // For PNaCl, use ARM-style method pointers so that PNaCl code
268 // does not assume anything about the alignment of function
269 // pointers.
270 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
271 /* UseARMGuardVarABI = */ false);
272 }
John McCall57625922013-01-25 23:36:14 +0000273 return new ItaniumCXXABI(CGM);
274
275 case TargetCXXABI::Microsoft:
276 llvm_unreachable("Microsoft ABI is not Itanium-based");
277 }
278 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000279}
280
Chris Lattnera5f58b02011-07-09 17:41:47 +0000281llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000282ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
283 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000284 return CGM.PtrDiffTy;
285 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000286}
287
John McCalld9c6c0b2010-08-22 00:59:17 +0000288/// In the Itanium and ARM ABIs, method pointers have the form:
289/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
290///
291/// In the Itanium ABI:
292/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
293/// - the this-adjustment is (memptr.adj)
294/// - the virtual offset is (memptr.ptr - 1)
295///
296/// In the ARM ABI:
297/// - method pointers are virtual if (memptr.adj & 1) is nonzero
298/// - the this-adjustment is (memptr.adj >> 1)
299/// - the virtual offset is (memptr.ptr)
300/// ARM uses 'adj' for the virtual flag because Thumb functions
301/// may be only single-byte aligned.
302///
303/// If the member is virtual, the adjusted 'this' pointer points
304/// to a vtable pointer from which the virtual offset is applied.
305///
306/// If the member is non-virtual, memptr.ptr is the address of
307/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000308llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
309 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
310 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000311 CGBuilderTy &Builder = CGF.Builder;
312
313 const FunctionProtoType *FPT =
314 MPT->getPointeeType()->getAs<FunctionProtoType>();
315 const CXXRecordDecl *RD =
316 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
317
Chris Lattner2192fe52011-07-18 04:24:23 +0000318 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000319 CGM.getTypes().GetFunctionType(
320 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000321
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000322 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000323
John McCalld9c6c0b2010-08-22 00:59:17 +0000324 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
325 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
326 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
327
John McCalla1dee5302010-08-22 10:59:02 +0000328 // Extract memptr.adj, which is in the second field.
329 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000330
331 // Compute the true adjustment.
332 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000333 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000334 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000335
336 // Apply the adjustment and cast back to the original struct type
337 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000338 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
339 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
340 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000341
342 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000343 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000344
345 // If the LSB in the function pointer is 1, the function pointer points to
346 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000347 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000348 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000349 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
350 else
351 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
352 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000353 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
354
355 // In the virtual path, the adjustment left 'This' pointing to the
356 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000357 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000358 CGF.EmitBlock(FnVirtual);
359
360 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000361 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000362 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000363
364 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000365 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000366 if (!UseARMMethodPtrABI)
367 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000368 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000369
370 // Load the virtual function to call.
371 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000372 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000373 CGF.EmitBranch(FnEnd);
374
375 // In the non-virtual path, the function pointer is actually a
376 // function pointer.
377 CGF.EmitBlock(FnNonVirtual);
378 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000379 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000380
381 // We're done.
382 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000383 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000384 Callee->addIncoming(VirtualFn, FnVirtual);
385 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
386 return Callee;
387}
John McCalla8bbb822010-08-22 03:04:22 +0000388
John McCallc134eb52010-08-31 21:07:20 +0000389/// Compute an l-value by applying the given pointer-to-member to a
390/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000391llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
392 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
393 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000394 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000395
396 CGBuilderTy &Builder = CGF.Builder;
397
Micah Villmowea2fea22012-10-25 15:39:14 +0000398 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000399
400 // Cast to char*.
401 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
402
403 // Apply the offset, which we assume is non-null.
404 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
405
406 // Cast the address to the appropriate pointer type, adopting the
407 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000408 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000409 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000410 return Builder.CreateBitCast(Addr, PType);
411}
412
John McCallc62bb392012-02-15 01:22:51 +0000413/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
414/// conversion.
415///
416/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000417///
418/// Obligatory offset/adjustment diagram:
419/// <-- offset --> <-- adjustment -->
420/// |--------------------------|----------------------|--------------------|
421/// ^Derived address point ^Base address point ^Member address point
422///
423/// So when converting a base member pointer to a derived member pointer,
424/// we add the offset to the adjustment because the address point has
425/// decreased; and conversely, when converting a derived MP to a base MP
426/// we subtract the offset from the adjustment because the address point
427/// has increased.
428///
429/// The standard forbids (at compile time) conversion to and from
430/// virtual bases, which is why we don't have to consider them here.
431///
432/// The standard forbids (at run time) casting a derived MP to a base
433/// MP when the derived MP does not point to a member of the base.
434/// This is why -1 is a reasonable choice for null data member
435/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000436llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000437ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
438 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000439 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000440 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000441 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
442 E->getCastKind() == CK_ReinterpretMemberPointer);
443
444 // Under Itanium, reinterprets don't require any additional processing.
445 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
446
447 // Use constant emission if we can.
448 if (isa<llvm::Constant>(src))
449 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
450
451 llvm::Constant *adj = getMemberPointerAdjustment(E);
452 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000453
454 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000455 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000456
John McCallc62bb392012-02-15 01:22:51 +0000457 const MemberPointerType *destTy =
458 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000459
John McCall7a9aac22010-08-23 01:21:21 +0000460 // For member data pointers, this is just a matter of adding the
461 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000462 if (destTy->isMemberDataPointer()) {
463 llvm::Value *dst;
464 if (isDerivedToBase)
465 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000466 else
John McCallc62bb392012-02-15 01:22:51 +0000467 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000468
469 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000470 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
471 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
472 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000473 }
474
John McCalla1dee5302010-08-22 10:59:02 +0000475 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000476 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000477 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
478 offset <<= 1;
479 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000480 }
481
John McCallc62bb392012-02-15 01:22:51 +0000482 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
483 llvm::Value *dstAdj;
484 if (isDerivedToBase)
485 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000486 else
John McCallc62bb392012-02-15 01:22:51 +0000487 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000488
John McCallc62bb392012-02-15 01:22:51 +0000489 return Builder.CreateInsertValue(src, dstAdj, 1);
490}
491
492llvm::Constant *
493ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
494 llvm::Constant *src) {
495 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
496 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
497 E->getCastKind() == CK_ReinterpretMemberPointer);
498
499 // Under Itanium, reinterprets don't require any additional processing.
500 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
501
502 // If the adjustment is trivial, we don't need to do anything.
503 llvm::Constant *adj = getMemberPointerAdjustment(E);
504 if (!adj) return src;
505
506 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
507
508 const MemberPointerType *destTy =
509 E->getType()->castAs<MemberPointerType>();
510
511 // For member data pointers, this is just a matter of adding the
512 // offset if the source is non-null.
513 if (destTy->isMemberDataPointer()) {
514 // null maps to null.
515 if (src->isAllOnesValue()) return src;
516
517 if (isDerivedToBase)
518 return llvm::ConstantExpr::getNSWSub(src, adj);
519 else
520 return llvm::ConstantExpr::getNSWAdd(src, adj);
521 }
522
523 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000524 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000525 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
526 offset <<= 1;
527 adj = llvm::ConstantInt::get(adj->getType(), offset);
528 }
529
530 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
531 llvm::Constant *dstAdj;
532 if (isDerivedToBase)
533 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
534 else
535 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
536
537 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000538}
John McCall84fa5102010-08-22 04:16:24 +0000539
540llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000541ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000542 // Itanium C++ ABI 2.3:
543 // A NULL pointer is represented as -1.
544 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000545 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000546
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000547 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000548 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000549 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000550}
551
John McCallf3a88602011-02-03 08:15:49 +0000552llvm::Constant *
553ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
554 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000555 // Itanium C++ ABI 2.3:
556 // A pointer to data member is an offset from the base address of
557 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000558 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000559}
560
John McCall2979fe02011-04-12 00:42:48 +0000561llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000562 return BuildMemberPointer(MD, CharUnits::Zero());
563}
564
565llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
566 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000567 assert(MD->isInstance() && "Member function must not be static!");
568 MD = MD->getCanonicalDecl();
569
570 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000571
572 // Get the function pointer (or index if this is a virtual function).
573 llvm::Constant *MemPtr[2];
574 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000575 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000576
Ken Dyckdf016282011-04-09 01:30:02 +0000577 const ASTContext &Context = getContext();
578 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000579 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000580 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000581
Mark Seabornedf0d382013-07-24 16:25:13 +0000582 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000583 // ARM C++ ABI 3.2.1:
584 // This ABI specifies that adj contains twice the this
585 // adjustment, plus 1 if the member function is virtual. The
586 // least significant bit of adj then makes exactly the same
587 // discrimination as the least significant bit of ptr does for
588 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000589 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
590 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000591 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000592 } else {
593 // Itanium C++ ABI 2.3:
594 // For a virtual function, [the pointer field] is 1 plus the
595 // virtual table offset (in bytes) of the function,
596 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000597 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
598 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000599 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000600 }
601 } else {
John McCall2979fe02011-04-12 00:42:48 +0000602 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000603 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000604 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000605 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000606 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000607 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000608 } else {
John McCall2979fe02011-04-12 00:42:48 +0000609 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
610 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000611 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000612 }
John McCall2979fe02011-04-12 00:42:48 +0000613 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000614
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000615 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000616 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
617 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000618 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000619 }
John McCall1c456c82010-08-22 06:43:33 +0000620
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000621 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000622}
623
Richard Smithdafff942012-01-14 04:30:29 +0000624llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
625 QualType MPType) {
626 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
627 const ValueDecl *MPD = MP.getMemberPointerDecl();
628 if (!MPD)
629 return EmitNullMemberPointer(MPT);
630
Reid Kleckner452abac2013-05-09 21:01:17 +0000631 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000632
633 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
634 return BuildMemberPointer(MD, ThisAdjustment);
635
636 CharUnits FieldOffset =
637 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
638 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
639}
640
John McCall131d97d2010-08-22 08:30:07 +0000641/// The comparison algorithm is pretty easy: the member pointers are
642/// the same if they're either bitwise identical *or* both null.
643///
644/// ARM is different here only because null-ness is more complicated.
645llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000646ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
647 llvm::Value *L,
648 llvm::Value *R,
649 const MemberPointerType *MPT,
650 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000651 CGBuilderTy &Builder = CGF.Builder;
652
John McCall131d97d2010-08-22 08:30:07 +0000653 llvm::ICmpInst::Predicate Eq;
654 llvm::Instruction::BinaryOps And, Or;
655 if (Inequality) {
656 Eq = llvm::ICmpInst::ICMP_NE;
657 And = llvm::Instruction::Or;
658 Or = llvm::Instruction::And;
659 } else {
660 Eq = llvm::ICmpInst::ICMP_EQ;
661 And = llvm::Instruction::And;
662 Or = llvm::Instruction::Or;
663 }
664
John McCall7a9aac22010-08-23 01:21:21 +0000665 // Member data pointers are easy because there's a unique null
666 // value, so it just comes down to bitwise equality.
667 if (MPT->isMemberDataPointer())
668 return Builder.CreateICmp(Eq, L, R);
669
670 // For member function pointers, the tautologies are more complex.
671 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000672 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000673 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000674 // (L == R) <==> (L.ptr == R.ptr &&
675 // (L.adj == R.adj ||
676 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000677 // The inequality tautologies have exactly the same structure, except
678 // applying De Morgan's laws.
679
680 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
681 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
682
John McCall131d97d2010-08-22 08:30:07 +0000683 // This condition tests whether L.ptr == R.ptr. This must always be
684 // true for equality to hold.
685 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
686
687 // This condition, together with the assumption that L.ptr == R.ptr,
688 // tests whether the pointers are both null. ARM imposes an extra
689 // condition.
690 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
691 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
692
693 // This condition tests whether L.adj == R.adj. If this isn't
694 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000695 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
696 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000697 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
698
699 // Null member function pointers on ARM clear the low bit of Adj,
700 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000701 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000702 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
703
704 // Compute (l.adj | r.adj) & 1 and test it against zero.
705 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
706 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
707 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
708 "cmp.or.adj");
709 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
710 }
711
712 // Tie together all our conditions.
713 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
714 Result = Builder.CreateBinOp(And, PtrEq, Result,
715 Inequality ? "memptr.ne" : "memptr.eq");
716 return Result;
717}
718
719llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000720ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
721 llvm::Value *MemPtr,
722 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000723 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000724
725 /// For member data pointers, this is just a check against -1.
726 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000727 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000728 llvm::Value *NegativeOne =
729 llvm::Constant::getAllOnesValue(MemPtr->getType());
730 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
731 }
John McCall131d97d2010-08-22 08:30:07 +0000732
Daniel Dunbar914bc412011-04-19 23:10:47 +0000733 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000734 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000735
736 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
737 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
738
Daniel Dunbar914bc412011-04-19 23:10:47 +0000739 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
740 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000741 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000742 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000743 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000744 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000745 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
746 "memptr.isvirtual");
747 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000748 }
749
750 return Result;
751}
John McCall1c456c82010-08-22 06:43:33 +0000752
John McCall614dbdc2010-08-22 21:01:12 +0000753/// The Itanium ABI requires non-zero initialization only for data
754/// member pointers, for which '0' is a valid offset.
755bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
756 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000757}
John McCall5d865c322010-08-31 07:33:07 +0000758
John McCall82fb8922012-09-25 10:10:39 +0000759/// The Itanium ABI always places an offset to the complete object
760/// at entry -2 in the vtable.
761llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
762 llvm::Value *ptr,
763 QualType type) {
764 // Grab the vtable pointer as an intptr_t*.
765 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
766
767 // Track back to entry -2 and pull out the offset there.
768 llvm::Value *offsetPtr =
769 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
770 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
771 offset->setAlignment(CGF.PointerAlignInBytes);
772
773 // Apply the offset.
774 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
775 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
776}
777
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000778llvm::Value *
779ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
780 llvm::Value *This,
781 const CXXRecordDecl *ClassDecl,
782 const CXXRecordDecl *BaseClassDecl) {
783 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
784 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000785 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
786 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000787
788 llvm::Value *VBaseOffsetPtr =
789 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
790 "vbase.offset.ptr");
791 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
792 CGM.PtrDiffTy->getPointerTo());
793
794 llvm::Value *VBaseOffset =
795 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
796
797 return VBaseOffset;
798}
799
John McCall5d865c322010-08-31 07:33:07 +0000800/// The generic ABI passes 'this', plus a VTT if it's initializing a
801/// base subobject.
Reid Kleckner89077a12013-12-17 19:46:40 +0000802void
803ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
804 CXXCtorType Type, CanQualType &ResTy,
805 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000806 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000807
Reid Kleckner89077a12013-12-17 19:46:40 +0000808 // All parameters are already in place except VTT, which goes after 'this'.
809 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +0000810
811 // Check if we need to add a VTT parameter (which has type void **).
812 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
Reid Kleckner89077a12013-12-17 19:46:40 +0000813 ArgTys.insert(ArgTys.begin() + 1,
814 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +0000815}
816
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000817void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
818 // Just make sure we're in sync with TargetCXXABI.
819 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
820
Rafael Espindolac3cde362013-12-09 14:51:17 +0000821 // The constructor used for constructing this as a base class;
822 // ignores virtual bases.
823 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
824
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000825 // The constructor used for constructing this as a complete class;
826 // constucts the virtual bases, then calls the base constructor.
827 if (!D->getParent()->isAbstract()) {
828 // We don't need to emit the complete ctor if the class is abstract.
829 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
830 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000831}
832
John McCall5d865c322010-08-31 07:33:07 +0000833/// The generic ABI passes 'this', plus a VTT if it's destroying a
834/// base subobject.
835void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
836 CXXDtorType Type,
837 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000838 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000839 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000840
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000841 // 'this' parameter is already there, as well as 'this' return if
842 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000843
844 // Check if we need to add a VTT parameter (which has type void **).
845 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
846 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
847}
848
Reid Klecknere7de47e2013-07-22 13:51:44 +0000849void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +0000850 // The destructor used for destructing this as a base class; ignores
851 // virtual bases.
852 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000853
854 // The destructor used for destructing this as a most-derived class;
855 // call the base destructor and then destructs any virtual bases.
856 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
857
Rafael Espindolac3cde362013-12-09 14:51:17 +0000858 // The destructor in a virtual table is always a 'deleting'
859 // destructor, which calls the complete destructor and then uses the
860 // appropriate operator delete.
861 if (D->isVirtual())
862 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000863}
864
Reid Kleckner89077a12013-12-17 19:46:40 +0000865void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
866 QualType &ResTy,
867 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +0000868 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +0000869 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +0000870
871 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000872 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +0000873 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000874
875 // FIXME: avoid the fake decl
876 QualType T = Context.getPointerType(Context.VoidPtrTy);
877 ImplicitParamDecl *VTTDecl
878 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
879 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +0000880 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +0000881 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +0000882 }
883}
884
John McCall5d865c322010-08-31 07:33:07 +0000885void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
886 /// Initialize the 'this' slot.
887 EmitThisParam(CGF);
888
889 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +0000890 if (getStructorImplicitParamDecl(CGF)) {
891 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
892 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +0000893 }
John McCall5d865c322010-08-31 07:33:07 +0000894
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000895 /// If this is a function that the ABI specifies returns 'this', initialize
896 /// the return slot to 'this' at the start of the function.
897 ///
898 /// Unlike the setting of return types, this is done within the ABI
899 /// implementation instead of by clients of CGCXXABI because:
900 /// 1) getThisValue is currently protected
901 /// 2) in theory, an ABI could implement 'this' returns some other way;
902 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +0000903 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +0000904 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +0000905}
906
Reid Kleckner89077a12013-12-17 19:46:40 +0000907unsigned ItaniumCXXABI::addImplicitConstructorArgs(
908 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
909 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
910 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
911 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000912
Reid Kleckner89077a12013-12-17 19:46:40 +0000913 // Insert the implicit 'vtt' argument as the second argument.
914 llvm::Value *VTT =
915 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
916 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
917 Args.insert(Args.begin() + 1,
918 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
919 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000920}
921
922void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
923 const CXXDestructorDecl *DD,
924 CXXDtorType Type, bool ForVirtualBase,
925 bool Delegating, llvm::Value *This) {
926 GlobalDecl GD(DD, Type);
927 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
928 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
929
930 llvm::Value *Callee = 0;
931 if (getContext().getLangOpts().AppleKext)
932 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
933
934 if (!Callee)
935 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
936
937 if (DD->isVirtual())
938 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
939
940 // FIXME: Provide a source location here.
941 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
942 VTT, VTTTy, 0, 0);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000943}
944
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000945void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
946 const CXXRecordDecl *RD) {
947 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
948 if (VTable->hasInitializer())
949 return;
950
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000951 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000952 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
953 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
954
955 // Create and set the initializer.
956 llvm::Constant *Init = CGVT.CreateVTableInitializer(
957 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
958 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
959 VTable->setInitializer(Init);
960
961 // Set the correct linkage.
962 VTable->setLinkage(Linkage);
963
964 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +0000965 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000966
967 // If this is the magic class __cxxabiv1::__fundamental_type_info,
968 // we will emit the typeinfo for the fundamental types. This is the
969 // same behaviour as GCC.
970 const DeclContext *DC = RD->getDeclContext();
971 if (RD->getIdentifier() &&
972 RD->getIdentifier()->isStr("__fundamental_type_info") &&
973 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
974 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
975 DC->getParent()->isTranslationUnit())
976 CGM.EmitFundamentalRTTIDescriptors();
977}
978
979llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
980 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
981 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
982 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
983 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
984
985 llvm::Value *VTableAddressPoint;
986 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
987 // Get the secondary vpointer index.
988 uint64_t VirtualPointerIndex =
989 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
990
991 /// Load the VTT.
992 llvm::Value *VTT = CGF.LoadCXXVTT();
993 if (VirtualPointerIndex)
994 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
995
996 // And load the address point from the VTT.
997 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
998 } else {
999 llvm::Constant *VTable =
1000 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001001 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1002 .getVTableLayout(VTableClass)
1003 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001004 VTableAddressPoint =
1005 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1006 }
1007
1008 return VTableAddressPoint;
1009}
1010
1011llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1012 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1013 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1014
1015 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001016 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1017 .getVTableLayout(VTableClass)
1018 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001019 llvm::Value *Indices[] = {
1020 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1021 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1022 };
1023
1024 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1025}
1026
1027llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1028 CharUnits VPtrOffset) {
1029 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1030
1031 llvm::GlobalVariable *&VTable = VTables[RD];
1032 if (VTable)
1033 return VTable;
1034
1035 // Queue up this v-table for possible deferred emission.
1036 CGM.addDeferredVTable(RD);
1037
1038 SmallString<256> OutName;
1039 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001040 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001041 Out.flush();
1042 StringRef Name = OutName.str();
1043
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001044 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001045 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1046 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1047
1048 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1049 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1050 VTable->setUnnamedAddr(true);
1051 return VTable;
1052}
1053
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001054llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1055 GlobalDecl GD,
1056 llvm::Value *This,
1057 llvm::Type *Ty) {
1058 GD = GD.getCanonicalDecl();
1059 Ty = Ty->getPointerTo()->getPointerTo();
1060 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1061
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001062 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001063 llvm::Value *VFuncPtr =
1064 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1065 return CGF.Builder.CreateLoad(VFuncPtr);
1066}
1067
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001068void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1069 const CXXDestructorDecl *Dtor,
1070 CXXDtorType DtorType,
1071 SourceLocation CallLoc,
1072 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001073 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1074
1075 const CGFunctionInfo *FInfo
1076 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1077 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001078 llvm::Value *Callee =
1079 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001080
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001081 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1082 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001083}
1084
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001085void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001086 CodeGenVTables &VTables = CGM.getVTables();
1087 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001088 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001089}
1090
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001091static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1092 llvm::Value *Ptr,
1093 int64_t NonVirtualAdjustment,
1094 int64_t VirtualAdjustment,
1095 bool IsReturnAdjustment) {
1096 if (!NonVirtualAdjustment && !VirtualAdjustment)
1097 return Ptr;
1098
1099 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1100 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1101
1102 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1103 // Perform the non-virtual adjustment for a base-to-derived cast.
1104 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1105 }
1106
1107 if (VirtualAdjustment) {
1108 llvm::Type *PtrDiffTy =
1109 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1110
1111 // Perform the virtual adjustment.
1112 llvm::Value *VTablePtrPtr =
1113 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1114
1115 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1116
1117 llvm::Value *OffsetPtr =
1118 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1119
1120 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1121
1122 // Load the adjustment offset from the vtable.
1123 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1124
1125 // Adjust our pointer.
1126 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1127 }
1128
1129 if (NonVirtualAdjustment && IsReturnAdjustment) {
1130 // Perform the non-virtual adjustment for a derived-to-base cast.
1131 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1132 }
1133
1134 // Cast back to the original type.
1135 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1136}
1137
1138llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1139 llvm::Value *This,
1140 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001141 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1142 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001143 /*IsReturnAdjustment=*/false);
1144}
1145
1146llvm::Value *
1147ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1148 const ReturnAdjustment &RA) {
1149 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1150 RA.Virtual.Itanium.VBaseOffsetOffset,
1151 /*IsReturnAdjustment=*/true);
1152}
1153
John McCall5d865c322010-08-31 07:33:07 +00001154void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1155 RValue RV, QualType ResultType) {
1156 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1157 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1158
1159 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001160 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001161 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1162 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1163 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1164}
John McCall8ed55a52010-09-02 09:58:18 +00001165
1166/************************** Array allocation cookies **************************/
1167
John McCallb91cd662012-05-01 05:23:51 +00001168CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1169 // The array cookie is a size_t; pad that up to the element alignment.
1170 // The cookie is actually right-justified in that space.
1171 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1172 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001173}
1174
1175llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1176 llvm::Value *NewPtr,
1177 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001178 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001179 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001180 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001181
Micah Villmowea2fea22012-10-25 15:39:14 +00001182 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001183
John McCall9bca9232010-09-02 10:25:57 +00001184 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001185 QualType SizeTy = Ctx.getSizeType();
1186 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1187
1188 // The size of the cookie.
1189 CharUnits CookieSize =
1190 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001191 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001192
1193 // Compute an offset to the cookie.
1194 llvm::Value *CookiePtr = NewPtr;
1195 CharUnits CookieOffset = CookieSize - SizeSize;
1196 if (!CookieOffset.isZero())
1197 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1198 CookieOffset.getQuantity());
1199
1200 // Write the number of elements into the appropriate slot.
1201 llvm::Value *NumElementsPtr
1202 = CGF.Builder.CreateBitCast(CookiePtr,
1203 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1204 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1205
1206 // Finally, compute a pointer to the actual data buffer by skipping
1207 // over the cookie completely.
1208 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1209 CookieSize.getQuantity());
1210}
1211
John McCallb91cd662012-05-01 05:23:51 +00001212llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1213 llvm::Value *allocPtr,
1214 CharUnits cookieSize) {
1215 // The element size is right-justified in the cookie.
1216 llvm::Value *numElementsPtr = allocPtr;
1217 CharUnits numElementsOffset =
1218 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1219 if (!numElementsOffset.isZero())
1220 numElementsPtr =
1221 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1222 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001223
Micah Villmowea2fea22012-10-25 15:39:14 +00001224 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001225 numElementsPtr =
1226 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1227 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001228}
1229
John McCallb91cd662012-05-01 05:23:51 +00001230CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001231 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001232 // struct array_cookie {
1233 // std::size_t element_size; // element_size != 0
1234 // std::size_t element_count;
1235 // };
John McCallc19c7062013-01-25 23:36:19 +00001236 // But the base ABI doesn't give anything an alignment greater than
1237 // 8, so we can dismiss this as typical ABI-author blindness to
1238 // actual language complexity and round up to the element alignment.
1239 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1240 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001241}
1242
1243llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001244 llvm::Value *newPtr,
1245 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001246 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001247 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001248 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001249
John McCallc19c7062013-01-25 23:36:19 +00001250 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1251 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001252
1253 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001254 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001255
1256 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001257 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1258 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1259 getContext().getTypeSizeInChars(elementType).getQuantity());
1260 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001261
1262 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001263 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1264 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001265
1266 // Finally, compute a pointer to the actual data buffer by skipping
1267 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001268 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1269 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1270 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001271}
1272
John McCallb91cd662012-05-01 05:23:51 +00001273llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1274 llvm::Value *allocPtr,
1275 CharUnits cookieSize) {
1276 // The number of elements is at offset sizeof(size_t) relative to
1277 // the allocated pointer.
1278 llvm::Value *numElementsPtr
1279 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001280
Micah Villmowea2fea22012-10-25 15:39:14 +00001281 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001282 numElementsPtr =
1283 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1284 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001285}
1286
John McCall68ff0372010-09-08 01:44:27 +00001287/*********************** Static local initialization **************************/
1288
1289static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001290 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001291 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001292 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001293 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001294 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001295 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001296 llvm::AttributeSet::get(CGM.getLLVMContext(),
1297 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001298 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001299}
1300
1301static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001302 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001303 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001304 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001305 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001306 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001307 llvm::AttributeSet::get(CGM.getLLVMContext(),
1308 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001309 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001310}
1311
1312static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001313 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001314 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001315 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001316 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001317 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001318 llvm::AttributeSet::get(CGM.getLLVMContext(),
1319 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001320 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001321}
1322
1323namespace {
1324 struct CallGuardAbort : EHScopeStack::Cleanup {
1325 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001326 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001327
Craig Topper4f12f102014-03-12 06:41:41 +00001328 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001329 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1330 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001331 }
1332 };
1333}
1334
1335/// The ARM code here follows the Itanium code closely enough that we
1336/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001337void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1338 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001339 llvm::GlobalVariable *var,
1340 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001341 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001342
Richard Smithdbf74ba2013-04-14 23:01:42 +00001343 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001344 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001345 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1346 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001347
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001348 // If we have a global variable with internal linkage and thread-safe statics
1349 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001350 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1351
1352 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001353 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001354 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001355 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001356 // Guard variables are 64 bits in the generic ABI and size width on ARM
1357 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001358 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001359 }
John McCallb88a5662012-03-30 21:00:39 +00001360 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001361
John McCallb88a5662012-03-30 21:00:39 +00001362 // Create the guard variable if we don't already have it (as we
1363 // might if we're double-emitting this function body).
1364 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1365 if (!guard) {
1366 // Mangle the name for the guard.
1367 SmallString<256> guardName;
1368 {
1369 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001370 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001371 out.flush();
1372 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001373
John McCallb88a5662012-03-30 21:00:39 +00001374 // Create the guard variable with a zero-initializer.
1375 // Just absorb linkage and visibility from the guarded variable.
1376 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1377 false, var->getLinkage(),
1378 llvm::ConstantInt::get(guardTy, 0),
1379 guardName.str());
1380 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001381 // If the variable is thread-local, so is its guard variable.
1382 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001383
1384 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1385 }
John McCall87590e62012-03-30 07:09:50 +00001386
John McCall68ff0372010-09-08 01:44:27 +00001387 // Test whether the variable has completed initialization.
John McCallb88a5662012-03-30 21:00:39 +00001388 llvm::Value *isInitialized;
John McCall68ff0372010-09-08 01:44:27 +00001389
1390 // ARM C++ ABI 3.2.3.1:
1391 // To support the potential use of initialization guard variables
1392 // as semaphores that are the target of ARM SWP and LDREX/STREX
1393 // synchronizing instructions we define a static initialization
1394 // guard variable to be a 4-byte aligned, 4- byte word with the
1395 // following inline access protocol.
1396 // #define INITIALIZED 1
1397 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1398 // if (__cxa_guard_acquire(&obj_guard))
1399 // ...
1400 // }
Mark Seabornedf0d382013-07-24 16:25:13 +00001401 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001402 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northover9bb857a2013-01-31 12:13:10 +00001403 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1404 V = Builder.CreateAnd(V, Test1);
John McCallb88a5662012-03-30 21:00:39 +00001405 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001406
1407 // Itanium C++ ABI 3.3.2:
1408 // The following is pseudo-code showing how these functions can be used:
1409 // if (obj_guard.first_byte == 0) {
1410 // if ( __cxa_guard_acquire (&obj_guard) ) {
1411 // try {
1412 // ... initialize the object ...;
1413 // } catch (...) {
1414 // __cxa_guard_abort (&obj_guard);
1415 // throw;
1416 // }
1417 // ... queue object destructor with __cxa_atexit() ...;
1418 // __cxa_guard_release (&obj_guard);
1419 // }
1420 // }
1421 } else {
1422 // Load the first byte of the guard variable.
Chandler Carruth84537952012-03-30 19:44:53 +00001423 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001424 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth84537952012-03-30 19:44:53 +00001425 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001426
Eli Friedman84d28122011-09-13 22:21:56 +00001427 // Itanium ABI:
1428 // An implementation supporting thread-safety on multiprocessor
1429 // systems must also guarantee that references to the initialized
1430 // object do not occur before the load of the initialization flag.
1431 //
1432 // In LLVM, we do this by marking the load Acquire.
1433 if (threadsafe)
Chandler Carruth84537952012-03-30 19:44:53 +00001434 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001435
John McCallb88a5662012-03-30 21:00:39 +00001436 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001437 }
1438
1439 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1440 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1441
1442 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001443 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001444
1445 CGF.EmitBlock(InitCheckBlock);
1446
1447 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001448 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001449 // Call __cxa_guard_acquire.
1450 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001451 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001452
1453 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1454
1455 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1456 InitBlock, EndBlock);
1457
1458 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001459 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001460
1461 CGF.EmitBlock(InitBlock);
1462 }
1463
1464 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001465 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001466
John McCall5aa52592011-06-17 07:33:57 +00001467 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001468 // Pop the guard-abort cleanup if we pushed one.
1469 CGF.PopCleanupBlock();
1470
1471 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001472 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001473 } else {
John McCallb88a5662012-03-30 21:00:39 +00001474 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001475 }
1476
1477 CGF.EmitBlock(EndBlock);
1478}
John McCallc84ed6a2012-05-01 06:13:13 +00001479
1480/// Register a global destructor using __cxa_atexit.
1481static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1482 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001483 llvm::Constant *addr,
1484 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001485 const char *Name = "__cxa_atexit";
1486 if (TLS) {
1487 const llvm::Triple &T = CGF.getTarget().getTriple();
1488 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1489 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001490
John McCallc84ed6a2012-05-01 06:13:13 +00001491 // We're assuming that the destructor function is something we can
1492 // reasonably call with the default CC. Go ahead and cast it to the
1493 // right prototype.
1494 llvm::Type *dtorTy =
1495 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1496
1497 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1498 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1499 llvm::FunctionType *atexitTy =
1500 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1501
1502 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001503 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001504 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1505 fn->setDoesNotThrow();
1506
1507 // Create a variable that binds the atexit to this shared object.
1508 llvm::Constant *handle =
1509 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1510
1511 llvm::Value *args[] = {
1512 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1513 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1514 handle
1515 };
John McCall882987f2013-02-28 19:01:20 +00001516 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001517}
1518
1519/// Register a global destructor as best as we know how.
1520void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001521 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001522 llvm::Constant *dtor,
1523 llvm::Constant *addr) {
1524 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001525 if (CGM.getCodeGenOpts().CXAAtExit)
1526 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1527
1528 if (D.getTLSKind())
1529 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001530
1531 // In Apple kexts, we want to add a global destructor entry.
1532 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001533 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001534 // Generate a global destructor entry.
1535 return CGM.AddCXXDtorEntry(dtor, addr);
1536 }
1537
David Blaikieebe87e12013-08-27 23:57:18 +00001538 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001539}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001540
1541/// Get the appropriate linkage for the wrapper function. This is essentially
1542/// the weak form of the variable's linkage; every translation unit which wneeds
1543/// the wrapper emits a copy, and we want the linker to merge them.
1544static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1545 llvm::GlobalValue::LinkageTypes VarLinkage) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001546 // For internal linkage variables, we don't need an external or weak wrapper.
1547 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1548 return VarLinkage;
1549 return llvm::GlobalValue::WeakODRLinkage;
1550}
1551
1552llvm::Function *
1553ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1554 llvm::GlobalVariable *Var) {
1555 // Mangle the name for the thread_local wrapper function.
1556 SmallString<256> WrapperName;
1557 {
1558 llvm::raw_svector_ostream Out(WrapperName);
1559 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1560 Out.flush();
1561 }
1562
1563 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1564 return cast<llvm::Function>(V);
1565
1566 llvm::Type *RetTy = Var->getType();
1567 if (VD->getType()->isReferenceType())
1568 RetTy = RetTy->getPointerElementType();
1569
1570 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1571 llvm::Function *Wrapper = llvm::Function::Create(
1572 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1573 &CGM.getModule());
1574 // Always resolve references to the wrapper at link time.
1575 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1576 return Wrapper;
1577}
1578
1579void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1580 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1581 llvm::Function *InitFunc) {
1582 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1583 const VarDecl *VD = Decls[I].first;
1584 llvm::GlobalVariable *Var = Decls[I].second;
1585
1586 // Mangle the name for the thread_local initialization function.
1587 SmallString<256> InitFnName;
1588 {
1589 llvm::raw_svector_ostream Out(InitFnName);
1590 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1591 Out.flush();
1592 }
1593
1594 // If we have a definition for the variable, emit the initialization
1595 // function as an alias to the global Init function (if any). Otherwise,
1596 // produce a declaration of the initialization function.
1597 llvm::GlobalValue *Init = 0;
1598 bool InitIsInitFunc = false;
1599 if (VD->hasDefinition()) {
1600 InitIsInitFunc = true;
1601 if (InitFunc)
1602 Init =
1603 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1604 InitFnName.str(), InitFunc, &CGM.getModule());
1605 } else {
1606 // Emit a weak global function referring to the initialization function.
1607 // This function will not exist if the TU defining the thread_local
1608 // variable in question does not need any dynamic initialization for
1609 // its thread_local variables.
1610 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1611 Init = llvm::Function::Create(
1612 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1613 &CGM.getModule());
1614 }
1615
1616 if (Init)
1617 Init->setVisibility(Var->getVisibility());
1618
1619 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1620 llvm::LLVMContext &Context = CGM.getModule().getContext();
1621 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1622 CGBuilderTy Builder(Entry);
1623 if (InitIsInitFunc) {
1624 if (Init)
1625 Builder.CreateCall(Init);
1626 } else {
1627 // Don't know whether we have an init function. Call it if it exists.
1628 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1629 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1630 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1631 Builder.CreateCondBr(Have, InitBB, ExitBB);
1632
1633 Builder.SetInsertPoint(InitBB);
1634 Builder.CreateCall(Init);
1635 Builder.CreateBr(ExitBB);
1636
1637 Builder.SetInsertPoint(ExitBB);
1638 }
1639
1640 // For a reference, the result of the wrapper function is a pointer to
1641 // the referenced object.
1642 llvm::Value *Val = Var;
1643 if (VD->getType()->isReferenceType()) {
1644 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1645 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1646 Val = LI;
1647 }
1648
1649 Builder.CreateRet(Val);
1650 }
1651}
1652
1653LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1654 const DeclRefExpr *DRE) {
1655 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1656 QualType T = VD->getType();
1657 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1658 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1659 llvm::Function *Wrapper =
1660 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1661
1662 Val = CGF.Builder.CreateCall(Wrapper);
1663
1664 LValue LV;
1665 if (VD->getType()->isReferenceType())
1666 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1667 else
1668 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1669 CGF.getContext().getDeclAlign(VD));
1670 // FIXME: need setObjCGCLValueClass?
1671 return LV;
1672}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001673
1674/// Return whether the given global decl needs a VTT parameter, which it does
1675/// if it's a base constructor or destructor with virtual bases.
1676bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1677 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1678
1679 // We don't have any virtual bases, just return early.
1680 if (!MD->getParent()->getNumVBases())
1681 return false;
1682
1683 // Check if we have a base constructor.
1684 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1685 return true;
1686
1687 // Check if we have a base destructor.
1688 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1689 return true;
1690
1691 return false;
1692}