blob: 2a311a0cf0c7882432674bc71ada3d78cfbc5254 [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
Rafael Espindolac3cde362013-12-09 14:51:17 +0000818 // The constructor used for constructing this as a base class;
819 // ignores virtual bases.
820 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
821
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000822 // The constructor used for constructing this as a complete class;
823 // constucts the virtual bases, then calls the base constructor.
824 if (!D->getParent()->isAbstract()) {
825 // We don't need to emit the complete ctor if the class is abstract.
826 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
827 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000828}
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) {
Rafael Espindolac3cde362013-12-09 14:51:17 +0000847 // The destructor used for destructing this as a base class; ignores
848 // virtual bases.
849 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000850
851 // The destructor used for destructing this as a most-derived class;
852 // call the base destructor and then destructs any virtual bases.
853 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
854
Rafael Espindolac3cde362013-12-09 14:51:17 +0000855 // The destructor in a virtual table is always a 'deleting'
856 // destructor, which calls the complete destructor and then uses the
857 // appropriate operator delete.
858 if (D->isVirtual())
859 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +0000860}
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);
Reid Kleckner2af6d732013-12-13 00:09:59 +0000881 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +0000882 }
883}
884
John McCall5d865c322010-08-31 07:33:07 +0000885void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
886 /// Initialize the 'this' slot.
887 EmitThisParam(CGF);
888
889 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +0000890 if (getStructorImplicitParamDecl(CGF)) {
891 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
892 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +0000893 }
John McCall5d865c322010-08-31 07:33:07 +0000894
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000895 /// If this is a function that the ABI specifies returns 'this', initialize
896 /// the return slot to 'this' at the start of the function.
897 ///
898 /// Unlike the setting of return types, this is done within the ABI
899 /// implementation instead of by clients of CGCXXABI because:
900 /// 1) getThisValue is currently protected
901 /// 2) in theory, an ABI could implement 'this' returns some other way;
902 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +0000903 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +0000904 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +0000905}
906
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000907void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000908 const CXXConstructorDecl *D,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000909 CXXCtorType Type,
910 bool ForVirtualBase, bool Delegating,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000911 llvm::Value *This,
912 CallExpr::const_arg_iterator ArgBeg,
913 CallExpr::const_arg_iterator ArgEnd) {
914 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
915 Delegating);
916 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
917 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
918
919 // FIXME: Provide a source location here.
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000920 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
921 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000922}
923
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000924void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
925 const CXXRecordDecl *RD) {
926 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
927 if (VTable->hasInitializer())
928 return;
929
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000930 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000931 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
932 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
933
934 // Create and set the initializer.
935 llvm::Constant *Init = CGVT.CreateVTableInitializer(
936 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
937 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
938 VTable->setInitializer(Init);
939
940 // Set the correct linkage.
941 VTable->setLinkage(Linkage);
942
943 // Set the right visibility.
944 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
945
946 // If this is the magic class __cxxabiv1::__fundamental_type_info,
947 // we will emit the typeinfo for the fundamental types. This is the
948 // same behaviour as GCC.
949 const DeclContext *DC = RD->getDeclContext();
950 if (RD->getIdentifier() &&
951 RD->getIdentifier()->isStr("__fundamental_type_info") &&
952 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
953 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
954 DC->getParent()->isTranslationUnit())
955 CGM.EmitFundamentalRTTIDescriptors();
956}
957
958llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
959 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
960 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
961 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
962 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
963
964 llvm::Value *VTableAddressPoint;
965 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
966 // Get the secondary vpointer index.
967 uint64_t VirtualPointerIndex =
968 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
969
970 /// Load the VTT.
971 llvm::Value *VTT = CGF.LoadCXXVTT();
972 if (VirtualPointerIndex)
973 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
974
975 // And load the address point from the VTT.
976 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
977 } else {
978 llvm::Constant *VTable =
979 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000980 uint64_t AddressPoint = CGM.getItaniumVTableContext()
981 .getVTableLayout(VTableClass)
982 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000983 VTableAddressPoint =
984 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
985 }
986
987 return VTableAddressPoint;
988}
989
990llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
991 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
992 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
993
994 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000995 uint64_t AddressPoint = CGM.getItaniumVTableContext()
996 .getVTableLayout(VTableClass)
997 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000998 llvm::Value *Indices[] = {
999 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1000 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1001 };
1002
1003 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1004}
1005
1006llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1007 CharUnits VPtrOffset) {
1008 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1009
1010 llvm::GlobalVariable *&VTable = VTables[RD];
1011 if (VTable)
1012 return VTable;
1013
1014 // Queue up this v-table for possible deferred emission.
1015 CGM.addDeferredVTable(RD);
1016
1017 SmallString<256> OutName;
1018 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001019 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001020 Out.flush();
1021 StringRef Name = OutName.str();
1022
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001023 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001024 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1025 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1026
1027 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1028 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1029 VTable->setUnnamedAddr(true);
1030 return VTable;
1031}
1032
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001033llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1034 GlobalDecl GD,
1035 llvm::Value *This,
1036 llvm::Type *Ty) {
1037 GD = GD.getCanonicalDecl();
1038 Ty = Ty->getPointerTo()->getPointerTo();
1039 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1040
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001041 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001042 llvm::Value *VFuncPtr =
1043 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1044 return CGF.Builder.CreateLoad(VFuncPtr);
1045}
1046
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001047void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1048 const CXXDestructorDecl *Dtor,
1049 CXXDtorType DtorType,
1050 SourceLocation CallLoc,
1051 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001052 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1053
1054 const CGFunctionInfo *FInfo
1055 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1056 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001057 llvm::Value *Callee =
1058 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001059
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001060 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1061 /*ImplicitParam=*/0, QualType(), 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001062}
1063
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001064void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001065 CodeGenVTables &VTables = CGM.getVTables();
1066 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001067 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001068}
1069
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001070static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1071 llvm::Value *Ptr,
1072 int64_t NonVirtualAdjustment,
1073 int64_t VirtualAdjustment,
1074 bool IsReturnAdjustment) {
1075 if (!NonVirtualAdjustment && !VirtualAdjustment)
1076 return Ptr;
1077
1078 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1079 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1080
1081 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1082 // Perform the non-virtual adjustment for a base-to-derived cast.
1083 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1084 }
1085
1086 if (VirtualAdjustment) {
1087 llvm::Type *PtrDiffTy =
1088 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1089
1090 // Perform the virtual adjustment.
1091 llvm::Value *VTablePtrPtr =
1092 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1093
1094 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1095
1096 llvm::Value *OffsetPtr =
1097 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1098
1099 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1100
1101 // Load the adjustment offset from the vtable.
1102 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1103
1104 // Adjust our pointer.
1105 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1106 }
1107
1108 if (NonVirtualAdjustment && IsReturnAdjustment) {
1109 // Perform the non-virtual adjustment for a derived-to-base cast.
1110 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1111 }
1112
1113 // Cast back to the original type.
1114 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1115}
1116
1117llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1118 llvm::Value *This,
1119 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001120 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1121 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001122 /*IsReturnAdjustment=*/false);
1123}
1124
1125llvm::Value *
1126ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1127 const ReturnAdjustment &RA) {
1128 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1129 RA.Virtual.Itanium.VBaseOffsetOffset,
1130 /*IsReturnAdjustment=*/true);
1131}
1132
John McCall5d865c322010-08-31 07:33:07 +00001133void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1134 RValue RV, QualType ResultType) {
1135 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1136 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1137
1138 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001139 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001140 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1141 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1142 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1143}
John McCall8ed55a52010-09-02 09:58:18 +00001144
1145/************************** Array allocation cookies **************************/
1146
John McCallb91cd662012-05-01 05:23:51 +00001147CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1148 // The array cookie is a size_t; pad that up to the element alignment.
1149 // The cookie is actually right-justified in that space.
1150 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1151 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001152}
1153
1154llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1155 llvm::Value *NewPtr,
1156 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001157 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001158 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001159 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001160
Micah Villmowea2fea22012-10-25 15:39:14 +00001161 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001162
John McCall9bca9232010-09-02 10:25:57 +00001163 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001164 QualType SizeTy = Ctx.getSizeType();
1165 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1166
1167 // The size of the cookie.
1168 CharUnits CookieSize =
1169 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001170 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001171
1172 // Compute an offset to the cookie.
1173 llvm::Value *CookiePtr = NewPtr;
1174 CharUnits CookieOffset = CookieSize - SizeSize;
1175 if (!CookieOffset.isZero())
1176 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1177 CookieOffset.getQuantity());
1178
1179 // Write the number of elements into the appropriate slot.
1180 llvm::Value *NumElementsPtr
1181 = CGF.Builder.CreateBitCast(CookiePtr,
1182 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1183 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1184
1185 // Finally, compute a pointer to the actual data buffer by skipping
1186 // over the cookie completely.
1187 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1188 CookieSize.getQuantity());
1189}
1190
John McCallb91cd662012-05-01 05:23:51 +00001191llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1192 llvm::Value *allocPtr,
1193 CharUnits cookieSize) {
1194 // The element size is right-justified in the cookie.
1195 llvm::Value *numElementsPtr = allocPtr;
1196 CharUnits numElementsOffset =
1197 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1198 if (!numElementsOffset.isZero())
1199 numElementsPtr =
1200 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1201 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001202
Micah Villmowea2fea22012-10-25 15:39:14 +00001203 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001204 numElementsPtr =
1205 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1206 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001207}
1208
John McCallb91cd662012-05-01 05:23:51 +00001209CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001210 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001211 // struct array_cookie {
1212 // std::size_t element_size; // element_size != 0
1213 // std::size_t element_count;
1214 // };
John McCallc19c7062013-01-25 23:36:19 +00001215 // But the base ABI doesn't give anything an alignment greater than
1216 // 8, so we can dismiss this as typical ABI-author blindness to
1217 // actual language complexity and round up to the element alignment.
1218 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1219 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001220}
1221
1222llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001223 llvm::Value *newPtr,
1224 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001225 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001226 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001227 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001228
John McCallc19c7062013-01-25 23:36:19 +00001229 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1230 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001231
1232 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001233 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001234
1235 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001236 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1237 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1238 getContext().getTypeSizeInChars(elementType).getQuantity());
1239 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001240
1241 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001242 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1243 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001244
1245 // Finally, compute a pointer to the actual data buffer by skipping
1246 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001247 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1248 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1249 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001250}
1251
John McCallb91cd662012-05-01 05:23:51 +00001252llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1253 llvm::Value *allocPtr,
1254 CharUnits cookieSize) {
1255 // The number of elements is at offset sizeof(size_t) relative to
1256 // the allocated pointer.
1257 llvm::Value *numElementsPtr
1258 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001259
Micah Villmowea2fea22012-10-25 15:39:14 +00001260 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001261 numElementsPtr =
1262 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1263 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001264}
1265
John McCall68ff0372010-09-08 01:44:27 +00001266/*********************** Static local initialization **************************/
1267
1268static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001269 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001270 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001271 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001272 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001273 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001274 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001275 llvm::AttributeSet::get(CGM.getLLVMContext(),
1276 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001277 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001278}
1279
1280static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001281 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001282 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001283 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001284 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001285 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001286 llvm::AttributeSet::get(CGM.getLLVMContext(),
1287 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001288 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001289}
1290
1291static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001292 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001293 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001294 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001295 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001296 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001297 llvm::AttributeSet::get(CGM.getLLVMContext(),
1298 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001299 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001300}
1301
1302namespace {
1303 struct CallGuardAbort : EHScopeStack::Cleanup {
1304 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001305 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001306
John McCall30317fd2011-07-12 20:27:29 +00001307 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall882987f2013-02-28 19:01:20 +00001308 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1309 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001310 }
1311 };
1312}
1313
1314/// The ARM code here follows the Itanium code closely enough that we
1315/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001316void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1317 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001318 llvm::GlobalVariable *var,
1319 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001320 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001321
Richard Smithdbf74ba2013-04-14 23:01:42 +00001322 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001323 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001324 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1325 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001326
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001327 // If we have a global variable with internal linkage and thread-safe statics
1328 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001329 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1330
1331 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001332 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001333 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001334 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001335 // Guard variables are 64 bits in the generic ABI and size width on ARM
1336 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001337 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001338 }
John McCallb88a5662012-03-30 21:00:39 +00001339 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001340
John McCallb88a5662012-03-30 21:00:39 +00001341 // Create the guard variable if we don't already have it (as we
1342 // might if we're double-emitting this function body).
1343 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1344 if (!guard) {
1345 // Mangle the name for the guard.
1346 SmallString<256> guardName;
1347 {
1348 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001349 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001350 out.flush();
1351 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001352
John McCallb88a5662012-03-30 21:00:39 +00001353 // Create the guard variable with a zero-initializer.
1354 // Just absorb linkage and visibility from the guarded variable.
1355 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1356 false, var->getLinkage(),
1357 llvm::ConstantInt::get(guardTy, 0),
1358 guardName.str());
1359 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001360 // If the variable is thread-local, so is its guard variable.
1361 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001362
1363 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1364 }
John McCall87590e62012-03-30 07:09:50 +00001365
John McCall68ff0372010-09-08 01:44:27 +00001366 // Test whether the variable has completed initialization.
John McCallb88a5662012-03-30 21:00:39 +00001367 llvm::Value *isInitialized;
John McCall68ff0372010-09-08 01:44:27 +00001368
1369 // ARM C++ ABI 3.2.3.1:
1370 // To support the potential use of initialization guard variables
1371 // as semaphores that are the target of ARM SWP and LDREX/STREX
1372 // synchronizing instructions we define a static initialization
1373 // guard variable to be a 4-byte aligned, 4- byte word with the
1374 // following inline access protocol.
1375 // #define INITIALIZED 1
1376 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1377 // if (__cxa_guard_acquire(&obj_guard))
1378 // ...
1379 // }
Mark Seabornedf0d382013-07-24 16:25:13 +00001380 if (UseARMGuardVarABI && !useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001381 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northover9bb857a2013-01-31 12:13:10 +00001382 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1383 V = Builder.CreateAnd(V, Test1);
John McCallb88a5662012-03-30 21:00:39 +00001384 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001385
1386 // Itanium C++ ABI 3.3.2:
1387 // The following is pseudo-code showing how these functions can be used:
1388 // if (obj_guard.first_byte == 0) {
1389 // if ( __cxa_guard_acquire (&obj_guard) ) {
1390 // try {
1391 // ... initialize the object ...;
1392 // } catch (...) {
1393 // __cxa_guard_abort (&obj_guard);
1394 // throw;
1395 // }
1396 // ... queue object destructor with __cxa_atexit() ...;
1397 // __cxa_guard_release (&obj_guard);
1398 // }
1399 // }
1400 } else {
1401 // Load the first byte of the guard variable.
Chandler Carruth84537952012-03-30 19:44:53 +00001402 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001403 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth84537952012-03-30 19:44:53 +00001404 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001405
Eli Friedman84d28122011-09-13 22:21:56 +00001406 // Itanium ABI:
1407 // An implementation supporting thread-safety on multiprocessor
1408 // systems must also guarantee that references to the initialized
1409 // object do not occur before the load of the initialization flag.
1410 //
1411 // In LLVM, we do this by marking the load Acquire.
1412 if (threadsafe)
Chandler Carruth84537952012-03-30 19:44:53 +00001413 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001414
John McCallb88a5662012-03-30 21:00:39 +00001415 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001416 }
1417
1418 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1419 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1420
1421 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001422 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001423
1424 CGF.EmitBlock(InitCheckBlock);
1425
1426 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001427 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001428 // Call __cxa_guard_acquire.
1429 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001430 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001431
1432 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1433
1434 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1435 InitBlock, EndBlock);
1436
1437 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001438 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001439
1440 CGF.EmitBlock(InitBlock);
1441 }
1442
1443 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001444 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001445
John McCall5aa52592011-06-17 07:33:57 +00001446 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001447 // Pop the guard-abort cleanup if we pushed one.
1448 CGF.PopCleanupBlock();
1449
1450 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001451 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001452 } else {
John McCallb88a5662012-03-30 21:00:39 +00001453 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001454 }
1455
1456 CGF.EmitBlock(EndBlock);
1457}
John McCallc84ed6a2012-05-01 06:13:13 +00001458
1459/// Register a global destructor using __cxa_atexit.
1460static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1461 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001462 llvm::Constant *addr,
1463 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001464 const char *Name = "__cxa_atexit";
1465 if (TLS) {
1466 const llvm::Triple &T = CGF.getTarget().getTriple();
1467 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1468 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001469
John McCallc84ed6a2012-05-01 06:13:13 +00001470 // We're assuming that the destructor function is something we can
1471 // reasonably call with the default CC. Go ahead and cast it to the
1472 // right prototype.
1473 llvm::Type *dtorTy =
1474 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1475
1476 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1477 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1478 llvm::FunctionType *atexitTy =
1479 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1480
1481 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001482 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001483 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1484 fn->setDoesNotThrow();
1485
1486 // Create a variable that binds the atexit to this shared object.
1487 llvm::Constant *handle =
1488 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1489
1490 llvm::Value *args[] = {
1491 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1492 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1493 handle
1494 };
John McCall882987f2013-02-28 19:01:20 +00001495 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001496}
1497
1498/// Register a global destructor as best as we know how.
1499void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001500 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001501 llvm::Constant *dtor,
1502 llvm::Constant *addr) {
1503 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001504 if (CGM.getCodeGenOpts().CXAAtExit)
1505 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1506
1507 if (D.getTLSKind())
1508 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001509
1510 // In Apple kexts, we want to add a global destructor entry.
1511 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001512 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001513 // Generate a global destructor entry.
1514 return CGM.AddCXXDtorEntry(dtor, addr);
1515 }
1516
David Blaikieebe87e12013-08-27 23:57:18 +00001517 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001518}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001519
1520/// Get the appropriate linkage for the wrapper function. This is essentially
1521/// the weak form of the variable's linkage; every translation unit which wneeds
1522/// the wrapper emits a copy, and we want the linker to merge them.
1523static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1524 llvm::GlobalValue::LinkageTypes VarLinkage) {
1525 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1526 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1527 // For internal linkage variables, we don't need an external or weak wrapper.
1528 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1529 return VarLinkage;
1530 return llvm::GlobalValue::WeakODRLinkage;
1531}
1532
1533llvm::Function *
1534ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1535 llvm::GlobalVariable *Var) {
1536 // Mangle the name for the thread_local wrapper function.
1537 SmallString<256> WrapperName;
1538 {
1539 llvm::raw_svector_ostream Out(WrapperName);
1540 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1541 Out.flush();
1542 }
1543
1544 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1545 return cast<llvm::Function>(V);
1546
1547 llvm::Type *RetTy = Var->getType();
1548 if (VD->getType()->isReferenceType())
1549 RetTy = RetTy->getPointerElementType();
1550
1551 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1552 llvm::Function *Wrapper = llvm::Function::Create(
1553 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1554 &CGM.getModule());
1555 // Always resolve references to the wrapper at link time.
1556 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1557 return Wrapper;
1558}
1559
1560void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1561 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1562 llvm::Function *InitFunc) {
1563 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1564 const VarDecl *VD = Decls[I].first;
1565 llvm::GlobalVariable *Var = Decls[I].second;
1566
1567 // Mangle the name for the thread_local initialization function.
1568 SmallString<256> InitFnName;
1569 {
1570 llvm::raw_svector_ostream Out(InitFnName);
1571 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1572 Out.flush();
1573 }
1574
1575 // If we have a definition for the variable, emit the initialization
1576 // function as an alias to the global Init function (if any). Otherwise,
1577 // produce a declaration of the initialization function.
1578 llvm::GlobalValue *Init = 0;
1579 bool InitIsInitFunc = false;
1580 if (VD->hasDefinition()) {
1581 InitIsInitFunc = true;
1582 if (InitFunc)
1583 Init =
1584 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1585 InitFnName.str(), InitFunc, &CGM.getModule());
1586 } else {
1587 // Emit a weak global function referring to the initialization function.
1588 // This function will not exist if the TU defining the thread_local
1589 // variable in question does not need any dynamic initialization for
1590 // its thread_local variables.
1591 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1592 Init = llvm::Function::Create(
1593 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1594 &CGM.getModule());
1595 }
1596
1597 if (Init)
1598 Init->setVisibility(Var->getVisibility());
1599
1600 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1601 llvm::LLVMContext &Context = CGM.getModule().getContext();
1602 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1603 CGBuilderTy Builder(Entry);
1604 if (InitIsInitFunc) {
1605 if (Init)
1606 Builder.CreateCall(Init);
1607 } else {
1608 // Don't know whether we have an init function. Call it if it exists.
1609 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1610 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1611 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1612 Builder.CreateCondBr(Have, InitBB, ExitBB);
1613
1614 Builder.SetInsertPoint(InitBB);
1615 Builder.CreateCall(Init);
1616 Builder.CreateBr(ExitBB);
1617
1618 Builder.SetInsertPoint(ExitBB);
1619 }
1620
1621 // For a reference, the result of the wrapper function is a pointer to
1622 // the referenced object.
1623 llvm::Value *Val = Var;
1624 if (VD->getType()->isReferenceType()) {
1625 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1626 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1627 Val = LI;
1628 }
1629
1630 Builder.CreateRet(Val);
1631 }
1632}
1633
1634LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1635 const DeclRefExpr *DRE) {
1636 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1637 QualType T = VD->getType();
1638 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1639 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1640 llvm::Function *Wrapper =
1641 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1642
1643 Val = CGF.Builder.CreateCall(Wrapper);
1644
1645 LValue LV;
1646 if (VD->getType()->isReferenceType())
1647 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1648 else
1649 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1650 CGF.getContext().getDeclAlign(VD));
1651 // FIXME: need setObjCGCLValueClass?
1652 return LV;
1653}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001654
1655/// Return whether the given global decl needs a VTT parameter, which it does
1656/// if it's a base constructor or destructor with virtual bases.
1657bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1658 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1659
1660 // We don't have any virtual bases, just return early.
1661 if (!MD->getParent()->getNumVBases())
1662 return false;
1663
1664 // Check if we have a base constructor.
1665 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1666 return true;
1667
1668 // Check if we have a base destructor.
1669 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1670 return true;
1671
1672 return false;
1673}