blob: 86eb36d86536946cc71ef7433148102fab5272f8 [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
Reid Kleckner40ca9132014-05-13 22:05:45 +000055 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000056
Craig Topper4f12f102014-03-12 06:41:41 +000057 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000058 // Structures with either a non-trivial destructor or a non-trivial
59 // copy constructor are always indirect.
60 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
61 // special members.
62 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000063 return RAA_Indirect;
64 return RAA_Default;
65 }
66
Craig Topper4f12f102014-03-12 06:41:41 +000067 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000068
Craig Topper4f12f102014-03-12 06:41:41 +000069 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +000070
Craig Topper4f12f102014-03-12 06:41:41 +000071 llvm::Value *
72 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
73 const Expr *E,
74 llvm::Value *&This,
75 llvm::Value *MemFnPtr,
76 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +000077
Craig Topper4f12f102014-03-12 06:41:41 +000078 llvm::Value *
79 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
80 llvm::Value *Base,
81 llvm::Value *MemPtr,
82 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +000083
John McCall7a9aac22010-08-23 01:21:21 +000084 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
85 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000086 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +000087 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000088 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +000089
Craig Topper4f12f102014-03-12 06:41:41 +000090 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000091
Craig Topper4f12f102014-03-12 06:41:41 +000092 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000093 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000094 CharUnits offset) override;
95 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +000096 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
97 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +000098
John McCall7a9aac22010-08-23 01:21:21 +000099 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000100 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000101 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000102 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000103
John McCall7a9aac22010-08-23 01:21:21 +0000104 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000105 llvm::Value *Addr,
106 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000107
Craig Topper4f12f102014-03-12 06:41:41 +0000108 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr,
109 QualType type) override;
John McCall82fb8922012-09-25 10:10:39 +0000110
Craig Topper4f12f102014-03-12 06:41:41 +0000111 llvm::Value *
112 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
113 const CXXRecordDecl *ClassDecl,
114 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000115
John McCall5d865c322010-08-31 07:33:07 +0000116 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
Craig Topper4f12f102014-03-12 06:41:41 +0000117 CXXCtorType T, CanQualType &ResTy,
118 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000119
Craig Topper4f12f102014-03-12 06:41:41 +0000120 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000121
John McCall5d865c322010-08-31 07:33:07 +0000122 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000123 CXXDtorType T, CanQualType &ResTy,
124 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000125
Reid Klecknere7de47e2013-07-22 13:51:44 +0000126 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000127 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000128 // Itanium does not emit any destructor variant as an inline thunk.
129 // Delegating may occur as an optimization, but all variants are either
130 // emitted with external linkage or as linkonce if they are inline and used.
131 return false;
132 }
133
Craig Topper4f12f102014-03-12 06:41:41 +0000134 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000135
Reid Kleckner89077a12013-12-17 19:46:40 +0000136 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000137 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000138
Craig Topper4f12f102014-03-12 06:41:41 +0000139 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000140
Reid Kleckner89077a12013-12-17 19:46:40 +0000141 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
142 const CXXConstructorDecl *D,
143 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000144 bool Delegating,
145 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000146
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000147 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
148 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000149 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000150
Craig Topper4f12f102014-03-12 06:41:41 +0000151 void emitVTableDefinitions(CodeGenVTables &CGVT,
152 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000153
154 llvm::Value *getVTableAddressPointInStructor(
155 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
156 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000157 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000158
159 llvm::Constant *
160 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000161 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000162
163 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000164 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000165
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000166 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000167 llvm::Value *This,
168 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000169
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000170 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
171 const CXXDestructorDecl *Dtor,
172 CXXDtorType DtorType, SourceLocation CallLoc,
Craig Topper4f12f102014-03-12 06:41:41 +0000173 llvm::Value *This) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000174
Craig Topper4f12f102014-03-12 06:41:41 +0000175 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000176
Hans Wennborgc94391d2014-06-06 20:04:01 +0000177 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
178 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000179 // Allow inlining of thunks by emitting them with available_externally
180 // linkage together with vtables when needed.
181 if (ForVTable)
182 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
183 }
184
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000185 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000186 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000187
188 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000189 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000190
Craig Topper4f12f102014-03-12 06:41:41 +0000191 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
192 StringRef GetDeletedVirtualCallName() override
193 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000194
Craig Topper4f12f102014-03-12 06:41:41 +0000195 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000196 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
197 llvm::Value *NewPtr,
198 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000199 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000200 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000201 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
202 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000203 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000204
John McCallcdf7ef52010-11-06 09:44:32 +0000205 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000206 llvm::GlobalVariable *DeclPtr,
207 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000208 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000209 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000210
211 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
212 llvm::GlobalVariable *Var);
213 void EmitThreadLocalInitFuncs(
214 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Craig Topper4f12f102014-03-12 06:41:41 +0000215 llvm::Function *InitFunc) override;
Richard Smith0f383742014-03-26 22:48:22 +0000216 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
217 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000218
Craig Topper4f12f102014-03-12 06:41:41 +0000219 bool NeedsVTTParameter(GlobalDecl GD) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000220};
John McCall86353412010-08-21 22:46:04 +0000221
222class ARMCXXABI : public ItaniumCXXABI {
223public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000224 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
225 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
226 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000227
Craig Topper4f12f102014-03-12 06:41:41 +0000228 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000229 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
230 isa<CXXDestructorDecl>(GD.getDecl()) &&
231 GD.getDtorType() != Dtor_Deleting));
232 }
John McCall5d865c322010-08-31 07:33:07 +0000233
Craig Topper4f12f102014-03-12 06:41:41 +0000234 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
235 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000236
Craig Topper4f12f102014-03-12 06:41:41 +0000237 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000238 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
239 llvm::Value *NewPtr,
240 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000241 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000242 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000243 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000244 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000245};
Tim Northovera2ee4332014-03-29 15:09:45 +0000246
247class iOS64CXXABI : public ARMCXXABI {
248public:
249 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000250
251 // ARM64 libraries are prepared for non-unique RTTI.
252 bool shouldRTTIBeUnique() override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000253};
Charles Davis4e786dd2010-05-25 19:52:27 +0000254}
255
Charles Davis53c59df2010-08-16 03:33:14 +0000256CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000257 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000258 // For IR-generation purposes, there's no significant difference
259 // between the ARM and iOS ABIs.
260 case TargetCXXABI::GenericARM:
261 case TargetCXXABI::iOS:
262 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000263
Tim Northovera2ee4332014-03-29 15:09:45 +0000264 case TargetCXXABI::iOS64:
265 return new iOS64CXXABI(CGM);
266
Tim Northover9bb857a2013-01-31 12:13:10 +0000267 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
268 // include the other 32-bit ARM oddities: constructor/destructor return values
269 // and array cookies.
270 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000271 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
272 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000273
John McCall57625922013-01-25 23:36:14 +0000274 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000275 if (CGM.getContext().getTargetInfo().getTriple().getArch()
276 == llvm::Triple::le32) {
277 // For PNaCl, use ARM-style method pointers so that PNaCl code
278 // does not assume anything about the alignment of function
279 // pointers.
280 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
281 /* UseARMGuardVarABI = */ false);
282 }
John McCall57625922013-01-25 23:36:14 +0000283 return new ItaniumCXXABI(CGM);
284
285 case TargetCXXABI::Microsoft:
286 llvm_unreachable("Microsoft ABI is not Itanium-based");
287 }
288 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000289}
290
Chris Lattnera5f58b02011-07-09 17:41:47 +0000291llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000292ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
293 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000294 return CGM.PtrDiffTy;
295 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000296}
297
John McCalld9c6c0b2010-08-22 00:59:17 +0000298/// In the Itanium and ARM ABIs, method pointers have the form:
299/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
300///
301/// In the Itanium ABI:
302/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
303/// - the this-adjustment is (memptr.adj)
304/// - the virtual offset is (memptr.ptr - 1)
305///
306/// In the ARM ABI:
307/// - method pointers are virtual if (memptr.adj & 1) is nonzero
308/// - the this-adjustment is (memptr.adj >> 1)
309/// - the virtual offset is (memptr.ptr)
310/// ARM uses 'adj' for the virtual flag because Thumb functions
311/// may be only single-byte aligned.
312///
313/// If the member is virtual, the adjusted 'this' pointer points
314/// to a vtable pointer from which the virtual offset is applied.
315///
316/// If the member is non-virtual, memptr.ptr is the address of
317/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000318llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
319 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
320 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000321 CGBuilderTy &Builder = CGF.Builder;
322
323 const FunctionProtoType *FPT =
324 MPT->getPointeeType()->getAs<FunctionProtoType>();
325 const CXXRecordDecl *RD =
326 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
327
Chris Lattner2192fe52011-07-18 04:24:23 +0000328 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000329 CGM.getTypes().GetFunctionType(
330 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000331
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000332 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000333
John McCalld9c6c0b2010-08-22 00:59:17 +0000334 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
335 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
336 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
337
John McCalla1dee5302010-08-22 10:59:02 +0000338 // Extract memptr.adj, which is in the second field.
339 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000340
341 // Compute the true adjustment.
342 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000343 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000344 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000345
346 // Apply the adjustment and cast back to the original struct type
347 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000348 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
349 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
350 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000351
352 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000353 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000354
355 // If the LSB in the function pointer is 1, the function pointer points to
356 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000357 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000358 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000359 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
360 else
361 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
362 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000363 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
364
365 // In the virtual path, the adjustment left 'This' pointing to the
366 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000367 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000368 CGF.EmitBlock(FnVirtual);
369
370 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000371 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000372 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000373
374 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000375 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000376 if (!UseARMMethodPtrABI)
377 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000378 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000379
380 // Load the virtual function to call.
381 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000382 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000383 CGF.EmitBranch(FnEnd);
384
385 // In the non-virtual path, the function pointer is actually a
386 // function pointer.
387 CGF.EmitBlock(FnNonVirtual);
388 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000389 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000390
391 // We're done.
392 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000393 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000394 Callee->addIncoming(VirtualFn, FnVirtual);
395 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
396 return Callee;
397}
John McCalla8bbb822010-08-22 03:04:22 +0000398
John McCallc134eb52010-08-31 21:07:20 +0000399/// Compute an l-value by applying the given pointer-to-member to a
400/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000401llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
402 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
403 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000404 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000405
406 CGBuilderTy &Builder = CGF.Builder;
407
Micah Villmowea2fea22012-10-25 15:39:14 +0000408 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000409
410 // Cast to char*.
411 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
412
413 // Apply the offset, which we assume is non-null.
414 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
415
416 // Cast the address to the appropriate pointer type, adopting the
417 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000418 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000419 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000420 return Builder.CreateBitCast(Addr, PType);
421}
422
John McCallc62bb392012-02-15 01:22:51 +0000423/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
424/// conversion.
425///
426/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000427///
428/// Obligatory offset/adjustment diagram:
429/// <-- offset --> <-- adjustment -->
430/// |--------------------------|----------------------|--------------------|
431/// ^Derived address point ^Base address point ^Member address point
432///
433/// So when converting a base member pointer to a derived member pointer,
434/// we add the offset to the adjustment because the address point has
435/// decreased; and conversely, when converting a derived MP to a base MP
436/// we subtract the offset from the adjustment because the address point
437/// has increased.
438///
439/// The standard forbids (at compile time) conversion to and from
440/// virtual bases, which is why we don't have to consider them here.
441///
442/// The standard forbids (at run time) casting a derived MP to a base
443/// MP when the derived MP does not point to a member of the base.
444/// This is why -1 is a reasonable choice for null data member
445/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000446llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000447ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
448 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000449 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000450 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000451 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
452 E->getCastKind() == CK_ReinterpretMemberPointer);
453
454 // Under Itanium, reinterprets don't require any additional processing.
455 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
456
457 // Use constant emission if we can.
458 if (isa<llvm::Constant>(src))
459 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
460
461 llvm::Constant *adj = getMemberPointerAdjustment(E);
462 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000463
464 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000465 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000466
John McCallc62bb392012-02-15 01:22:51 +0000467 const MemberPointerType *destTy =
468 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000469
John McCall7a9aac22010-08-23 01:21:21 +0000470 // For member data pointers, this is just a matter of adding the
471 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000472 if (destTy->isMemberDataPointer()) {
473 llvm::Value *dst;
474 if (isDerivedToBase)
475 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000476 else
John McCallc62bb392012-02-15 01:22:51 +0000477 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000478
479 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000480 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
481 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
482 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000483 }
484
John McCalla1dee5302010-08-22 10:59:02 +0000485 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000486 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000487 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
488 offset <<= 1;
489 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000490 }
491
John McCallc62bb392012-02-15 01:22:51 +0000492 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
493 llvm::Value *dstAdj;
494 if (isDerivedToBase)
495 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000496 else
John McCallc62bb392012-02-15 01:22:51 +0000497 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000498
John McCallc62bb392012-02-15 01:22:51 +0000499 return Builder.CreateInsertValue(src, dstAdj, 1);
500}
501
502llvm::Constant *
503ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
504 llvm::Constant *src) {
505 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
506 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
507 E->getCastKind() == CK_ReinterpretMemberPointer);
508
509 // Under Itanium, reinterprets don't require any additional processing.
510 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
511
512 // If the adjustment is trivial, we don't need to do anything.
513 llvm::Constant *adj = getMemberPointerAdjustment(E);
514 if (!adj) return src;
515
516 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
517
518 const MemberPointerType *destTy =
519 E->getType()->castAs<MemberPointerType>();
520
521 // For member data pointers, this is just a matter of adding the
522 // offset if the source is non-null.
523 if (destTy->isMemberDataPointer()) {
524 // null maps to null.
525 if (src->isAllOnesValue()) return src;
526
527 if (isDerivedToBase)
528 return llvm::ConstantExpr::getNSWSub(src, adj);
529 else
530 return llvm::ConstantExpr::getNSWAdd(src, adj);
531 }
532
533 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000534 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000535 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
536 offset <<= 1;
537 adj = llvm::ConstantInt::get(adj->getType(), offset);
538 }
539
540 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
541 llvm::Constant *dstAdj;
542 if (isDerivedToBase)
543 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
544 else
545 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
546
547 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000548}
John McCall84fa5102010-08-22 04:16:24 +0000549
550llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000551ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000552 // Itanium C++ ABI 2.3:
553 // A NULL pointer is represented as -1.
554 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000555 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000556
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000557 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000558 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000559 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000560}
561
John McCallf3a88602011-02-03 08:15:49 +0000562llvm::Constant *
563ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
564 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000565 // Itanium C++ ABI 2.3:
566 // A pointer to data member is an offset from the base address of
567 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000568 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000569}
570
John McCall2979fe02011-04-12 00:42:48 +0000571llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000572 return BuildMemberPointer(MD, CharUnits::Zero());
573}
574
575llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
576 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000577 assert(MD->isInstance() && "Member function must not be static!");
578 MD = MD->getCanonicalDecl();
579
580 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000581
582 // Get the function pointer (or index if this is a virtual function).
583 llvm::Constant *MemPtr[2];
584 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000585 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000586
Ken Dyckdf016282011-04-09 01:30:02 +0000587 const ASTContext &Context = getContext();
588 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000589 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000590 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000591
Mark Seabornedf0d382013-07-24 16:25:13 +0000592 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000593 // ARM C++ ABI 3.2.1:
594 // This ABI specifies that adj contains twice the this
595 // adjustment, plus 1 if the member function is virtual. The
596 // least significant bit of adj then makes exactly the same
597 // discrimination as the least significant bit of ptr does for
598 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000599 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
600 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000601 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000602 } else {
603 // Itanium C++ ABI 2.3:
604 // For a virtual function, [the pointer field] is 1 plus the
605 // virtual table offset (in bytes) of the function,
606 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000607 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
608 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000609 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000610 }
611 } else {
John McCall2979fe02011-04-12 00:42:48 +0000612 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000613 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000614 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000615 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000616 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000617 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000618 } else {
John McCall2979fe02011-04-12 00:42:48 +0000619 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
620 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000621 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000622 }
John McCall2979fe02011-04-12 00:42:48 +0000623 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000624
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000625 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000626 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
627 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000628 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000629 }
John McCall1c456c82010-08-22 06:43:33 +0000630
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000631 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000632}
633
Richard Smithdafff942012-01-14 04:30:29 +0000634llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
635 QualType MPType) {
636 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
637 const ValueDecl *MPD = MP.getMemberPointerDecl();
638 if (!MPD)
639 return EmitNullMemberPointer(MPT);
640
Reid Kleckner452abac2013-05-09 21:01:17 +0000641 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000642
643 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
644 return BuildMemberPointer(MD, ThisAdjustment);
645
646 CharUnits FieldOffset =
647 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
648 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
649}
650
John McCall131d97d2010-08-22 08:30:07 +0000651/// The comparison algorithm is pretty easy: the member pointers are
652/// the same if they're either bitwise identical *or* both null.
653///
654/// ARM is different here only because null-ness is more complicated.
655llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000656ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
657 llvm::Value *L,
658 llvm::Value *R,
659 const MemberPointerType *MPT,
660 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000661 CGBuilderTy &Builder = CGF.Builder;
662
John McCall131d97d2010-08-22 08:30:07 +0000663 llvm::ICmpInst::Predicate Eq;
664 llvm::Instruction::BinaryOps And, Or;
665 if (Inequality) {
666 Eq = llvm::ICmpInst::ICMP_NE;
667 And = llvm::Instruction::Or;
668 Or = llvm::Instruction::And;
669 } else {
670 Eq = llvm::ICmpInst::ICMP_EQ;
671 And = llvm::Instruction::And;
672 Or = llvm::Instruction::Or;
673 }
674
John McCall7a9aac22010-08-23 01:21:21 +0000675 // Member data pointers are easy because there's a unique null
676 // value, so it just comes down to bitwise equality.
677 if (MPT->isMemberDataPointer())
678 return Builder.CreateICmp(Eq, L, R);
679
680 // For member function pointers, the tautologies are more complex.
681 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000682 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000683 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000684 // (L == R) <==> (L.ptr == R.ptr &&
685 // (L.adj == R.adj ||
686 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000687 // The inequality tautologies have exactly the same structure, except
688 // applying De Morgan's laws.
689
690 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
691 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
692
John McCall131d97d2010-08-22 08:30:07 +0000693 // This condition tests whether L.ptr == R.ptr. This must always be
694 // true for equality to hold.
695 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
696
697 // This condition, together with the assumption that L.ptr == R.ptr,
698 // tests whether the pointers are both null. ARM imposes an extra
699 // condition.
700 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
701 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
702
703 // This condition tests whether L.adj == R.adj. If this isn't
704 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000705 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
706 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000707 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
708
709 // Null member function pointers on ARM clear the low bit of Adj,
710 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000711 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000712 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
713
714 // Compute (l.adj | r.adj) & 1 and test it against zero.
715 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
716 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
717 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
718 "cmp.or.adj");
719 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
720 }
721
722 // Tie together all our conditions.
723 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
724 Result = Builder.CreateBinOp(And, PtrEq, Result,
725 Inequality ? "memptr.ne" : "memptr.eq");
726 return Result;
727}
728
729llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000730ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
731 llvm::Value *MemPtr,
732 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000733 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000734
735 /// For member data pointers, this is just a check against -1.
736 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000737 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000738 llvm::Value *NegativeOne =
739 llvm::Constant::getAllOnesValue(MemPtr->getType());
740 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
741 }
John McCall131d97d2010-08-22 08:30:07 +0000742
Daniel Dunbar914bc412011-04-19 23:10:47 +0000743 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000744 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000745
746 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
747 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
748
Daniel Dunbar914bc412011-04-19 23:10:47 +0000749 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
750 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000751 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000752 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000753 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000754 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000755 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
756 "memptr.isvirtual");
757 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000758 }
759
760 return Result;
761}
John McCall1c456c82010-08-22 06:43:33 +0000762
Reid Kleckner40ca9132014-05-13 22:05:45 +0000763bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
764 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
765 if (!RD)
766 return false;
767
Reid Klecknerd355ca72014-05-15 01:26:32 +0000768 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
769 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
770 // special members.
771 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000772 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
773 return true;
774 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000775 return false;
776}
777
John McCall614dbdc2010-08-22 21:01:12 +0000778/// The Itanium ABI requires non-zero initialization only for data
779/// member pointers, for which '0' is a valid offset.
780bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
781 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000782}
John McCall5d865c322010-08-31 07:33:07 +0000783
John McCall82fb8922012-09-25 10:10:39 +0000784/// The Itanium ABI always places an offset to the complete object
785/// at entry -2 in the vtable.
786llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
787 llvm::Value *ptr,
788 QualType type) {
789 // Grab the vtable pointer as an intptr_t*.
790 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
791
792 // Track back to entry -2 and pull out the offset there.
793 llvm::Value *offsetPtr =
794 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
795 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
796 offset->setAlignment(CGF.PointerAlignInBytes);
797
798 // Apply the offset.
799 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
800 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
801}
802
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000803llvm::Value *
804ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
805 llvm::Value *This,
806 const CXXRecordDecl *ClassDecl,
807 const CXXRecordDecl *BaseClassDecl) {
808 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
809 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000810 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
811 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000812
813 llvm::Value *VBaseOffsetPtr =
814 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
815 "vbase.offset.ptr");
816 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
817 CGM.PtrDiffTy->getPointerTo());
818
819 llvm::Value *VBaseOffset =
820 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
821
822 return VBaseOffset;
823}
824
John McCall5d865c322010-08-31 07:33:07 +0000825/// The generic ABI passes 'this', plus a VTT if it's initializing a
826/// base subobject.
Reid Kleckner89077a12013-12-17 19:46:40 +0000827void
828ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
829 CXXCtorType Type, CanQualType &ResTy,
830 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000831 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000832
Reid Kleckner89077a12013-12-17 19:46:40 +0000833 // All parameters are already in place except VTT, which goes after 'this'.
834 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +0000835
836 // Check if we need to add a VTT parameter (which has type void **).
837 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
Reid Kleckner89077a12013-12-17 19:46:40 +0000838 ArgTys.insert(ArgTys.begin() + 1,
839 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +0000840}
841
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000842void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
843 // Just make sure we're in sync with TargetCXXABI.
844 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
845
Rafael Espindolac3cde362013-12-09 14:51:17 +0000846 // The constructor used for constructing this as a base class;
847 // ignores virtual bases.
848 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
849
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000850 // The constructor used for constructing this as a complete class;
851 // constucts the virtual bases, then calls the base constructor.
852 if (!D->getParent()->isAbstract()) {
853 // We don't need to emit the complete ctor if the class is abstract.
854 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
855 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000856}
857
John McCall5d865c322010-08-31 07:33:07 +0000858/// The generic ABI passes 'this', plus a VTT if it's destroying a
859/// base subobject.
860void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
861 CXXDtorType Type,
862 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000863 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000864 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000865
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000866 // 'this' parameter is already there, as well as 'this' return if
867 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000868
869 // Check if we need to add a VTT parameter (which has type void **).
870 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
871 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
872}
873
Reid Klecknere7de47e2013-07-22 13:51:44 +0000874void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +0000875 // The destructor used for destructing this as a base class; ignores
876 // virtual bases.
877 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000878
879 // The destructor used for destructing this as a most-derived class;
880 // call the base destructor and then destructs any virtual bases.
881 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
882
Rafael Espindolac3cde362013-12-09 14:51:17 +0000883 // The destructor in a virtual table is always a 'deleting'
884 // destructor, which calls the complete destructor and then uses the
885 // appropriate operator delete.
886 if (D->isVirtual())
887 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000888}
889
Reid Kleckner89077a12013-12-17 19:46:40 +0000890void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
891 QualType &ResTy,
892 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +0000893 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +0000894 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +0000895
896 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000897 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +0000898 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000899
900 // FIXME: avoid the fake decl
901 QualType T = Context.getPointerType(Context.VoidPtrTy);
902 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +0000903 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +0000904 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +0000905 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +0000906 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +0000907 }
908}
909
John McCall5d865c322010-08-31 07:33:07 +0000910void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
911 /// Initialize the 'this' slot.
912 EmitThisParam(CGF);
913
914 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +0000915 if (getStructorImplicitParamDecl(CGF)) {
916 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
917 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +0000918 }
John McCall5d865c322010-08-31 07:33:07 +0000919
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000920 /// If this is a function that the ABI specifies returns 'this', initialize
921 /// the return slot to 'this' at the start of the function.
922 ///
923 /// Unlike the setting of return types, this is done within the ABI
924 /// implementation instead of by clients of CGCXXABI because:
925 /// 1) getThisValue is currently protected
926 /// 2) in theory, an ABI could implement 'this' returns some other way;
927 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +0000928 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +0000929 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +0000930}
931
Reid Kleckner89077a12013-12-17 19:46:40 +0000932unsigned ItaniumCXXABI::addImplicitConstructorArgs(
933 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
934 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
935 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
936 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000937
Reid Kleckner89077a12013-12-17 19:46:40 +0000938 // Insert the implicit 'vtt' argument as the second argument.
939 llvm::Value *VTT =
940 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
941 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
942 Args.insert(Args.begin() + 1,
943 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
944 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000945}
946
947void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
948 const CXXDestructorDecl *DD,
949 CXXDtorType Type, bool ForVirtualBase,
950 bool Delegating, llvm::Value *This) {
951 GlobalDecl GD(DD, Type);
952 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
953 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
954
Craig Topper8a13c412014-05-21 05:09:00 +0000955 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000956 if (getContext().getLangOpts().AppleKext)
957 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
958
959 if (!Callee)
960 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
961
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000962 // FIXME: Provide a source location here.
963 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Craig Topper8a13c412014-05-21 05:09:00 +0000964 VTT, VTTTy, nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000965}
966
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000967void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
968 const CXXRecordDecl *RD) {
969 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
970 if (VTable->hasInitializer())
971 return;
972
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000973 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000974 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
975 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
976
977 // Create and set the initializer.
978 llvm::Constant *Init = CGVT.CreateVTableInitializer(
979 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
980 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
981 VTable->setInitializer(Init);
982
983 // Set the correct linkage.
984 VTable->setLinkage(Linkage);
985
986 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +0000987 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000988
989 // If this is the magic class __cxxabiv1::__fundamental_type_info,
990 // we will emit the typeinfo for the fundamental types. This is the
991 // same behaviour as GCC.
992 const DeclContext *DC = RD->getDeclContext();
993 if (RD->getIdentifier() &&
994 RD->getIdentifier()->isStr("__fundamental_type_info") &&
995 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
996 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
997 DC->getParent()->isTranslationUnit())
998 CGM.EmitFundamentalRTTIDescriptors();
999}
1000
1001llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1002 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1003 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1004 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1005 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1006
1007 llvm::Value *VTableAddressPoint;
1008 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1009 // Get the secondary vpointer index.
1010 uint64_t VirtualPointerIndex =
1011 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1012
1013 /// Load the VTT.
1014 llvm::Value *VTT = CGF.LoadCXXVTT();
1015 if (VirtualPointerIndex)
1016 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1017
1018 // And load the address point from the VTT.
1019 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1020 } else {
1021 llvm::Constant *VTable =
1022 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001023 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1024 .getVTableLayout(VTableClass)
1025 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001026 VTableAddressPoint =
1027 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1028 }
1029
1030 return VTableAddressPoint;
1031}
1032
1033llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1034 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1035 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1036
1037 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001038 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1039 .getVTableLayout(VTableClass)
1040 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001041 llvm::Value *Indices[] = {
1042 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1043 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1044 };
1045
1046 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1047}
1048
1049llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1050 CharUnits VPtrOffset) {
1051 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1052
1053 llvm::GlobalVariable *&VTable = VTables[RD];
1054 if (VTable)
1055 return VTable;
1056
1057 // Queue up this v-table for possible deferred emission.
1058 CGM.addDeferredVTable(RD);
1059
1060 SmallString<256> OutName;
1061 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001062 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001063 Out.flush();
1064 StringRef Name = OutName.str();
1065
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001066 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001067 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1068 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1069
1070 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1071 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1072 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001073
1074 if (RD->hasAttr<DLLImportAttr>())
1075 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1076 else if (RD->hasAttr<DLLExportAttr>())
1077 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1078
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001079 return VTable;
1080}
1081
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001082llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1083 GlobalDecl GD,
1084 llvm::Value *This,
1085 llvm::Type *Ty) {
1086 GD = GD.getCanonicalDecl();
1087 Ty = Ty->getPointerTo()->getPointerTo();
1088 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1089
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001090 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001091 llvm::Value *VFuncPtr =
1092 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1093 return CGF.Builder.CreateLoad(VFuncPtr);
1094}
1095
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001096void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1097 const CXXDestructorDecl *Dtor,
1098 CXXDtorType DtorType,
1099 SourceLocation CallLoc,
1100 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001101 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1102
1103 const CGFunctionInfo *FInfo
1104 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1105 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001106 llvm::Value *Callee =
1107 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001108
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001109 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Craig Topper8a13c412014-05-21 05:09:00 +00001110 /*ImplicitParam=*/nullptr, QualType(), nullptr,
1111 nullptr);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001112}
1113
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001114void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001115 CodeGenVTables &VTables = CGM.getVTables();
1116 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001117 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001118}
1119
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001120static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1121 llvm::Value *Ptr,
1122 int64_t NonVirtualAdjustment,
1123 int64_t VirtualAdjustment,
1124 bool IsReturnAdjustment) {
1125 if (!NonVirtualAdjustment && !VirtualAdjustment)
1126 return Ptr;
1127
1128 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1129 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1130
1131 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1132 // Perform the non-virtual adjustment for a base-to-derived cast.
1133 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1134 }
1135
1136 if (VirtualAdjustment) {
1137 llvm::Type *PtrDiffTy =
1138 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1139
1140 // Perform the virtual adjustment.
1141 llvm::Value *VTablePtrPtr =
1142 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1143
1144 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1145
1146 llvm::Value *OffsetPtr =
1147 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1148
1149 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1150
1151 // Load the adjustment offset from the vtable.
1152 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1153
1154 // Adjust our pointer.
1155 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1156 }
1157
1158 if (NonVirtualAdjustment && IsReturnAdjustment) {
1159 // Perform the non-virtual adjustment for a derived-to-base cast.
1160 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1161 }
1162
1163 // Cast back to the original type.
1164 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1165}
1166
1167llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1168 llvm::Value *This,
1169 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001170 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1171 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001172 /*IsReturnAdjustment=*/false);
1173}
1174
1175llvm::Value *
1176ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1177 const ReturnAdjustment &RA) {
1178 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1179 RA.Virtual.Itanium.VBaseOffsetOffset,
1180 /*IsReturnAdjustment=*/true);
1181}
1182
John McCall5d865c322010-08-31 07:33:07 +00001183void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1184 RValue RV, QualType ResultType) {
1185 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1186 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1187
1188 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001189 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001190 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1191 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1192 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1193}
John McCall8ed55a52010-09-02 09:58:18 +00001194
1195/************************** Array allocation cookies **************************/
1196
John McCallb91cd662012-05-01 05:23:51 +00001197CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1198 // The array cookie is a size_t; pad that up to the element alignment.
1199 // The cookie is actually right-justified in that space.
1200 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1201 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001202}
1203
1204llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1205 llvm::Value *NewPtr,
1206 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001207 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001208 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001209 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001210
Micah Villmowea2fea22012-10-25 15:39:14 +00001211 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001212
John McCall9bca9232010-09-02 10:25:57 +00001213 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001214 QualType SizeTy = Ctx.getSizeType();
1215 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1216
1217 // The size of the cookie.
1218 CharUnits CookieSize =
1219 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001220 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001221
1222 // Compute an offset to the cookie.
1223 llvm::Value *CookiePtr = NewPtr;
1224 CharUnits CookieOffset = CookieSize - SizeSize;
1225 if (!CookieOffset.isZero())
1226 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1227 CookieOffset.getQuantity());
1228
1229 // Write the number of elements into the appropriate slot.
1230 llvm::Value *NumElementsPtr
1231 = CGF.Builder.CreateBitCast(CookiePtr,
1232 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1233 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1234
1235 // Finally, compute a pointer to the actual data buffer by skipping
1236 // over the cookie completely.
1237 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1238 CookieSize.getQuantity());
1239}
1240
John McCallb91cd662012-05-01 05:23:51 +00001241llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1242 llvm::Value *allocPtr,
1243 CharUnits cookieSize) {
1244 // The element size is right-justified in the cookie.
1245 llvm::Value *numElementsPtr = allocPtr;
1246 CharUnits numElementsOffset =
1247 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1248 if (!numElementsOffset.isZero())
1249 numElementsPtr =
1250 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1251 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001252
Micah Villmowea2fea22012-10-25 15:39:14 +00001253 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001254 numElementsPtr =
1255 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1256 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001257}
1258
John McCallb91cd662012-05-01 05:23:51 +00001259CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001260 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001261 // struct array_cookie {
1262 // std::size_t element_size; // element_size != 0
1263 // std::size_t element_count;
1264 // };
John McCallc19c7062013-01-25 23:36:19 +00001265 // But the base ABI doesn't give anything an alignment greater than
1266 // 8, so we can dismiss this as typical ABI-author blindness to
1267 // actual language complexity and round up to the element alignment.
1268 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1269 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001270}
1271
1272llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001273 llvm::Value *newPtr,
1274 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001275 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001276 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001277 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001278
John McCallc19c7062013-01-25 23:36:19 +00001279 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1280 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001281
1282 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001283 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001284
1285 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001286 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1287 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1288 getContext().getTypeSizeInChars(elementType).getQuantity());
1289 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001290
1291 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001292 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1293 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001294
1295 // Finally, compute a pointer to the actual data buffer by skipping
1296 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001297 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1298 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1299 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001300}
1301
John McCallb91cd662012-05-01 05:23:51 +00001302llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1303 llvm::Value *allocPtr,
1304 CharUnits cookieSize) {
1305 // The number of elements is at offset sizeof(size_t) relative to
1306 // the allocated pointer.
1307 llvm::Value *numElementsPtr
1308 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001309
Micah Villmowea2fea22012-10-25 15:39:14 +00001310 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001311 numElementsPtr =
1312 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1313 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001314}
1315
John McCall68ff0372010-09-08 01:44:27 +00001316/*********************** Static local initialization **************************/
1317
1318static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001319 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001320 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001321 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001322 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001323 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001324 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001325 llvm::AttributeSet::get(CGM.getLLVMContext(),
1326 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001327 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001328}
1329
1330static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001331 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001332 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001333 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001334 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001335 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001336 llvm::AttributeSet::get(CGM.getLLVMContext(),
1337 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001338 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001339}
1340
1341static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001342 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001343 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001344 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001345 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001346 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001347 llvm::AttributeSet::get(CGM.getLLVMContext(),
1348 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001349 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001350}
1351
1352namespace {
1353 struct CallGuardAbort : EHScopeStack::Cleanup {
1354 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001355 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001356
Craig Topper4f12f102014-03-12 06:41:41 +00001357 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001358 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1359 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001360 }
1361 };
1362}
1363
1364/// The ARM code here follows the Itanium code closely enough that we
1365/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001366void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1367 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001368 llvm::GlobalVariable *var,
1369 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001370 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001371
Richard Smithdbf74ba2013-04-14 23:01:42 +00001372 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001373 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001374 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1375 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001376
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001377 // If we have a global variable with internal linkage and thread-safe statics
1378 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001379 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1380
1381 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001382 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001383 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001384 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001385 // Guard variables are 64 bits in the generic ABI and size width on ARM
1386 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001387 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001388 }
John McCallb88a5662012-03-30 21:00:39 +00001389 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001390
John McCallb88a5662012-03-30 21:00:39 +00001391 // Create the guard variable if we don't already have it (as we
1392 // might if we're double-emitting this function body).
1393 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1394 if (!guard) {
1395 // Mangle the name for the guard.
1396 SmallString<256> guardName;
1397 {
1398 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001399 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001400 out.flush();
1401 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001402
John McCallb88a5662012-03-30 21:00:39 +00001403 // Create the guard variable with a zero-initializer.
1404 // Just absorb linkage and visibility from the guarded variable.
1405 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1406 false, var->getLinkage(),
1407 llvm::ConstantInt::get(guardTy, 0),
1408 guardName.str());
1409 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001410 // If the variable is thread-local, so is its guard variable.
1411 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001412
1413 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1414 }
John McCall87590e62012-03-30 07:09:50 +00001415
John McCall68ff0372010-09-08 01:44:27 +00001416 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001417 //
John McCall68ff0372010-09-08 01:44:27 +00001418 // Itanium C++ ABI 3.3.2:
1419 // The following is pseudo-code showing how these functions can be used:
1420 // if (obj_guard.first_byte == 0) {
1421 // if ( __cxa_guard_acquire (&obj_guard) ) {
1422 // try {
1423 // ... initialize the object ...;
1424 // } catch (...) {
1425 // __cxa_guard_abort (&obj_guard);
1426 // throw;
1427 // }
1428 // ... queue object destructor with __cxa_atexit() ...;
1429 // __cxa_guard_release (&obj_guard);
1430 // }
1431 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001432
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001433 // Load the first byte of the guard variable.
1434 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001435 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001436 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001437
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001438 // Itanium ABI:
1439 // An implementation supporting thread-safety on multiprocessor
1440 // systems must also guarantee that references to the initialized
1441 // object do not occur before the load of the initialization flag.
1442 //
1443 // In LLVM, we do this by marking the load Acquire.
1444 if (threadsafe)
1445 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001446
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001447 // For ARM, we should only check the first bit, rather than the entire byte:
1448 //
1449 // ARM C++ ABI 3.2.3.1:
1450 // To support the potential use of initialization guard variables
1451 // as semaphores that are the target of ARM SWP and LDREX/STREX
1452 // synchronizing instructions we define a static initialization
1453 // guard variable to be a 4-byte aligned, 4-byte word with the
1454 // following inline access protocol.
1455 // #define INITIALIZED 1
1456 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1457 // if (__cxa_guard_acquire(&obj_guard))
1458 // ...
1459 // }
1460 //
1461 // and similarly for ARM64:
1462 //
1463 // ARM64 C++ ABI 3.2.2:
1464 // This ABI instead only specifies the value bit 0 of the static guard
1465 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1466 // variable is not initialized and 1 when it is.
1467 llvm::Value *V =
1468 (UseARMGuardVarABI && !useInt8GuardVariable)
1469 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1470 : LI;
1471 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001472
1473 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1474 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1475
1476 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001477 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001478
1479 CGF.EmitBlock(InitCheckBlock);
1480
1481 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001482 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001483 // Call __cxa_guard_acquire.
1484 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001485 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001486
1487 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1488
1489 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1490 InitBlock, EndBlock);
1491
1492 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001493 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001494
1495 CGF.EmitBlock(InitBlock);
1496 }
1497
1498 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001499 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001500
John McCall5aa52592011-06-17 07:33:57 +00001501 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001502 // Pop the guard-abort cleanup if we pushed one.
1503 CGF.PopCleanupBlock();
1504
1505 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001506 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001507 } else {
John McCallb88a5662012-03-30 21:00:39 +00001508 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001509 }
1510
1511 CGF.EmitBlock(EndBlock);
1512}
John McCallc84ed6a2012-05-01 06:13:13 +00001513
1514/// Register a global destructor using __cxa_atexit.
1515static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1516 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001517 llvm::Constant *addr,
1518 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001519 const char *Name = "__cxa_atexit";
1520 if (TLS) {
1521 const llvm::Triple &T = CGF.getTarget().getTriple();
1522 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1523 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001524
John McCallc84ed6a2012-05-01 06:13:13 +00001525 // We're assuming that the destructor function is something we can
1526 // reasonably call with the default CC. Go ahead and cast it to the
1527 // right prototype.
1528 llvm::Type *dtorTy =
1529 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1530
1531 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1532 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1533 llvm::FunctionType *atexitTy =
1534 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1535
1536 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001537 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001538 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1539 fn->setDoesNotThrow();
1540
1541 // Create a variable that binds the atexit to this shared object.
1542 llvm::Constant *handle =
1543 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1544
1545 llvm::Value *args[] = {
1546 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1547 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1548 handle
1549 };
John McCall882987f2013-02-28 19:01:20 +00001550 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001551}
1552
1553/// Register a global destructor as best as we know how.
1554void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001555 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001556 llvm::Constant *dtor,
1557 llvm::Constant *addr) {
1558 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001559 if (CGM.getCodeGenOpts().CXAAtExit)
1560 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1561
1562 if (D.getTLSKind())
1563 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001564
1565 // In Apple kexts, we want to add a global destructor entry.
1566 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001567 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001568 // Generate a global destructor entry.
1569 return CGM.AddCXXDtorEntry(dtor, addr);
1570 }
1571
David Blaikieebe87e12013-08-27 23:57:18 +00001572 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001573}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001574
1575/// Get the appropriate linkage for the wrapper function. This is essentially
1576/// the weak form of the variable's linkage; every translation unit which wneeds
1577/// the wrapper emits a copy, and we want the linker to merge them.
1578static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1579 llvm::GlobalValue::LinkageTypes VarLinkage) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001580 // For internal linkage variables, we don't need an external or weak wrapper.
1581 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1582 return VarLinkage;
1583 return llvm::GlobalValue::WeakODRLinkage;
1584}
1585
1586llvm::Function *
1587ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1588 llvm::GlobalVariable *Var) {
1589 // Mangle the name for the thread_local wrapper function.
1590 SmallString<256> WrapperName;
1591 {
1592 llvm::raw_svector_ostream Out(WrapperName);
1593 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1594 Out.flush();
1595 }
1596
1597 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1598 return cast<llvm::Function>(V);
1599
1600 llvm::Type *RetTy = Var->getType();
1601 if (VD->getType()->isReferenceType())
1602 RetTy = RetTy->getPointerElementType();
1603
1604 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1605 llvm::Function *Wrapper = llvm::Function::Create(
David Majnemerceaaa8d2014-05-05 18:54:23 +00001606 FnTy, getThreadLocalWrapperLinkage(
1607 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
1608 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001609 // Always resolve references to the wrapper at link time.
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001610 if (!Wrapper->hasLocalLinkage())
1611 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001612 return Wrapper;
1613}
1614
1615void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1616 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1617 llvm::Function *InitFunc) {
1618 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1619 const VarDecl *VD = Decls[I].first;
1620 llvm::GlobalVariable *Var = Decls[I].second;
1621
1622 // Mangle the name for the thread_local initialization function.
1623 SmallString<256> InitFnName;
1624 {
1625 llvm::raw_svector_ostream Out(InitFnName);
1626 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1627 Out.flush();
1628 }
1629
1630 // If we have a definition for the variable, emit the initialization
1631 // function as an alias to the global Init function (if any). Otherwise,
1632 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001633 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001634 bool InitIsInitFunc = false;
1635 if (VD->hasDefinition()) {
1636 InitIsInitFunc = true;
1637 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001638 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1639 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001640 } else {
1641 // Emit a weak global function referring to the initialization function.
1642 // This function will not exist if the TU defining the thread_local
1643 // variable in question does not need any dynamic initialization for
1644 // its thread_local variables.
1645 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1646 Init = llvm::Function::Create(
1647 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1648 &CGM.getModule());
1649 }
1650
1651 if (Init)
1652 Init->setVisibility(Var->getVisibility());
1653
1654 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1655 llvm::LLVMContext &Context = CGM.getModule().getContext();
1656 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1657 CGBuilderTy Builder(Entry);
1658 if (InitIsInitFunc) {
1659 if (Init)
1660 Builder.CreateCall(Init);
1661 } else {
1662 // Don't know whether we have an init function. Call it if it exists.
1663 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1664 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1665 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1666 Builder.CreateCondBr(Have, InitBB, ExitBB);
1667
1668 Builder.SetInsertPoint(InitBB);
1669 Builder.CreateCall(Init);
1670 Builder.CreateBr(ExitBB);
1671
1672 Builder.SetInsertPoint(ExitBB);
1673 }
1674
1675 // For a reference, the result of the wrapper function is a pointer to
1676 // the referenced object.
1677 llvm::Value *Val = Var;
1678 if (VD->getType()->isReferenceType()) {
1679 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1680 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1681 Val = LI;
1682 }
1683
1684 Builder.CreateRet(Val);
1685 }
1686}
1687
Richard Smith0f383742014-03-26 22:48:22 +00001688LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1689 const VarDecl *VD,
1690 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001691 QualType T = VD->getType();
1692 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1693 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1694 llvm::Function *Wrapper =
1695 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1696
1697 Val = CGF.Builder.CreateCall(Wrapper);
1698
1699 LValue LV;
1700 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00001701 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001702 else
Richard Smith0f383742014-03-26 22:48:22 +00001703 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001704 // FIXME: need setObjCGCLValueClass?
1705 return LV;
1706}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001707
1708/// Return whether the given global decl needs a VTT parameter, which it does
1709/// if it's a base constructor or destructor with virtual bases.
1710bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1711 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1712
1713 // We don't have any virtual bases, just return early.
1714 if (!MD->getParent()->getNumVBases())
1715 return false;
1716
1717 // Check if we have a base constructor.
1718 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1719 return true;
1720
1721 // Check if we have a base destructor.
1722 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1723 return true;
1724
1725 return false;
1726}