blob: 0e8f31a48454a122fa454231599529ba76aa978a [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
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000055 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
56 // Structures with either a non-trivial destructor or a non-trivial
57 // copy constructor are always indirect.
58 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
59 }
60
61 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
62 // Structures with either a non-trivial destructor or a non-trivial
63 // copy constructor are always indirect.
64 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
65 return RAA_Indirect;
66 return RAA_Default;
67 }
68
John McCall614dbdc2010-08-22 21:01:12 +000069 bool isZeroInitializable(const MemberPointerType *MPT);
John McCall84fa5102010-08-22 04:16:24 +000070
Chris Lattnera5f58b02011-07-09 17:41:47 +000071 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall7a9aac22010-08-23 01:21:21 +000072
John McCall475999d2010-08-22 00:05:51 +000073 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
74 llvm::Value *&This,
75 llvm::Value *MemFnPtr,
76 const MemberPointerType *MPT);
John McCalla8bbb822010-08-22 03:04:22 +000077
John McCallc134eb52010-08-31 21:07:20 +000078 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
79 llvm::Value *Base,
80 llvm::Value *MemPtr,
81 const MemberPointerType *MPT);
82
John McCall7a9aac22010-08-23 01:21:21 +000083 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
84 const CastExpr *E,
85 llvm::Value *Src);
John McCallc62bb392012-02-15 01:22:51 +000086 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
87 llvm::Constant *Src);
John McCall84fa5102010-08-22 04:16:24 +000088
John McCall7a9aac22010-08-23 01:21:21 +000089 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCall84fa5102010-08-22 04:16:24 +000090
John McCall2979fe02011-04-12 00:42:48 +000091 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCallf3a88602011-02-03 08:15:49 +000092 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
93 CharUnits offset);
Richard Smithdafff942012-01-14 04:30:29 +000094 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
95 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
96 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +000097
John McCall7a9aac22010-08-23 01:21:21 +000098 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
99 llvm::Value *L,
100 llvm::Value *R,
101 const MemberPointerType *MPT,
102 bool Inequality);
John McCall131d97d2010-08-22 08:30:07 +0000103
John McCall7a9aac22010-08-23 01:21:21 +0000104 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
105 llvm::Value *Addr,
106 const MemberPointerType *MPT);
John McCall5d865c322010-08-31 07:33:07 +0000107
John McCall82fb8922012-09-25 10:10:39 +0000108 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
109 llvm::Value *ptr,
110 QualType type);
111
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000112 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
113 llvm::Value *This,
114 const CXXRecordDecl *ClassDecl,
115 const CXXRecordDecl *BaseClassDecl);
116
John McCall5d865c322010-08-31 07:33:07 +0000117 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
118 CXXCtorType T,
119 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000120 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000121
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000122 void EmitCXXConstructors(const CXXConstructorDecl *D);
123
John McCall5d865c322010-08-31 07:33:07 +0000124 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
125 CXXDtorType T,
126 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000128
Reid Klecknere7de47e2013-07-22 13:51:44 +0000129 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
130 CXXDtorType DT) const {
131 // Itanium does not emit any destructor variant as an inline thunk.
132 // Delegating may occur as an optimization, but all variants are either
133 // emitted with external linkage or as linkonce if they are inline and used.
134 return false;
135 }
136
137 void EmitCXXDestructors(const CXXDestructorDecl *D);
138
John McCall5d865c322010-08-31 07:33:07 +0000139 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
140 QualType &ResTy,
141 FunctionArgList &Params);
142
143 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall8ed55a52010-09-02 09:58:18 +0000144
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000145 void EmitConstructorCall(CodeGenFunction &CGF,
146 const CXXConstructorDecl *D, CXXCtorType Type,
147 bool ForVirtualBase, bool Delegating,
Stephen Linc467c872013-06-19 18:10:35 +0000148 llvm::Value *This,
149 CallExpr::const_arg_iterator ArgBeg,
150 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000151
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000152 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
153
154 llvm::Value *getVTableAddressPointInStructor(
155 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
156 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
157 bool &NeedsVirtualOffset);
158
159 llvm::Constant *
160 getVTableAddressPointForConstExpr(BaseSubobject Base,
161 const CXXRecordDecl *VTableClass);
162
163 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
164 CharUnits VPtrOffset);
165
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000166 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
167 llvm::Value *This, llvm::Type *Ty);
168
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000169 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
170 const CXXDestructorDecl *Dtor,
171 CXXDtorType DtorType, SourceLocation CallLoc,
172 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000173
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000174 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000175
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000176 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
177 // Allow inlining of thunks by emitting them with available_externally
178 // linkage together with vtables when needed.
179 if (ForVTable)
180 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
181 }
182
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000183 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
184 const ThisAdjustment &TA);
185
186 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
187 const ReturnAdjustment &RA);
188
Joao Matos2ce88ef2012-07-17 17:10:11 +0000189 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikieeb7d5982012-10-16 22:56:05 +0000190 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000191
John McCallb91cd662012-05-01 05:23:51 +0000192 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall8ed55a52010-09-02 09:58:18 +0000193 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
194 llvm::Value *NewPtr,
195 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000196 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +0000197 QualType ElementType);
John McCallb91cd662012-05-01 05:23:51 +0000198 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
199 llvm::Value *allocPtr,
200 CharUnits cookieSize);
John McCall68ff0372010-09-08 01:44:27 +0000201
John McCallcdf7ef52010-11-06 09:44:32 +0000202 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000203 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smithdbf74ba2013-04-14 23:01:42 +0000204 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
205 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000206
207 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
208 llvm::GlobalVariable *Var);
209 void EmitThreadLocalInitFuncs(
210 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
211 llvm::Function *InitFunc);
212 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
213 const DeclRefExpr *DRE);
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000214
215 bool NeedsVTTParameter(GlobalDecl GD);
Charles Davis4e786dd2010-05-25 19:52:27 +0000216};
John McCall86353412010-08-21 22:46:04 +0000217
218class ARMCXXABI : public ItaniumCXXABI {
219public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000220 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
221 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
222 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000223
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000224 bool HasThisReturn(GlobalDecl GD) const {
225 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
226 isa<CXXDestructorDecl>(GD.getDecl()) &&
227 GD.getDtorType() != Dtor_Deleting));
228 }
John McCall5d865c322010-08-31 07:33:07 +0000229
230 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
231
John McCallb91cd662012-05-01 05:23:51 +0000232 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall8ed55a52010-09-02 09:58:18 +0000233 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
234 llvm::Value *NewPtr,
235 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000236 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +0000237 QualType ElementType);
John McCallb91cd662012-05-01 05:23:51 +0000238 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
239 CharUnits cookieSize);
John McCall86353412010-08-21 22:46:04 +0000240};
Charles Davis4e786dd2010-05-25 19:52:27 +0000241}
242
Charles Davis53c59df2010-08-16 03:33:14 +0000243CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000244 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000245 // For IR-generation purposes, there's no significant difference
246 // between the ARM and iOS ABIs.
247 case TargetCXXABI::GenericARM:
248 case TargetCXXABI::iOS:
249 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000250
Tim Northover9bb857a2013-01-31 12:13:10 +0000251 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
252 // include the other 32-bit ARM oddities: constructor/destructor return values
253 // and array cookies.
254 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000255 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
256 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000257
John McCall57625922013-01-25 23:36:14 +0000258 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000259 if (CGM.getContext().getTargetInfo().getTriple().getArch()
260 == llvm::Triple::le32) {
261 // For PNaCl, use ARM-style method pointers so that PNaCl code
262 // does not assume anything about the alignment of function
263 // pointers.
264 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
265 /* UseARMGuardVarABI = */ false);
266 }
John McCall57625922013-01-25 23:36:14 +0000267 return new ItaniumCXXABI(CGM);
268
269 case TargetCXXABI::Microsoft:
270 llvm_unreachable("Microsoft ABI is not Itanium-based");
271 }
272 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000273}
274
Chris Lattnera5f58b02011-07-09 17:41:47 +0000275llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000276ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
277 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000278 return CGM.PtrDiffTy;
279 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000280}
281
John McCalld9c6c0b2010-08-22 00:59:17 +0000282/// In the Itanium and ARM ABIs, method pointers have the form:
283/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
284///
285/// In the Itanium ABI:
286/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
287/// - the this-adjustment is (memptr.adj)
288/// - the virtual offset is (memptr.ptr - 1)
289///
290/// In the ARM ABI:
291/// - method pointers are virtual if (memptr.adj & 1) is nonzero
292/// - the this-adjustment is (memptr.adj >> 1)
293/// - the virtual offset is (memptr.ptr)
294/// ARM uses 'adj' for the virtual flag because Thumb functions
295/// may be only single-byte aligned.
296///
297/// If the member is virtual, the adjusted 'this' pointer points
298/// to a vtable pointer from which the virtual offset is applied.
299///
300/// If the member is non-virtual, memptr.ptr is the address of
301/// the function to call.
John McCall475999d2010-08-22 00:05:51 +0000302llvm::Value *
303ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
304 llvm::Value *&This,
305 llvm::Value *MemFnPtr,
306 const MemberPointerType *MPT) {
307 CGBuilderTy &Builder = CGF.Builder;
308
309 const FunctionProtoType *FPT =
310 MPT->getPointeeType()->getAs<FunctionProtoType>();
311 const CXXRecordDecl *RD =
312 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
313
Chris Lattner2192fe52011-07-18 04:24:23 +0000314 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000315 CGM.getTypes().GetFunctionType(
316 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000317
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000318 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000319
John McCalld9c6c0b2010-08-22 00:59:17 +0000320 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
321 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
322 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
323
John McCalla1dee5302010-08-22 10:59:02 +0000324 // Extract memptr.adj, which is in the second field.
325 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000326
327 // Compute the true adjustment.
328 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000329 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000330 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000331
332 // Apply the adjustment and cast back to the original struct type
333 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000334 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
335 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
336 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000337
338 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000339 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000340
341 // If the LSB in the function pointer is 1, the function pointer points to
342 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000343 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000344 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000345 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
346 else
347 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
348 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000349 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
350
351 // In the virtual path, the adjustment left 'This' pointing to the
352 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000353 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000354 CGF.EmitBlock(FnVirtual);
355
356 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000357 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall475999d2010-08-22 00:05:51 +0000358 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000359 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall475999d2010-08-22 00:05:51 +0000360
361 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000362 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000363 if (!UseARMMethodPtrABI)
364 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000365 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000366
367 // Load the virtual function to call.
368 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000369 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000370 CGF.EmitBranch(FnEnd);
371
372 // In the non-virtual path, the function pointer is actually a
373 // function pointer.
374 CGF.EmitBlock(FnNonVirtual);
375 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000376 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000377
378 // We're done.
379 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000380 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000381 Callee->addIncoming(VirtualFn, FnVirtual);
382 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
383 return Callee;
384}
John McCalla8bbb822010-08-22 03:04:22 +0000385
John McCallc134eb52010-08-31 21:07:20 +0000386/// Compute an l-value by applying the given pointer-to-member to a
387/// base object.
388llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
389 llvm::Value *Base,
390 llvm::Value *MemPtr,
391 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000392 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000393
394 CGBuilderTy &Builder = CGF.Builder;
395
Micah Villmowea2fea22012-10-25 15:39:14 +0000396 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000397
398 // Cast to char*.
399 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
400
401 // Apply the offset, which we assume is non-null.
402 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
403
404 // Cast the address to the appropriate pointer type, adopting the
405 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000406 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000407 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000408 return Builder.CreateBitCast(Addr, PType);
409}
410
John McCallc62bb392012-02-15 01:22:51 +0000411/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
412/// conversion.
413///
414/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000415///
416/// Obligatory offset/adjustment diagram:
417/// <-- offset --> <-- adjustment -->
418/// |--------------------------|----------------------|--------------------|
419/// ^Derived address point ^Base address point ^Member address point
420///
421/// So when converting a base member pointer to a derived member pointer,
422/// we add the offset to the adjustment because the address point has
423/// decreased; and conversely, when converting a derived MP to a base MP
424/// we subtract the offset from the adjustment because the address point
425/// has increased.
426///
427/// The standard forbids (at compile time) conversion to and from
428/// virtual bases, which is why we don't have to consider them here.
429///
430/// The standard forbids (at run time) casting a derived MP to a base
431/// MP when the derived MP does not point to a member of the base.
432/// This is why -1 is a reasonable choice for null data member
433/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000434llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000435ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
436 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000437 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000438 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000439 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
440 E->getCastKind() == CK_ReinterpretMemberPointer);
441
442 // Under Itanium, reinterprets don't require any additional processing.
443 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
444
445 // Use constant emission if we can.
446 if (isa<llvm::Constant>(src))
447 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
448
449 llvm::Constant *adj = getMemberPointerAdjustment(E);
450 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000451
452 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000453 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000454
John McCallc62bb392012-02-15 01:22:51 +0000455 const MemberPointerType *destTy =
456 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000457
John McCall7a9aac22010-08-23 01:21:21 +0000458 // For member data pointers, this is just a matter of adding the
459 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000460 if (destTy->isMemberDataPointer()) {
461 llvm::Value *dst;
462 if (isDerivedToBase)
463 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000464 else
John McCallc62bb392012-02-15 01:22:51 +0000465 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000466
467 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000468 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
469 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
470 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000471 }
472
John McCalla1dee5302010-08-22 10:59:02 +0000473 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000474 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000475 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
476 offset <<= 1;
477 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000478 }
479
John McCallc62bb392012-02-15 01:22:51 +0000480 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
481 llvm::Value *dstAdj;
482 if (isDerivedToBase)
483 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000484 else
John McCallc62bb392012-02-15 01:22:51 +0000485 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000486
John McCallc62bb392012-02-15 01:22:51 +0000487 return Builder.CreateInsertValue(src, dstAdj, 1);
488}
489
490llvm::Constant *
491ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
492 llvm::Constant *src) {
493 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
494 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
495 E->getCastKind() == CK_ReinterpretMemberPointer);
496
497 // Under Itanium, reinterprets don't require any additional processing.
498 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
499
500 // If the adjustment is trivial, we don't need to do anything.
501 llvm::Constant *adj = getMemberPointerAdjustment(E);
502 if (!adj) return src;
503
504 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
505
506 const MemberPointerType *destTy =
507 E->getType()->castAs<MemberPointerType>();
508
509 // For member data pointers, this is just a matter of adding the
510 // offset if the source is non-null.
511 if (destTy->isMemberDataPointer()) {
512 // null maps to null.
513 if (src->isAllOnesValue()) return src;
514
515 if (isDerivedToBase)
516 return llvm::ConstantExpr::getNSWSub(src, adj);
517 else
518 return llvm::ConstantExpr::getNSWAdd(src, adj);
519 }
520
521 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000522 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000523 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
524 offset <<= 1;
525 adj = llvm::ConstantInt::get(adj->getType(), offset);
526 }
527
528 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
529 llvm::Constant *dstAdj;
530 if (isDerivedToBase)
531 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
532 else
533 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
534
535 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000536}
John McCall84fa5102010-08-22 04:16:24 +0000537
538llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000539ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000540 // Itanium C++ ABI 2.3:
541 // A NULL pointer is represented as -1.
542 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000543 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000544
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000545 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000546 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000547 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000548}
549
John McCallf3a88602011-02-03 08:15:49 +0000550llvm::Constant *
551ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
552 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000553 // Itanium C++ ABI 2.3:
554 // A pointer to data member is an offset from the base address of
555 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000556 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000557}
558
John McCall2979fe02011-04-12 00:42:48 +0000559llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000560 return BuildMemberPointer(MD, CharUnits::Zero());
561}
562
563llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
564 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000565 assert(MD->isInstance() && "Member function must not be static!");
566 MD = MD->getCanonicalDecl();
567
568 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000569
570 // Get the function pointer (or index if this is a virtual function).
571 llvm::Constant *MemPtr[2];
572 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000573 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000574
Ken Dyckdf016282011-04-09 01:30:02 +0000575 const ASTContext &Context = getContext();
576 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000577 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000578 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000579
Mark Seabornedf0d382013-07-24 16:25:13 +0000580 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000581 // ARM C++ ABI 3.2.1:
582 // This ABI specifies that adj contains twice the this
583 // adjustment, plus 1 if the member function is virtual. The
584 // least significant bit of adj then makes exactly the same
585 // discrimination as the least significant bit of ptr does for
586 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000587 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
588 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000589 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000590 } else {
591 // Itanium C++ ABI 2.3:
592 // For a virtual function, [the pointer field] is 1 plus the
593 // virtual table offset (in bytes) of the function,
594 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000595 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
596 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000597 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000598 }
599 } else {
John McCall2979fe02011-04-12 00:42:48 +0000600 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000601 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000602 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000603 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000604 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000605 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000606 } else {
John McCall2979fe02011-04-12 00:42:48 +0000607 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
608 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000609 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000610 }
John McCall2979fe02011-04-12 00:42:48 +0000611 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000612
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000613 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000614 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
615 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000616 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000617 }
John McCall1c456c82010-08-22 06:43:33 +0000618
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000619 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000620}
621
Richard Smithdafff942012-01-14 04:30:29 +0000622llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
623 QualType MPType) {
624 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
625 const ValueDecl *MPD = MP.getMemberPointerDecl();
626 if (!MPD)
627 return EmitNullMemberPointer(MPT);
628
Reid Kleckner452abac2013-05-09 21:01:17 +0000629 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000630
631 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
632 return BuildMemberPointer(MD, ThisAdjustment);
633
634 CharUnits FieldOffset =
635 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
636 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
637}
638
John McCall131d97d2010-08-22 08:30:07 +0000639/// The comparison algorithm is pretty easy: the member pointers are
640/// the same if they're either bitwise identical *or* both null.
641///
642/// ARM is different here only because null-ness is more complicated.
643llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000644ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
645 llvm::Value *L,
646 llvm::Value *R,
647 const MemberPointerType *MPT,
648 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000649 CGBuilderTy &Builder = CGF.Builder;
650
John McCall131d97d2010-08-22 08:30:07 +0000651 llvm::ICmpInst::Predicate Eq;
652 llvm::Instruction::BinaryOps And, Or;
653 if (Inequality) {
654 Eq = llvm::ICmpInst::ICMP_NE;
655 And = llvm::Instruction::Or;
656 Or = llvm::Instruction::And;
657 } else {
658 Eq = llvm::ICmpInst::ICMP_EQ;
659 And = llvm::Instruction::And;
660 Or = llvm::Instruction::Or;
661 }
662
John McCall7a9aac22010-08-23 01:21:21 +0000663 // Member data pointers are easy because there's a unique null
664 // value, so it just comes down to bitwise equality.
665 if (MPT->isMemberDataPointer())
666 return Builder.CreateICmp(Eq, L, R);
667
668 // For member function pointers, the tautologies are more complex.
669 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000670 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000671 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000672 // (L == R) <==> (L.ptr == R.ptr &&
673 // (L.adj == R.adj ||
674 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000675 // The inequality tautologies have exactly the same structure, except
676 // applying De Morgan's laws.
677
678 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
679 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
680
John McCall131d97d2010-08-22 08:30:07 +0000681 // This condition tests whether L.ptr == R.ptr. This must always be
682 // true for equality to hold.
683 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
684
685 // This condition, together with the assumption that L.ptr == R.ptr,
686 // tests whether the pointers are both null. ARM imposes an extra
687 // condition.
688 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
689 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
690
691 // This condition tests whether L.adj == R.adj. If this isn't
692 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000693 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
694 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000695 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
696
697 // Null member function pointers on ARM clear the low bit of Adj,
698 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000699 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000700 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
701
702 // Compute (l.adj | r.adj) & 1 and test it against zero.
703 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
704 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
705 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
706 "cmp.or.adj");
707 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
708 }
709
710 // Tie together all our conditions.
711 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
712 Result = Builder.CreateBinOp(And, PtrEq, Result,
713 Inequality ? "memptr.ne" : "memptr.eq");
714 return Result;
715}
716
717llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000718ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
719 llvm::Value *MemPtr,
720 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000721 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000722
723 /// For member data pointers, this is just a check against -1.
724 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000725 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000726 llvm::Value *NegativeOne =
727 llvm::Constant::getAllOnesValue(MemPtr->getType());
728 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
729 }
John McCall131d97d2010-08-22 08:30:07 +0000730
Daniel Dunbar914bc412011-04-19 23:10:47 +0000731 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000732 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000733
734 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
735 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
736
Daniel Dunbar914bc412011-04-19 23:10:47 +0000737 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
738 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000739 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000740 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000741 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000742 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000743 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
744 "memptr.isvirtual");
745 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000746 }
747
748 return Result;
749}
John McCall1c456c82010-08-22 06:43:33 +0000750
John McCall614dbdc2010-08-22 21:01:12 +0000751/// The Itanium ABI requires non-zero initialization only for data
752/// member pointers, for which '0' is a valid offset.
753bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
754 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000755}
John McCall5d865c322010-08-31 07:33:07 +0000756
John McCall82fb8922012-09-25 10:10:39 +0000757/// The Itanium ABI always places an offset to the complete object
758/// at entry -2 in the vtable.
759llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
760 llvm::Value *ptr,
761 QualType type) {
762 // Grab the vtable pointer as an intptr_t*.
763 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
764
765 // Track back to entry -2 and pull out the offset there.
766 llvm::Value *offsetPtr =
767 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
768 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
769 offset->setAlignment(CGF.PointerAlignInBytes);
770
771 // Apply the offset.
772 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
773 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
774}
775
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000776llvm::Value *
777ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
778 llvm::Value *This,
779 const CXXRecordDecl *ClassDecl,
780 const CXXRecordDecl *BaseClassDecl) {
781 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
782 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000783 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
784 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000785
786 llvm::Value *VBaseOffsetPtr =
787 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
788 "vbase.offset.ptr");
789 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
790 CGM.PtrDiffTy->getPointerTo());
791
792 llvm::Value *VBaseOffset =
793 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
794
795 return VBaseOffset;
796}
797
John McCall5d865c322010-08-31 07:33:07 +0000798/// The generic ABI passes 'this', plus a VTT if it's initializing a
799/// base subobject.
800void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
801 CXXCtorType Type,
802 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000803 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000804 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000805
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000806 // 'this' parameter is already there, as well as 'this' return if
807 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000808
809 // Check if we need to add a VTT parameter (which has type void **).
810 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
811 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
812}
813
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000814void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
815 // Just make sure we're in sync with TargetCXXABI.
816 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
817
818 // The constructor used for constructing this as a complete class;
819 // constucts the virtual bases, then calls the base constructor.
820 if (!D->getParent()->isAbstract()) {
821 // We don't need to emit the complete ctor if the class is abstract.
822 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
823 }
824
825 // The constructor used for constructing this as a base class;
826 // ignores virtual bases.
827 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
828}
829
John McCall5d865c322010-08-31 07:33:07 +0000830/// The generic ABI passes 'this', plus a VTT if it's destroying a
831/// base subobject.
832void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
833 CXXDtorType Type,
834 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000835 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +0000836 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000837
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000838 // 'this' parameter is already there, as well as 'this' return if
839 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +0000840
841 // Check if we need to add a VTT parameter (which has type void **).
842 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
843 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
844}
845
Reid Klecknere7de47e2013-07-22 13:51:44 +0000846void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
847 // The destructor in a virtual table is always a 'deleting'
848 // destructor, which calls the complete destructor and then uses the
849 // appropriate operator delete.
850 if (D->isVirtual())
851 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
852
853 // The destructor used for destructing this as a most-derived class;
854 // call the base destructor and then destructs any virtual bases.
855 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
856
857 // The destructor used for destructing this as a base class; ignores
858 // virtual bases.
859 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
860}
861
John McCall5d865c322010-08-31 07:33:07 +0000862void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
863 QualType &ResTy,
864 FunctionArgList &Params) {
865 /// Create the 'this' variable.
866 BuildThisParam(CGF, Params);
867
868 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
869 assert(MD->isInstance());
870
871 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000872 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +0000873 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +0000874
875 // FIXME: avoid the fake decl
876 QualType T = Context.getPointerType(Context.VoidPtrTy);
877 ImplicitParamDecl *VTTDecl
878 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
879 &Context.Idents.get("vtt"), T);
John McCalla738c252011-03-09 04:27:21 +0000880 Params.push_back(VTTDecl);
John McCall5d865c322010-08-31 07:33:07 +0000881 getVTTDecl(CGF) = VTTDecl;
882 }
883}
884
John McCall5d865c322010-08-31 07:33:07 +0000885void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
886 /// Initialize the 'this' slot.
887 EmitThisParam(CGF);
888
889 /// Initialize the 'vtt' slot if needed.
890 if (getVTTDecl(CGF)) {
891 getVTTValue(CGF)
892 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
893 "vtt");
894 }
John McCall5d865c322010-08-31 07:33:07 +0000895
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000896 /// If this is a function that the ABI specifies returns 'this', initialize
897 /// the return slot to 'this' at the start of the function.
898 ///
899 /// Unlike the setting of return types, this is done within the ABI
900 /// implementation instead of by clients of CGCXXABI because:
901 /// 1) getThisValue is currently protected
902 /// 2) in theory, an ABI could implement 'this' returns some other way;
903 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +0000904 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +0000905 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +0000906}
907
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000908void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000909 const CXXConstructorDecl *D,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000910 CXXCtorType Type,
911 bool ForVirtualBase, bool Delegating,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000912 llvm::Value *This,
913 CallExpr::const_arg_iterator ArgBeg,
914 CallExpr::const_arg_iterator ArgEnd) {
915 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
916 Delegating);
917 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
918 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
919
920 // FIXME: Provide a source location here.
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000921 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
922 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000923}
924
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000925void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
926 const CXXRecordDecl *RD) {
927 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
928 if (VTable->hasInitializer())
929 return;
930
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000931 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000932 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
933 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
934
935 // Create and set the initializer.
936 llvm::Constant *Init = CGVT.CreateVTableInitializer(
937 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
938 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
939 VTable->setInitializer(Init);
940
941 // Set the correct linkage.
942 VTable->setLinkage(Linkage);
943
944 // Set the right visibility.
945 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
946
947 // If this is the magic class __cxxabiv1::__fundamental_type_info,
948 // we will emit the typeinfo for the fundamental types. This is the
949 // same behaviour as GCC.
950 const DeclContext *DC = RD->getDeclContext();
951 if (RD->getIdentifier() &&
952 RD->getIdentifier()->isStr("__fundamental_type_info") &&
953 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
954 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
955 DC->getParent()->isTranslationUnit())
956 CGM.EmitFundamentalRTTIDescriptors();
957}
958
959llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
960 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
961 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
962 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
963 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
964
965 llvm::Value *VTableAddressPoint;
966 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
967 // Get the secondary vpointer index.
968 uint64_t VirtualPointerIndex =
969 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
970
971 /// Load the VTT.
972 llvm::Value *VTT = CGF.LoadCXXVTT();
973 if (VirtualPointerIndex)
974 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
975
976 // And load the address point from the VTT.
977 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
978 } else {
979 llvm::Constant *VTable =
980 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000981 uint64_t AddressPoint = CGM.getItaniumVTableContext()
982 .getVTableLayout(VTableClass)
983 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000984 VTableAddressPoint =
985 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
986 }
987
988 return VTableAddressPoint;
989}
990
991llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
992 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
993 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
994
995 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000996 uint64_t AddressPoint = CGM.getItaniumVTableContext()
997 .getVTableLayout(VTableClass)
998 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000999 llvm::Value *Indices[] = {
1000 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1001 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1002 };
1003
1004 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1005}
1006
1007llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1008 CharUnits VPtrOffset) {
1009 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1010
1011 llvm::GlobalVariable *&VTable = VTables[RD];
1012 if (VTable)
1013 return VTable;
1014
1015 // Queue up this v-table for possible deferred emission.
1016 CGM.addDeferredVTable(RD);
1017
1018 SmallString<256> OutName;
1019 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001020 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001021 Out.flush();
1022 StringRef Name = OutName.str();
1023
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001024 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001025 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1026 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1027
1028 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1029 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1030 VTable->setUnnamedAddr(true);
1031 return VTable;
1032}
1033
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001034llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1035 GlobalDecl GD,
1036 llvm::Value *This,
1037 llvm::Type *Ty) {
1038 GD = GD.getCanonicalDecl();
1039 Ty = Ty->getPointerTo()->getPointerTo();
1040 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1041
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001042 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001043 llvm::Value *VFuncPtr =
1044 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1045 return CGF.Builder.CreateLoad(VFuncPtr);
1046}
1047
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001048void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1049 const CXXDestructorDecl *Dtor,
1050 CXXDtorType DtorType,
1051 SourceLocation CallLoc,
1052 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001053 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1054
1055 const CGFunctionInfo *FInfo
1056 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1057 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001058 llvm::Value *Callee =
1059 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001060
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001061 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1062 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001063}
1064
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001065void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001066 CodeGenVTables &VTables = CGM.getVTables();
1067 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001068 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001069}
1070
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001071static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1072 llvm::Value *Ptr,
1073 int64_t NonVirtualAdjustment,
1074 int64_t VirtualAdjustment,
1075 bool IsReturnAdjustment) {
1076 if (!NonVirtualAdjustment && !VirtualAdjustment)
1077 return Ptr;
1078
1079 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1080 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1081
1082 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1083 // Perform the non-virtual adjustment for a base-to-derived cast.
1084 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1085 }
1086
1087 if (VirtualAdjustment) {
1088 llvm::Type *PtrDiffTy =
1089 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1090
1091 // Perform the virtual adjustment.
1092 llvm::Value *VTablePtrPtr =
1093 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1094
1095 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1096
1097 llvm::Value *OffsetPtr =
1098 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1099
1100 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1101
1102 // Load the adjustment offset from the vtable.
1103 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1104
1105 // Adjust our pointer.
1106 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1107 }
1108
1109 if (NonVirtualAdjustment && IsReturnAdjustment) {
1110 // Perform the non-virtual adjustment for a derived-to-base cast.
1111 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1112 }
1113
1114 // Cast back to the original type.
1115 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1116}
1117
1118llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1119 llvm::Value *This,
1120 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001121 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1122 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001123 /*IsReturnAdjustment=*/false);
1124}
1125
1126llvm::Value *
1127ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1128 const ReturnAdjustment &RA) {
1129 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1130 RA.Virtual.Itanium.VBaseOffsetOffset,
1131 /*IsReturnAdjustment=*/true);
1132}
1133
John McCall5d865c322010-08-31 07:33:07 +00001134void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1135 RValue RV, QualType ResultType) {
1136 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1137 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1138
1139 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001140 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001141 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1142 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1143 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1144}
John McCall8ed55a52010-09-02 09:58:18 +00001145
1146/************************** Array allocation cookies **************************/
1147
John McCallb91cd662012-05-01 05:23:51 +00001148CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1149 // The array cookie is a size_t; pad that up to the element alignment.
1150 // The cookie is actually right-justified in that space.
1151 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1152 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001153}
1154
1155llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1156 llvm::Value *NewPtr,
1157 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001158 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001159 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001160 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001161
Micah Villmowea2fea22012-10-25 15:39:14 +00001162 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001163
John McCall9bca9232010-09-02 10:25:57 +00001164 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001165 QualType SizeTy = Ctx.getSizeType();
1166 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1167
1168 // The size of the cookie.
1169 CharUnits CookieSize =
1170 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001171 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001172
1173 // Compute an offset to the cookie.
1174 llvm::Value *CookiePtr = NewPtr;
1175 CharUnits CookieOffset = CookieSize - SizeSize;
1176 if (!CookieOffset.isZero())
1177 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1178 CookieOffset.getQuantity());
1179
1180 // Write the number of elements into the appropriate slot.
1181 llvm::Value *NumElementsPtr
1182 = CGF.Builder.CreateBitCast(CookiePtr,
1183 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1184 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1185
1186 // Finally, compute a pointer to the actual data buffer by skipping
1187 // over the cookie completely.
1188 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1189 CookieSize.getQuantity());
1190}
1191
John McCallb91cd662012-05-01 05:23:51 +00001192llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1193 llvm::Value *allocPtr,
1194 CharUnits cookieSize) {
1195 // The element size is right-justified in the cookie.
1196 llvm::Value *numElementsPtr = allocPtr;
1197 CharUnits numElementsOffset =
1198 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1199 if (!numElementsOffset.isZero())
1200 numElementsPtr =
1201 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1202 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001203
Micah Villmowea2fea22012-10-25 15:39:14 +00001204 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001205 numElementsPtr =
1206 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1207 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001208}
1209
John McCallb91cd662012-05-01 05:23:51 +00001210CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001211 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001212 // struct array_cookie {
1213 // std::size_t element_size; // element_size != 0
1214 // std::size_t element_count;
1215 // };
John McCallc19c7062013-01-25 23:36:19 +00001216 // But the base ABI doesn't give anything an alignment greater than
1217 // 8, so we can dismiss this as typical ABI-author blindness to
1218 // actual language complexity and round up to the element alignment.
1219 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1220 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001221}
1222
1223llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001224 llvm::Value *newPtr,
1225 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001226 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001227 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001228 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001229
John McCallc19c7062013-01-25 23:36:19 +00001230 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1231 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001232
1233 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001234 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001235
1236 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001237 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1238 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1239 getContext().getTypeSizeInChars(elementType).getQuantity());
1240 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001241
1242 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001243 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1244 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001245
1246 // Finally, compute a pointer to the actual data buffer by skipping
1247 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001248 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1249 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1250 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001251}
1252
John McCallb91cd662012-05-01 05:23:51 +00001253llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1254 llvm::Value *allocPtr,
1255 CharUnits cookieSize) {
1256 // The number of elements is at offset sizeof(size_t) relative to
1257 // the allocated pointer.
1258 llvm::Value *numElementsPtr
1259 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001260
Micah Villmowea2fea22012-10-25 15:39:14 +00001261 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001262 numElementsPtr =
1263 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1264 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001265}
1266
John McCall68ff0372010-09-08 01:44:27 +00001267/*********************** Static local initialization **************************/
1268
1269static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001270 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001271 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001272 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001273 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001274 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001275 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001276 llvm::AttributeSet::get(CGM.getLLVMContext(),
1277 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001278 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001279}
1280
1281static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001282 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001283 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001284 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001285 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001286 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001287 llvm::AttributeSet::get(CGM.getLLVMContext(),
1288 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001289 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001290}
1291
1292static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001293 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001294 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001295 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001296 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001297 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001298 llvm::AttributeSet::get(CGM.getLLVMContext(),
1299 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001300 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001301}
1302
1303namespace {
1304 struct CallGuardAbort : EHScopeStack::Cleanup {
1305 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001306 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001307
John McCall30317fd2011-07-12 20:27:29 +00001308 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall882987f2013-02-28 19:01:20 +00001309 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1310 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001311 }
1312 };
1313}
1314
1315/// The ARM code here follows the Itanium code closely enough that we
1316/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001317void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1318 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001319 llvm::GlobalVariable *var,
1320 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001321 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001322
Richard Smithdbf74ba2013-04-14 23:01:42 +00001323 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001324 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001325 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1326 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001327
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001328 // If we have a global variable with internal linkage and thread-safe statics
1329 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001330 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1331
1332 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001333 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001334 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001335 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001336 // Guard variables are 64 bits in the generic ABI and size width on ARM
1337 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001338 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001339 }
John McCallb88a5662012-03-30 21:00:39 +00001340 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001341
John McCallb88a5662012-03-30 21:00:39 +00001342 // Create the guard variable if we don't already have it (as we
1343 // might if we're double-emitting this function body).
1344 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1345 if (!guard) {
1346 // Mangle the name for the guard.
1347 SmallString<256> guardName;
1348 {
1349 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001350 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001351 out.flush();
1352 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001353
John McCallb88a5662012-03-30 21:00:39 +00001354 // Create the guard variable with a zero-initializer.
1355 // Just absorb linkage and visibility from the guarded variable.
1356 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1357 false, var->getLinkage(),
1358 llvm::ConstantInt::get(guardTy, 0),
1359 guardName.str());
1360 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001361 // If the variable is thread-local, so is its guard variable.
1362 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001363
1364 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1365 }
John McCall87590e62012-03-30 07:09:50 +00001366
John McCall68ff0372010-09-08 01:44:27 +00001367 // Test whether the variable has completed initialization.
John McCallb88a5662012-03-30 21:00:39 +00001368 llvm::Value *isInitialized;
John McCall68ff0372010-09-08 01:44:27 +00001369
1370 // ARM C++ ABI 3.2.3.1:
1371 // To support the potential use of initialization guard variables
1372 // as semaphores that are the target of ARM SWP and LDREX/STREX
1373 // synchronizing instructions we define a static initialization
1374 // guard variable to be a 4-byte aligned, 4- byte word with the
1375 // following inline access protocol.
1376 // #define INITIALIZED 1
1377 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1378 // if (__cxa_guard_acquire(&obj_guard))
1379 // ...
1380 // }
Mark Seabornedf0d382013-07-24 16:25:13 +00001381 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001382 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northover9bb857a2013-01-31 12:13:10 +00001383 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1384 V = Builder.CreateAnd(V, Test1);
John McCallb88a5662012-03-30 21:00:39 +00001385 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001386
1387 // Itanium C++ ABI 3.3.2:
1388 // The following is pseudo-code showing how these functions can be used:
1389 // if (obj_guard.first_byte == 0) {
1390 // if ( __cxa_guard_acquire (&obj_guard) ) {
1391 // try {
1392 // ... initialize the object ...;
1393 // } catch (...) {
1394 // __cxa_guard_abort (&obj_guard);
1395 // throw;
1396 // }
1397 // ... queue object destructor with __cxa_atexit() ...;
1398 // __cxa_guard_release (&obj_guard);
1399 // }
1400 // }
1401 } else {
1402 // Load the first byte of the guard variable.
Chandler Carruth84537952012-03-30 19:44:53 +00001403 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001404 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth84537952012-03-30 19:44:53 +00001405 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001406
Eli Friedman84d28122011-09-13 22:21:56 +00001407 // Itanium ABI:
1408 // An implementation supporting thread-safety on multiprocessor
1409 // systems must also guarantee that references to the initialized
1410 // object do not occur before the load of the initialization flag.
1411 //
1412 // In LLVM, we do this by marking the load Acquire.
1413 if (threadsafe)
Chandler Carruth84537952012-03-30 19:44:53 +00001414 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001415
John McCallb88a5662012-03-30 21:00:39 +00001416 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001417 }
1418
1419 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1420 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1421
1422 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001423 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001424
1425 CGF.EmitBlock(InitCheckBlock);
1426
1427 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001428 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001429 // Call __cxa_guard_acquire.
1430 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001431 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001432
1433 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1434
1435 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1436 InitBlock, EndBlock);
1437
1438 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001439 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001440
1441 CGF.EmitBlock(InitBlock);
1442 }
1443
1444 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001445 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001446
John McCall5aa52592011-06-17 07:33:57 +00001447 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001448 // Pop the guard-abort cleanup if we pushed one.
1449 CGF.PopCleanupBlock();
1450
1451 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001452 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001453 } else {
John McCallb88a5662012-03-30 21:00:39 +00001454 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001455 }
1456
1457 CGF.EmitBlock(EndBlock);
1458}
John McCallc84ed6a2012-05-01 06:13:13 +00001459
1460/// Register a global destructor using __cxa_atexit.
1461static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1462 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001463 llvm::Constant *addr,
1464 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001465 const char *Name = "__cxa_atexit";
1466 if (TLS) {
1467 const llvm::Triple &T = CGF.getTarget().getTriple();
1468 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1469 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001470
John McCallc84ed6a2012-05-01 06:13:13 +00001471 // We're assuming that the destructor function is something we can
1472 // reasonably call with the default CC. Go ahead and cast it to the
1473 // right prototype.
1474 llvm::Type *dtorTy =
1475 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1476
1477 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1478 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1479 llvm::FunctionType *atexitTy =
1480 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1481
1482 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001483 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001484 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1485 fn->setDoesNotThrow();
1486
1487 // Create a variable that binds the atexit to this shared object.
1488 llvm::Constant *handle =
1489 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1490
1491 llvm::Value *args[] = {
1492 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1493 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1494 handle
1495 };
John McCall882987f2013-02-28 19:01:20 +00001496 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001497}
1498
1499/// Register a global destructor as best as we know how.
1500void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001501 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001502 llvm::Constant *dtor,
1503 llvm::Constant *addr) {
1504 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001505 if (CGM.getCodeGenOpts().CXAAtExit)
1506 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1507
1508 if (D.getTLSKind())
1509 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001510
1511 // In Apple kexts, we want to add a global destructor entry.
1512 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001513 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001514 // Generate a global destructor entry.
1515 return CGM.AddCXXDtorEntry(dtor, addr);
1516 }
1517
David Blaikieebe87e12013-08-27 23:57:18 +00001518 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001519}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001520
1521/// Get the appropriate linkage for the wrapper function. This is essentially
1522/// the weak form of the variable's linkage; every translation unit which wneeds
1523/// the wrapper emits a copy, and we want the linker to merge them.
1524static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1525 llvm::GlobalValue::LinkageTypes VarLinkage) {
1526 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1527 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1528 // For internal linkage variables, we don't need an external or weak wrapper.
1529 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1530 return VarLinkage;
1531 return llvm::GlobalValue::WeakODRLinkage;
1532}
1533
1534llvm::Function *
1535ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1536 llvm::GlobalVariable *Var) {
1537 // Mangle the name for the thread_local wrapper function.
1538 SmallString<256> WrapperName;
1539 {
1540 llvm::raw_svector_ostream Out(WrapperName);
1541 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1542 Out.flush();
1543 }
1544
1545 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1546 return cast<llvm::Function>(V);
1547
1548 llvm::Type *RetTy = Var->getType();
1549 if (VD->getType()->isReferenceType())
1550 RetTy = RetTy->getPointerElementType();
1551
1552 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1553 llvm::Function *Wrapper = llvm::Function::Create(
1554 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1555 &CGM.getModule());
1556 // Always resolve references to the wrapper at link time.
1557 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1558 return Wrapper;
1559}
1560
1561void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1562 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1563 llvm::Function *InitFunc) {
1564 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1565 const VarDecl *VD = Decls[I].first;
1566 llvm::GlobalVariable *Var = Decls[I].second;
1567
1568 // Mangle the name for the thread_local initialization function.
1569 SmallString<256> InitFnName;
1570 {
1571 llvm::raw_svector_ostream Out(InitFnName);
1572 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1573 Out.flush();
1574 }
1575
1576 // If we have a definition for the variable, emit the initialization
1577 // function as an alias to the global Init function (if any). Otherwise,
1578 // produce a declaration of the initialization function.
1579 llvm::GlobalValue *Init = 0;
1580 bool InitIsInitFunc = false;
1581 if (VD->hasDefinition()) {
1582 InitIsInitFunc = true;
1583 if (InitFunc)
1584 Init =
1585 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1586 InitFnName.str(), InitFunc, &CGM.getModule());
1587 } else {
1588 // Emit a weak global function referring to the initialization function.
1589 // This function will not exist if the TU defining the thread_local
1590 // variable in question does not need any dynamic initialization for
1591 // its thread_local variables.
1592 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1593 Init = llvm::Function::Create(
1594 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1595 &CGM.getModule());
1596 }
1597
1598 if (Init)
1599 Init->setVisibility(Var->getVisibility());
1600
1601 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1602 llvm::LLVMContext &Context = CGM.getModule().getContext();
1603 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1604 CGBuilderTy Builder(Entry);
1605 if (InitIsInitFunc) {
1606 if (Init)
1607 Builder.CreateCall(Init);
1608 } else {
1609 // Don't know whether we have an init function. Call it if it exists.
1610 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1611 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1612 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1613 Builder.CreateCondBr(Have, InitBB, ExitBB);
1614
1615 Builder.SetInsertPoint(InitBB);
1616 Builder.CreateCall(Init);
1617 Builder.CreateBr(ExitBB);
1618
1619 Builder.SetInsertPoint(ExitBB);
1620 }
1621
1622 // For a reference, the result of the wrapper function is a pointer to
1623 // the referenced object.
1624 llvm::Value *Val = Var;
1625 if (VD->getType()->isReferenceType()) {
1626 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1627 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1628 Val = LI;
1629 }
1630
1631 Builder.CreateRet(Val);
1632 }
1633}
1634
1635LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1636 const DeclRefExpr *DRE) {
1637 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1638 QualType T = VD->getType();
1639 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1640 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1641 llvm::Function *Wrapper =
1642 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1643
1644 Val = CGF.Builder.CreateCall(Wrapper);
1645
1646 LValue LV;
1647 if (VD->getType()->isReferenceType())
1648 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1649 else
1650 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1651 CGF.getContext().getDeclAlign(VD));
1652 // FIXME: need setObjCGCLValueClass?
1653 return LV;
1654}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001655
1656/// Return whether the given global decl needs a VTT parameter, which it does
1657/// if it's a base constructor or destructor with virtual bases.
1658bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1659 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1660
1661 // We don't have any virtual bases, just return early.
1662 if (!MD->getParent()->getNumVBases())
1663 return false;
1664
1665 // Check if we have a base constructor.
1666 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1667 return true;
1668
1669 // Check if we have a base destructor.
1670 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1671 return true;
1672
1673 return false;
1674}