blob: 1952ee6012f6f023d86c7793b996b387ac0f8383 [file] [log] [blame]
Charles Davis3a811f12010-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 Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis3a811f12010-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 McCallee79a4c2010-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 Davis3a811f12010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
John McCall0bab0cd2010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davis9ee494f2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall93d557b2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis3a811f12010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Craig Topperba77cb92012-09-15 18:47:51 +000026#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Value.h"
Charles Davis3a811f12010-05-25 19:52:27 +000031
32using namespace clang;
John McCall93d557b2010-08-22 00:05:51 +000033using namespace CodeGen;
Charles Davis3a811f12010-05-25 19:52:27 +000034
35namespace {
Charles Davis071cc7d2010-08-16 03:33:14 +000036class ItaniumCXXABI : public CodeGen::CGCXXABI {
John McCall93d557b2010-08-22 00:05:51 +000037protected:
John McCallbabc9a92010-08-22 00:59:17 +000038 bool IsARM;
John McCall0bab0cd2010-08-23 01:21:21 +000039
Charles Davis3a811f12010-05-25 19:52:27 +000040public:
John McCallbabc9a92010-08-22 00:59:17 +000041 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
Reid Kleckner92e44d92013-03-22 16:13:10 +000042 CGCXXABI(CGM), IsARM(IsARM) { }
John McCall93d557b2010-08-22 00:05:51 +000043
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000044 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
45 // Structures with either a non-trivial destructor or a non-trivial
46 // copy constructor are always indirect.
47 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
48 }
49
50 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
51 // Structures with either a non-trivial destructor or a non-trivial
52 // copy constructor are always indirect.
53 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
54 return RAA_Indirect;
55 return RAA_Default;
56 }
57
John McCallf16aa102010-08-22 21:01:12 +000058 bool isZeroInitializable(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000059
Chris Lattner9cbe4f02011-07-09 17:41:47 +000060 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
John McCall0bab0cd2010-08-23 01:21:21 +000061
John McCall93d557b2010-08-22 00:05:51 +000062 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
63 llvm::Value *&This,
64 llvm::Value *MemFnPtr,
65 const MemberPointerType *MPT);
John McCall3023def2010-08-22 03:04:22 +000066
John McCall6c2ab1d2010-08-31 21:07:20 +000067 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
68 llvm::Value *Base,
69 llvm::Value *MemPtr,
70 const MemberPointerType *MPT);
71
John McCall0bab0cd2010-08-23 01:21:21 +000072 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
73 const CastExpr *E,
74 llvm::Value *Src);
John McCall4d4e5c12012-02-15 01:22:51 +000075 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
76 llvm::Constant *Src);
John McCallcf2c85e2010-08-22 04:16:24 +000077
John McCall0bab0cd2010-08-23 01:21:21 +000078 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
John McCallcf2c85e2010-08-22 04:16:24 +000079
John McCall755d8492011-04-12 00:42:48 +000080 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
John McCall5808ce42011-02-03 08:15:49 +000081 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
82 CharUnits offset);
Richard Smith2d6a5672012-01-14 04:30:29 +000083 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
84 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
85 CharUnits ThisAdjustment);
John McCall875ab102010-08-22 06:43:33 +000086
John McCall0bab0cd2010-08-23 01:21:21 +000087 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
88 llvm::Value *L,
89 llvm::Value *R,
90 const MemberPointerType *MPT,
91 bool Inequality);
John McCalle9fd7eb2010-08-22 08:30:07 +000092
John McCall0bab0cd2010-08-23 01:21:21 +000093 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
94 llvm::Value *Addr,
95 const MemberPointerType *MPT);
John McCall4c40d982010-08-31 07:33:07 +000096
John McCallecd03b42012-09-25 10:10:39 +000097 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
98 llvm::Value *ptr,
99 QualType type);
100
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000101 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
102 llvm::Value *This,
103 const CXXRecordDecl *ClassDecl,
104 const CXXRecordDecl *BaseClassDecl);
105
John McCall4c40d982010-08-31 07:33:07 +0000106 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
107 CXXCtorType T,
108 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000109 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000110
111 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
112 CXXDtorType T,
113 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000114 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000115
116 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
117 QualType &ResTy,
118 FunctionArgList &Params);
119
120 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall1e7fe752010-09-02 09:58:18 +0000121
Stephen Lind4c0cd02013-06-18 17:00:49 +0000122 RValue EmitConstructorCall(CodeGenFunction &CGF,
123 const CXXConstructorDecl *D,
124 CXXCtorType Type,
125 bool ForVirtualBase, bool Delegating,
126 ReturnValueSlot ReturnValue,
127 llvm::Value *This,
128 CallExpr::const_arg_iterator ArgBeg,
129 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000130
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000131 RValue EmitVirtualDestructorCall(CodeGenFunction &CGF,
132 const CXXDestructorDecl *Dtor,
133 CXXDtorType DtorType,
134 SourceLocation CallLoc,
135 ReturnValueSlot ReturnValue,
136 llvm::Value *This);
137
Reid Kleckner90633022013-06-19 15:20:38 +0000138 void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage,
139 const CXXRecordDecl *RD);
140
Joao Matos285baac2012-07-17 17:10:11 +0000141 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
David Blaikie2eb9a952012-10-16 22:56:05 +0000142 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
Joao Matos285baac2012-07-17 17:10:11 +0000143
John McCalle2b45e22012-05-01 05:23:51 +0000144 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000145 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
146 llvm::Value *NewPtr,
147 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000148 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000149 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000150 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
151 llvm::Value *allocPtr,
152 CharUnits cookieSize);
John McCall5cd91b52010-09-08 01:44:27 +0000153
John McCall3030eb82010-11-06 09:44:32 +0000154 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000155 llvm::GlobalVariable *DeclPtr, bool PerformInit);
Richard Smith04e51762013-04-14 23:01:42 +0000156 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
157 llvm::Constant *dtor, llvm::Constant *addr);
Richard Smithb80a16e2013-04-19 16:42:07 +0000158
159 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
160 llvm::GlobalVariable *Var);
161 void EmitThreadLocalInitFuncs(
162 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
163 llvm::Function *InitFunc);
164 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
165 const DeclRefExpr *DRE);
Charles Davis3a811f12010-05-25 19:52:27 +0000166};
John McCallee79a4c2010-08-21 22:46:04 +0000167
168class ARMCXXABI : public ItaniumCXXABI {
169public:
John McCallbabc9a92010-08-22 00:59:17 +0000170 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
John McCall4c40d982010-08-31 07:33:07 +0000171
Stephen Lind4c0cd02013-06-18 17:00:49 +0000172 bool HasThisReturn(GlobalDecl GD) const {
173 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
174 isa<CXXDestructorDecl>(GD.getDecl()) &&
175 GD.getDtorType() != Dtor_Deleting));
176 }
John McCall4c40d982010-08-31 07:33:07 +0000177
178 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
179
John McCalle2b45e22012-05-01 05:23:51 +0000180 CharUnits getArrayCookieSizeImpl(QualType elementType);
John McCall1e7fe752010-09-02 09:58:18 +0000181 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
182 llvm::Value *NewPtr,
183 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000184 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000185 QualType ElementType);
John McCalle2b45e22012-05-01 05:23:51 +0000186 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
187 CharUnits cookieSize);
John McCallee79a4c2010-08-21 22:46:04 +0000188};
Charles Davis3a811f12010-05-25 19:52:27 +0000189}
190
Charles Davis071cc7d2010-08-16 03:33:14 +0000191CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +0000192 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall96fcde02013-01-25 23:36:14 +0000193 // For IR-generation purposes, there's no significant difference
194 // between the ARM and iOS ABIs.
195 case TargetCXXABI::GenericARM:
196 case TargetCXXABI::iOS:
197 return new ARMCXXABI(CGM);
Charles Davis3a811f12010-05-25 19:52:27 +0000198
Tim Northoverc264e162013-01-31 12:13:10 +0000199 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
200 // include the other 32-bit ARM oddities: constructor/destructor return values
201 // and array cookies.
202 case TargetCXXABI::GenericAArch64:
203 return new ItaniumCXXABI(CGM, /*IsARM = */ true);
204
John McCall96fcde02013-01-25 23:36:14 +0000205 case TargetCXXABI::GenericItanium:
206 return new ItaniumCXXABI(CGM);
207
208 case TargetCXXABI::Microsoft:
209 llvm_unreachable("Microsoft ABI is not Itanium-based");
210 }
211 llvm_unreachable("bad ABI kind");
John McCallee79a4c2010-08-21 22:46:04 +0000212}
213
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000214llvm::Type *
John McCall0bab0cd2010-08-23 01:21:21 +0000215ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
216 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000217 return CGM.PtrDiffTy;
218 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall875ab102010-08-22 06:43:33 +0000219}
220
John McCallbabc9a92010-08-22 00:59:17 +0000221/// In the Itanium and ARM ABIs, method pointers have the form:
222/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
223///
224/// In the Itanium ABI:
225/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
226/// - the this-adjustment is (memptr.adj)
227/// - the virtual offset is (memptr.ptr - 1)
228///
229/// In the ARM ABI:
230/// - method pointers are virtual if (memptr.adj & 1) is nonzero
231/// - the this-adjustment is (memptr.adj >> 1)
232/// - the virtual offset is (memptr.ptr)
233/// ARM uses 'adj' for the virtual flag because Thumb functions
234/// may be only single-byte aligned.
235///
236/// If the member is virtual, the adjusted 'this' pointer points
237/// to a vtable pointer from which the virtual offset is applied.
238///
239/// If the member is non-virtual, memptr.ptr is the address of
240/// the function to call.
John McCall93d557b2010-08-22 00:05:51 +0000241llvm::Value *
242ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
243 llvm::Value *&This,
244 llvm::Value *MemFnPtr,
245 const MemberPointerType *MPT) {
246 CGBuilderTy &Builder = CGF.Builder;
247
248 const FunctionProtoType *FPT =
249 MPT->getPointeeType()->getAs<FunctionProtoType>();
250 const CXXRecordDecl *RD =
251 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
252
Chris Lattner2acc6e32011-07-18 04:24:23 +0000253 llvm::FunctionType *FTy =
John McCallde5d3c72012-02-17 03:33:10 +0000254 CGM.getTypes().GetFunctionType(
255 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall93d557b2010-08-22 00:05:51 +0000256
Reid Kleckner92e44d92013-03-22 16:13:10 +0000257 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall93d557b2010-08-22 00:05:51 +0000258
John McCallbabc9a92010-08-22 00:59:17 +0000259 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
260 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
261 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
262
John McCalld608cdb2010-08-22 10:59:02 +0000263 // Extract memptr.adj, which is in the second field.
264 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCallbabc9a92010-08-22 00:59:17 +0000265
266 // Compute the true adjustment.
267 llvm::Value *Adj = RawAdj;
268 if (IsARM)
269 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall93d557b2010-08-22 00:05:51 +0000270
271 // Apply the adjustment and cast back to the original struct type
272 // for consistency.
John McCallbabc9a92010-08-22 00:59:17 +0000273 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
274 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
275 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall93d557b2010-08-22 00:05:51 +0000276
277 // Load the function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000278 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall93d557b2010-08-22 00:05:51 +0000279
280 // If the LSB in the function pointer is 1, the function pointer points to
281 // a virtual function.
John McCallbabc9a92010-08-22 00:59:17 +0000282 llvm::Value *IsVirtual;
283 if (IsARM)
284 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
285 else
286 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
287 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall93d557b2010-08-22 00:05:51 +0000288 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
289
290 // In the virtual path, the adjustment left 'This' pointing to the
291 // vtable of the correct base subobject. The "function pointer" is an
John McCallbabc9a92010-08-22 00:59:17 +0000292 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall93d557b2010-08-22 00:05:51 +0000293 CGF.EmitBlock(FnVirtual);
294
295 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000296 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall93d557b2010-08-22 00:05:51 +0000297 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000298 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
John McCall93d557b2010-08-22 00:05:51 +0000299
300 // Apply the offset.
John McCallbabc9a92010-08-22 00:59:17 +0000301 llvm::Value *VTableOffset = FnAsInt;
302 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
303 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall93d557b2010-08-22 00:05:51 +0000304
305 // Load the virtual function to call.
306 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCallbabc9a92010-08-22 00:59:17 +0000307 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000308 CGF.EmitBranch(FnEnd);
309
310 // In the non-virtual path, the function pointer is actually a
311 // function pointer.
312 CGF.EmitBlock(FnNonVirtual);
313 llvm::Value *NonVirtualFn =
John McCallbabc9a92010-08-22 00:59:17 +0000314 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall93d557b2010-08-22 00:05:51 +0000315
316 // We're done.
317 CGF.EmitBlock(FnEnd);
Jay Foadbbf3bac2011-03-30 11:28:58 +0000318 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall93d557b2010-08-22 00:05:51 +0000319 Callee->addIncoming(VirtualFn, FnVirtual);
320 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
321 return Callee;
322}
John McCall3023def2010-08-22 03:04:22 +0000323
John McCall6c2ab1d2010-08-31 21:07:20 +0000324/// Compute an l-value by applying the given pointer-to-member to a
325/// base object.
326llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
327 llvm::Value *Base,
328 llvm::Value *MemPtr,
329 const MemberPointerType *MPT) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000330 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall6c2ab1d2010-08-31 21:07:20 +0000331
332 CGBuilderTy &Builder = CGF.Builder;
333
Micah Villmow956a5a12012-10-25 15:39:14 +0000334 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCall6c2ab1d2010-08-31 21:07:20 +0000335
336 // Cast to char*.
337 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
338
339 // Apply the offset, which we assume is non-null.
340 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
341
342 // Cast the address to the appropriate pointer type, adopting the
343 // address space of the base pointer.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000344 llvm::Type *PType
Douglas Gregoreede61a2010-09-02 17:38:50 +0000345 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCall6c2ab1d2010-08-31 21:07:20 +0000346 return Builder.CreateBitCast(Addr, PType);
347}
348
John McCall4d4e5c12012-02-15 01:22:51 +0000349/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
350/// conversion.
351///
352/// Bitcast conversions are always a no-op under Itanium.
John McCall0bab0cd2010-08-23 01:21:21 +0000353///
354/// Obligatory offset/adjustment diagram:
355/// <-- offset --> <-- adjustment -->
356/// |--------------------------|----------------------|--------------------|
357/// ^Derived address point ^Base address point ^Member address point
358///
359/// So when converting a base member pointer to a derived member pointer,
360/// we add the offset to the adjustment because the address point has
361/// decreased; and conversely, when converting a derived MP to a base MP
362/// we subtract the offset from the adjustment because the address point
363/// has increased.
364///
365/// The standard forbids (at compile time) conversion to and from
366/// virtual bases, which is why we don't have to consider them here.
367///
368/// The standard forbids (at run time) casting a derived MP to a base
369/// MP when the derived MP does not point to a member of the base.
370/// This is why -1 is a reasonable choice for null data member
371/// pointers.
John McCalld608cdb2010-08-22 10:59:02 +0000372llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000373ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
374 const CastExpr *E,
John McCall4d4e5c12012-02-15 01:22:51 +0000375 llvm::Value *src) {
John McCall2de56d12010-08-25 11:45:40 +0000376 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCall4d4e5c12012-02-15 01:22:51 +0000377 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
378 E->getCastKind() == CK_ReinterpretMemberPointer);
379
380 // Under Itanium, reinterprets don't require any additional processing.
381 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
382
383 // Use constant emission if we can.
384 if (isa<llvm::Constant>(src))
385 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
386
387 llvm::Constant *adj = getMemberPointerAdjustment(E);
388 if (!adj) return src;
John McCall3023def2010-08-22 03:04:22 +0000389
390 CGBuilderTy &Builder = CGF.Builder;
John McCall4d4e5c12012-02-15 01:22:51 +0000391 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCall3023def2010-08-22 03:04:22 +0000392
John McCall4d4e5c12012-02-15 01:22:51 +0000393 const MemberPointerType *destTy =
394 E->getType()->castAs<MemberPointerType>();
John McCall875ab102010-08-22 06:43:33 +0000395
John McCall0bab0cd2010-08-23 01:21:21 +0000396 // For member data pointers, this is just a matter of adding the
397 // offset if the source is non-null.
John McCall4d4e5c12012-02-15 01:22:51 +0000398 if (destTy->isMemberDataPointer()) {
399 llvm::Value *dst;
400 if (isDerivedToBase)
401 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000402 else
John McCall4d4e5c12012-02-15 01:22:51 +0000403 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall0bab0cd2010-08-23 01:21:21 +0000404
405 // Null check.
John McCall4d4e5c12012-02-15 01:22:51 +0000406 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
407 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
408 return Builder.CreateSelect(isNull, src, dst);
John McCall0bab0cd2010-08-23 01:21:21 +0000409 }
410
John McCalld608cdb2010-08-22 10:59:02 +0000411 // The this-adjustment is left-shifted by 1 on ARM.
412 if (IsARM) {
John McCall4d4e5c12012-02-15 01:22:51 +0000413 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
414 offset <<= 1;
415 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalld608cdb2010-08-22 10:59:02 +0000416 }
417
John McCall4d4e5c12012-02-15 01:22:51 +0000418 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
419 llvm::Value *dstAdj;
420 if (isDerivedToBase)
421 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000422 else
John McCall4d4e5c12012-02-15 01:22:51 +0000423 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalld608cdb2010-08-22 10:59:02 +0000424
John McCall4d4e5c12012-02-15 01:22:51 +0000425 return Builder.CreateInsertValue(src, dstAdj, 1);
426}
427
428llvm::Constant *
429ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
430 llvm::Constant *src) {
431 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
432 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
433 E->getCastKind() == CK_ReinterpretMemberPointer);
434
435 // Under Itanium, reinterprets don't require any additional processing.
436 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
437
438 // If the adjustment is trivial, we don't need to do anything.
439 llvm::Constant *adj = getMemberPointerAdjustment(E);
440 if (!adj) return src;
441
442 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
443
444 const MemberPointerType *destTy =
445 E->getType()->castAs<MemberPointerType>();
446
447 // For member data pointers, this is just a matter of adding the
448 // offset if the source is non-null.
449 if (destTy->isMemberDataPointer()) {
450 // null maps to null.
451 if (src->isAllOnesValue()) return src;
452
453 if (isDerivedToBase)
454 return llvm::ConstantExpr::getNSWSub(src, adj);
455 else
456 return llvm::ConstantExpr::getNSWAdd(src, adj);
457 }
458
459 // The this-adjustment is left-shifted by 1 on ARM.
460 if (IsARM) {
461 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
462 offset <<= 1;
463 adj = llvm::ConstantInt::get(adj->getType(), offset);
464 }
465
466 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
467 llvm::Constant *dstAdj;
468 if (isDerivedToBase)
469 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
470 else
471 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
472
473 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCall3023def2010-08-22 03:04:22 +0000474}
John McCallcf2c85e2010-08-22 04:16:24 +0000475
476llvm::Constant *
John McCall0bab0cd2010-08-23 01:21:21 +0000477ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall0bab0cd2010-08-23 01:21:21 +0000478 // Itanium C++ ABI 2.3:
479 // A NULL pointer is represented as -1.
480 if (MPT->isMemberDataPointer())
Reid Kleckner92e44d92013-03-22 16:13:10 +0000481 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalld608cdb2010-08-22 10:59:02 +0000482
Reid Kleckner92e44d92013-03-22 16:13:10 +0000483 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalld608cdb2010-08-22 10:59:02 +0000484 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000485 return llvm::ConstantStruct::getAnon(Values);
John McCallcf2c85e2010-08-22 04:16:24 +0000486}
487
John McCall5808ce42011-02-03 08:15:49 +0000488llvm::Constant *
489ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
490 CharUnits offset) {
John McCall0bab0cd2010-08-23 01:21:21 +0000491 // Itanium C++ ABI 2.3:
492 // A pointer to data member is an offset from the base address of
493 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner92e44d92013-03-22 16:13:10 +0000494 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall0bab0cd2010-08-23 01:21:21 +0000495}
496
John McCall755d8492011-04-12 00:42:48 +0000497llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000498 return BuildMemberPointer(MD, CharUnits::Zero());
499}
500
501llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
502 CharUnits ThisAdjustment) {
John McCalld608cdb2010-08-22 10:59:02 +0000503 assert(MD->isInstance() && "Member function must not be static!");
504 MD = MD->getCanonicalDecl();
505
506 CodeGenTypes &Types = CGM.getTypes();
John McCalld608cdb2010-08-22 10:59:02 +0000507
508 // Get the function pointer (or index if this is a virtual function).
509 llvm::Constant *MemPtr[2];
510 if (MD->isVirtual()) {
Peter Collingbourne1d2b3172011-09-26 01:56:30 +0000511 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
John McCalld608cdb2010-08-22 10:59:02 +0000512
Ken Dyck1246ba62011-04-09 01:30:02 +0000513 const ASTContext &Context = getContext();
514 CharUnits PointerWidth =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000515 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyck1246ba62011-04-09 01:30:02 +0000516 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000517
518 if (IsARM) {
519 // ARM C++ ABI 3.2.1:
520 // This ABI specifies that adj contains twice the this
521 // adjustment, plus 1 if the member function is virtual. The
522 // least significant bit of adj then makes exactly the same
523 // discrimination as the least significant bit of ptr does for
524 // Itanium.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000525 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
526 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000527 2 * ThisAdjustment.getQuantity() + 1);
John McCalld608cdb2010-08-22 10:59:02 +0000528 } else {
529 // Itanium C++ ABI 2.3:
530 // For a virtual function, [the pointer field] is 1 plus the
531 // virtual table offset (in bytes) of the function,
532 // represented as a ptrdiff_t.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000533 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
534 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smith2d6a5672012-01-14 04:30:29 +0000535 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000536 }
537 } else {
John McCall755d8492011-04-12 00:42:48 +0000538 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000539 llvm::Type *Ty;
John McCall755d8492011-04-12 00:42:48 +0000540 // Check whether the function has a computable LLVM signature.
Chris Lattnerf742eb02011-07-10 00:18:59 +0000541 if (Types.isFuncTypeConvertible(FPT)) {
John McCall755d8492011-04-12 00:42:48 +0000542 // The function has a computable LLVM signature; use the correct type.
John McCallde5d3c72012-02-17 03:33:10 +0000543 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalld608cdb2010-08-22 10:59:02 +0000544 } else {
John McCall755d8492011-04-12 00:42:48 +0000545 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
546 // function type is incomplete.
Reid Kleckner92e44d92013-03-22 16:13:10 +0000547 Ty = CGM.PtrDiffTy;
John McCalld608cdb2010-08-22 10:59:02 +0000548 }
John McCall755d8492011-04-12 00:42:48 +0000549 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalld608cdb2010-08-22 10:59:02 +0000550
Reid Kleckner92e44d92013-03-22 16:13:10 +0000551 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
552 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, (IsARM ? 2 : 1) *
Richard Smith2d6a5672012-01-14 04:30:29 +0000553 ThisAdjustment.getQuantity());
John McCalld608cdb2010-08-22 10:59:02 +0000554 }
John McCall875ab102010-08-22 06:43:33 +0000555
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000556 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall875ab102010-08-22 06:43:33 +0000557}
558
Richard Smith2d6a5672012-01-14 04:30:29 +0000559llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
560 QualType MPType) {
561 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
562 const ValueDecl *MPD = MP.getMemberPointerDecl();
563 if (!MPD)
564 return EmitNullMemberPointer(MPT);
565
Reid Klecknerf6327302013-05-09 21:01:17 +0000566 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smith2d6a5672012-01-14 04:30:29 +0000567
568 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
569 return BuildMemberPointer(MD, ThisAdjustment);
570
571 CharUnits FieldOffset =
572 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
573 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
574}
575
John McCalle9fd7eb2010-08-22 08:30:07 +0000576/// The comparison algorithm is pretty easy: the member pointers are
577/// the same if they're either bitwise identical *or* both null.
578///
579/// ARM is different here only because null-ness is more complicated.
580llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000581ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
582 llvm::Value *L,
583 llvm::Value *R,
584 const MemberPointerType *MPT,
585 bool Inequality) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000586 CGBuilderTy &Builder = CGF.Builder;
587
John McCalle9fd7eb2010-08-22 08:30:07 +0000588 llvm::ICmpInst::Predicate Eq;
589 llvm::Instruction::BinaryOps And, Or;
590 if (Inequality) {
591 Eq = llvm::ICmpInst::ICMP_NE;
592 And = llvm::Instruction::Or;
593 Or = llvm::Instruction::And;
594 } else {
595 Eq = llvm::ICmpInst::ICMP_EQ;
596 And = llvm::Instruction::And;
597 Or = llvm::Instruction::Or;
598 }
599
John McCall0bab0cd2010-08-23 01:21:21 +0000600 // Member data pointers are easy because there's a unique null
601 // value, so it just comes down to bitwise equality.
602 if (MPT->isMemberDataPointer())
603 return Builder.CreateICmp(Eq, L, R);
604
605 // For member function pointers, the tautologies are more complex.
606 // The Itanium tautology is:
John McCallde719f72010-08-23 06:56:36 +0000607 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall0bab0cd2010-08-23 01:21:21 +0000608 // The ARM tautology is:
John McCallde719f72010-08-23 06:56:36 +0000609 // (L == R) <==> (L.ptr == R.ptr &&
610 // (L.adj == R.adj ||
611 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall0bab0cd2010-08-23 01:21:21 +0000612 // The inequality tautologies have exactly the same structure, except
613 // applying De Morgan's laws.
614
615 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
616 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
617
John McCalle9fd7eb2010-08-22 08:30:07 +0000618 // This condition tests whether L.ptr == R.ptr. This must always be
619 // true for equality to hold.
620 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
621
622 // This condition, together with the assumption that L.ptr == R.ptr,
623 // tests whether the pointers are both null. ARM imposes an extra
624 // condition.
625 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
626 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
627
628 // This condition tests whether L.adj == R.adj. If this isn't
629 // true, the pointers are unequal unless they're both null.
John McCalld608cdb2010-08-22 10:59:02 +0000630 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
631 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000632 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
633
634 // Null member function pointers on ARM clear the low bit of Adj,
635 // so the zero condition has to check that neither low bit is set.
636 if (IsARM) {
637 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
638
639 // Compute (l.adj | r.adj) & 1 and test it against zero.
640 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
641 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
642 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
643 "cmp.or.adj");
644 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
645 }
646
647 // Tie together all our conditions.
648 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
649 Result = Builder.CreateBinOp(And, PtrEq, Result,
650 Inequality ? "memptr.ne" : "memptr.eq");
651 return Result;
652}
653
654llvm::Value *
John McCall0bab0cd2010-08-23 01:21:21 +0000655ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
656 llvm::Value *MemPtr,
657 const MemberPointerType *MPT) {
John McCalle9fd7eb2010-08-22 08:30:07 +0000658 CGBuilderTy &Builder = CGF.Builder;
John McCall0bab0cd2010-08-23 01:21:21 +0000659
660 /// For member data pointers, this is just a check against -1.
661 if (MPT->isMemberDataPointer()) {
Reid Kleckner92e44d92013-03-22 16:13:10 +0000662 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall0bab0cd2010-08-23 01:21:21 +0000663 llvm::Value *NegativeOne =
664 llvm::Constant::getAllOnesValue(MemPtr->getType());
665 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
666 }
John McCalle9fd7eb2010-08-22 08:30:07 +0000667
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000668 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalld608cdb2010-08-22 10:59:02 +0000669 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCalle9fd7eb2010-08-22 08:30:07 +0000670
671 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
672 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
673
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000674 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
675 // (the virtual bit) is set.
John McCalle9fd7eb2010-08-22 08:30:07 +0000676 if (IsARM) {
677 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalld608cdb2010-08-22 10:59:02 +0000678 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCalle9fd7eb2010-08-22 08:30:07 +0000679 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbardb27b5f2011-04-19 23:10:47 +0000680 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
681 "memptr.isvirtual");
682 Result = Builder.CreateOr(Result, IsVirtual);
John McCalle9fd7eb2010-08-22 08:30:07 +0000683 }
684
685 return Result;
686}
John McCall875ab102010-08-22 06:43:33 +0000687
John McCallf16aa102010-08-22 21:01:12 +0000688/// The Itanium ABI requires non-zero initialization only for data
689/// member pointers, for which '0' is a valid offset.
690bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
691 return MPT->getPointeeType()->isFunctionType();
John McCallcf2c85e2010-08-22 04:16:24 +0000692}
John McCall4c40d982010-08-31 07:33:07 +0000693
John McCallecd03b42012-09-25 10:10:39 +0000694/// The Itanium ABI always places an offset to the complete object
695/// at entry -2 in the vtable.
696llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
697 llvm::Value *ptr,
698 QualType type) {
699 // Grab the vtable pointer as an intptr_t*.
700 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
701
702 // Track back to entry -2 and pull out the offset there.
703 llvm::Value *offsetPtr =
704 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
705 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
706 offset->setAlignment(CGF.PointerAlignInBytes);
707
708 // Apply the offset.
709 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
710 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
711}
712
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000713llvm::Value *
714ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
715 llvm::Value *This,
716 const CXXRecordDecl *ClassDecl,
717 const CXXRecordDecl *BaseClassDecl) {
718 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
719 CharUnits VBaseOffsetOffset =
720 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
721
722 llvm::Value *VBaseOffsetPtr =
723 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
724 "vbase.offset.ptr");
725 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
726 CGM.PtrDiffTy->getPointerTo());
727
728 llvm::Value *VBaseOffset =
729 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
730
731 return VBaseOffset;
732}
733
John McCall4c40d982010-08-31 07:33:07 +0000734/// The generic ABI passes 'this', plus a VTT if it's initializing a
735/// base subobject.
736void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
737 CXXCtorType Type,
738 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000739 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000740 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000741
Stephen Lind4c0cd02013-06-18 17:00:49 +0000742 // 'this' parameter is already there, as well as 'this' return if
743 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000744
745 // Check if we need to add a VTT parameter (which has type void **).
746 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
747 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
748}
749
John McCall4c40d982010-08-31 07:33:07 +0000750/// The generic ABI passes 'this', plus a VTT if it's destroying a
751/// base subobject.
752void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
753 CXXDtorType Type,
754 CanQualType &ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000755 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9cb2cee2010-09-02 10:25:57 +0000756 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000757
Stephen Lind4c0cd02013-06-18 17:00:49 +0000758 // 'this' parameter is already there, as well as 'this' return if
759 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall4c40d982010-08-31 07:33:07 +0000760
761 // Check if we need to add a VTT parameter (which has type void **).
762 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
763 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
764}
765
John McCall4c40d982010-08-31 07:33:07 +0000766void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
767 QualType &ResTy,
768 FunctionArgList &Params) {
769 /// Create the 'this' variable.
770 BuildThisParam(CGF, Params);
771
772 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
773 assert(MD->isInstance());
774
775 // Check if we need a VTT parameter as well.
776 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
John McCall9cb2cee2010-09-02 10:25:57 +0000777 ASTContext &Context = getContext();
John McCall4c40d982010-08-31 07:33:07 +0000778
779 // FIXME: avoid the fake decl
780 QualType T = Context.getPointerType(Context.VoidPtrTy);
781 ImplicitParamDecl *VTTDecl
782 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
783 &Context.Idents.get("vtt"), T);
John McCalld26bc762011-03-09 04:27:21 +0000784 Params.push_back(VTTDecl);
John McCall4c40d982010-08-31 07:33:07 +0000785 getVTTDecl(CGF) = VTTDecl;
786 }
787}
788
John McCall4c40d982010-08-31 07:33:07 +0000789void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
790 /// Initialize the 'this' slot.
791 EmitThisParam(CGF);
792
793 /// Initialize the 'vtt' slot if needed.
794 if (getVTTDecl(CGF)) {
795 getVTTValue(CGF)
796 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
797 "vtt");
798 }
John McCall4c40d982010-08-31 07:33:07 +0000799
Stephen Lind4c0cd02013-06-18 17:00:49 +0000800 /// If this is a function that the ABI specifies returns 'this', initialize
801 /// the return slot to 'this' at the start of the function.
802 ///
803 /// Unlike the setting of return types, this is done within the ABI
804 /// implementation instead of by clients of CGCXXABI because:
805 /// 1) getThisValue is currently protected
806 /// 2) in theory, an ABI could implement 'this' returns some other way;
807 /// HasThisReturn only specifies a contract, not the implementation
John McCall4c40d982010-08-31 07:33:07 +0000808 if (HasThisReturn(CGF.CurGD))
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000809 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall4c40d982010-08-31 07:33:07 +0000810}
811
Stephen Lind4c0cd02013-06-18 17:00:49 +0000812RValue ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000813 const CXXConstructorDecl *D,
Stephen Lind4c0cd02013-06-18 17:00:49 +0000814 CXXCtorType Type,
815 bool ForVirtualBase, bool Delegating,
816 ReturnValueSlot ReturnValue,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000817 llvm::Value *This,
818 CallExpr::const_arg_iterator ArgBeg,
819 CallExpr::const_arg_iterator ArgEnd) {
820 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
821 Delegating);
822 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
823 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
824
825 // FIXME: Provide a source location here.
Stephen Lind4c0cd02013-06-18 17:00:49 +0000826 return CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValue,
827 This, VTT, VTTTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000828}
829
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000830RValue ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
831 const CXXDestructorDecl *Dtor,
832 CXXDtorType DtorType,
833 SourceLocation CallLoc,
834 ReturnValueSlot ReturnValue,
835 llvm::Value *This) {
836 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
837
838 const CGFunctionInfo *FInfo
839 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
840 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
841 llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, DtorType, This, Ty);
842
843 return CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValue, This,
844 /*ImplicitParam=*/0, QualType(), 0, 0);
845}
846
Reid Kleckner90633022013-06-19 15:20:38 +0000847void ItaniumCXXABI::EmitVirtualInheritanceTables(
848 llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) {
849 CodeGenVTables &VTables = CGM.getVTables();
850 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
851 VTables.EmitVTTDefinition(VTT, Linkage, RD);
852}
853
John McCall4c40d982010-08-31 07:33:07 +0000854void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
855 RValue RV, QualType ResultType) {
856 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
857 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
858
859 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000860 llvm::Type *T =
John McCall4c40d982010-08-31 07:33:07 +0000861 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
862 RValue Undef = RValue::get(llvm::UndefValue::get(T));
863 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
864}
John McCall1e7fe752010-09-02 09:58:18 +0000865
866/************************** Array allocation cookies **************************/
867
John McCalle2b45e22012-05-01 05:23:51 +0000868CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
869 // The array cookie is a size_t; pad that up to the element alignment.
870 // The cookie is actually right-justified in that space.
871 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
872 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000873}
874
875llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
876 llvm::Value *NewPtr,
877 llvm::Value *NumElements,
John McCall6ec278d2011-01-27 09:37:56 +0000878 const CXXNewExpr *expr,
John McCall1e7fe752010-09-02 09:58:18 +0000879 QualType ElementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000880 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000881
Micah Villmow956a5a12012-10-25 15:39:14 +0000882 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000883
John McCall9cb2cee2010-09-02 10:25:57 +0000884 ASTContext &Ctx = getContext();
John McCall1e7fe752010-09-02 09:58:18 +0000885 QualType SizeTy = Ctx.getSizeType();
886 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
887
888 // The size of the cookie.
889 CharUnits CookieSize =
890 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCalle2b45e22012-05-01 05:23:51 +0000891 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall1e7fe752010-09-02 09:58:18 +0000892
893 // Compute an offset to the cookie.
894 llvm::Value *CookiePtr = NewPtr;
895 CharUnits CookieOffset = CookieSize - SizeSize;
896 if (!CookieOffset.isZero())
897 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
898 CookieOffset.getQuantity());
899
900 // Write the number of elements into the appropriate slot.
901 llvm::Value *NumElementsPtr
902 = CGF.Builder.CreateBitCast(CookiePtr,
903 CGF.ConvertType(SizeTy)->getPointerTo(AS));
904 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
905
906 // Finally, compute a pointer to the actual data buffer by skipping
907 // over the cookie completely.
908 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
909 CookieSize.getQuantity());
910}
911
John McCalle2b45e22012-05-01 05:23:51 +0000912llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
913 llvm::Value *allocPtr,
914 CharUnits cookieSize) {
915 // The element size is right-justified in the cookie.
916 llvm::Value *numElementsPtr = allocPtr;
917 CharUnits numElementsOffset =
918 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
919 if (!numElementsOffset.isZero())
920 numElementsPtr =
921 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
922 numElementsOffset.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000923
Micah Villmow956a5a12012-10-25 15:39:14 +0000924 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000925 numElementsPtr =
926 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
927 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000928}
929
John McCalle2b45e22012-05-01 05:23:51 +0000930CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallf3bbb152013-01-25 23:36:19 +0000931 // ARM says that the cookie is always:
John McCall1e7fe752010-09-02 09:58:18 +0000932 // struct array_cookie {
933 // std::size_t element_size; // element_size != 0
934 // std::size_t element_count;
935 // };
John McCallf3bbb152013-01-25 23:36:19 +0000936 // But the base ABI doesn't give anything an alignment greater than
937 // 8, so we can dismiss this as typical ABI-author blindness to
938 // actual language complexity and round up to the element alignment.
939 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
940 CGM.getContext().getTypeAlignInChars(elementType));
John McCall1e7fe752010-09-02 09:58:18 +0000941}
942
943llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallf3bbb152013-01-25 23:36:19 +0000944 llvm::Value *newPtr,
945 llvm::Value *numElements,
John McCall6ec278d2011-01-27 09:37:56 +0000946 const CXXNewExpr *expr,
John McCallf3bbb152013-01-25 23:36:19 +0000947 QualType elementType) {
John McCalle2b45e22012-05-01 05:23:51 +0000948 assert(requiresArrayCookie(expr));
John McCall1e7fe752010-09-02 09:58:18 +0000949
John McCallf3bbb152013-01-25 23:36:19 +0000950 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
951 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall1e7fe752010-09-02 09:58:18 +0000952
953 // The cookie is always at the start of the buffer.
John McCallf3bbb152013-01-25 23:36:19 +0000954 llvm::Value *cookie = newPtr;
John McCall1e7fe752010-09-02 09:58:18 +0000955
956 // The first element is the element size.
John McCallf3bbb152013-01-25 23:36:19 +0000957 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
958 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
959 getContext().getTypeSizeInChars(elementType).getQuantity());
960 CGF.Builder.CreateStore(elementSize, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000961
962 // The second element is the element count.
John McCallf3bbb152013-01-25 23:36:19 +0000963 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
964 CGF.Builder.CreateStore(numElements, cookie);
John McCall1e7fe752010-09-02 09:58:18 +0000965
966 // Finally, compute a pointer to the actual data buffer by skipping
967 // over the cookie completely.
John McCallf3bbb152013-01-25 23:36:19 +0000968 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
969 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
970 cookieSize.getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000971}
972
John McCalle2b45e22012-05-01 05:23:51 +0000973llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
974 llvm::Value *allocPtr,
975 CharUnits cookieSize) {
976 // The number of elements is at offset sizeof(size_t) relative to
977 // the allocated pointer.
978 llvm::Value *numElementsPtr
979 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall1e7fe752010-09-02 09:58:18 +0000980
Micah Villmow956a5a12012-10-25 15:39:14 +0000981 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000982 numElementsPtr =
983 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
984 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall1e7fe752010-09-02 09:58:18 +0000985}
986
John McCall5cd91b52010-09-08 01:44:27 +0000987/*********************** Static local initialization **************************/
988
989static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000990 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +0000991 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000992 llvm::FunctionType *FTy =
John McCall5cd91b52010-09-08 01:44:27 +0000993 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foadda549e82011-07-29 13:56:53 +0000994 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +0000995 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +0000996 llvm::AttributeSet::get(CGM.getLLVMContext(),
997 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +0000998 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +0000999}
1000
1001static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001002 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001003 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001004 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001005 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001006 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001007 llvm::AttributeSet::get(CGM.getLLVMContext(),
1008 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001009 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001010}
1011
1012static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001013 llvm::PointerType *GuardPtrTy) {
John McCall5cd91b52010-09-08 01:44:27 +00001014 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001015 llvm::FunctionType *FTy =
Chris Lattner8b418682012-02-07 00:39:47 +00001016 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckye76872e2012-02-13 23:45:02 +00001017 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001018 llvm::AttributeSet::get(CGM.getLLVMContext(),
1019 llvm::AttributeSet::FunctionIndex,
Bill Wendling72390b32012-12-20 19:27:06 +00001020 llvm::Attribute::NoUnwind));
John McCall5cd91b52010-09-08 01:44:27 +00001021}
1022
1023namespace {
1024 struct CallGuardAbort : EHScopeStack::Cleanup {
1025 llvm::GlobalVariable *Guard;
Chandler Carruth0f30a122012-03-30 19:44:53 +00001026 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall5cd91b52010-09-08 01:44:27 +00001027
John McCallad346f42011-07-12 20:27:29 +00001028 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbd7370a2013-02-28 19:01:20 +00001029 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1030 Guard);
John McCall5cd91b52010-09-08 01:44:27 +00001031 }
1032 };
1033}
1034
1035/// The ARM code here follows the Itanium code closely enough that we
1036/// just special-case it at particular places.
John McCall3030eb82010-11-06 09:44:32 +00001037void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1038 const VarDecl &D,
John McCall355bba72012-03-30 21:00:39 +00001039 llvm::GlobalVariable *var,
1040 bool shouldPerformInit) {
John McCall5cd91b52010-09-08 01:44:27 +00001041 CGBuilderTy &Builder = CGF.Builder;
John McCall3030eb82010-11-06 09:44:32 +00001042
Richard Smith04e51762013-04-14 23:01:42 +00001043 // We only need to use thread-safe statics for local non-TLS variables;
John McCall3030eb82010-11-06 09:44:32 +00001044 // global initialization is always single-threaded.
Richard Smith04e51762013-04-14 23:01:42 +00001045 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1046 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlsson173d5122011-04-27 04:37:08 +00001047
Anders Carlsson173d5122011-04-27 04:37:08 +00001048 // If we have a global variable with internal linkage and thread-safe statics
1049 // are disabled, we can just let the guard variable be of type i8.
John McCall355bba72012-03-30 21:00:39 +00001050 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1051
1052 llvm::IntegerType *guardTy;
John McCall0502a222011-06-17 07:33:57 +00001053 if (useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001054 guardTy = CGF.Int8Ty;
John McCall0502a222011-06-17 07:33:57 +00001055 } else {
Tim Northoverc264e162013-01-31 12:13:10 +00001056 // Guard variables are 64 bits in the generic ABI and size width on ARM
1057 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1058 guardTy = (IsARM ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlsson173d5122011-04-27 04:37:08 +00001059 }
John McCall355bba72012-03-30 21:00:39 +00001060 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall5cd91b52010-09-08 01:44:27 +00001061
John McCall355bba72012-03-30 21:00:39 +00001062 // Create the guard variable if we don't already have it (as we
1063 // might if we're double-emitting this function body).
1064 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1065 if (!guard) {
1066 // Mangle the name for the guard.
1067 SmallString<256> guardName;
1068 {
1069 llvm::raw_svector_ostream out(guardName);
1070 getMangleContext().mangleItaniumGuardVariable(&D, out);
1071 out.flush();
1072 }
John McCall112c9672010-11-02 21:04:24 +00001073
John McCall355bba72012-03-30 21:00:39 +00001074 // Create the guard variable with a zero-initializer.
1075 // Just absorb linkage and visibility from the guarded variable.
1076 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1077 false, var->getLinkage(),
1078 llvm::ConstantInt::get(guardTy, 0),
1079 guardName.str());
1080 guard->setVisibility(var->getVisibility());
Richard Smith04e51762013-04-14 23:01:42 +00001081 // If the variable is thread-local, so is its guard variable.
1082 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall355bba72012-03-30 21:00:39 +00001083
1084 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1085 }
John McCall49d26d22012-03-30 07:09:50 +00001086
John McCall5cd91b52010-09-08 01:44:27 +00001087 // Test whether the variable has completed initialization.
John McCall355bba72012-03-30 21:00:39 +00001088 llvm::Value *isInitialized;
John McCall5cd91b52010-09-08 01:44:27 +00001089
1090 // ARM C++ ABI 3.2.3.1:
1091 // To support the potential use of initialization guard variables
1092 // as semaphores that are the target of ARM SWP and LDREX/STREX
1093 // synchronizing instructions we define a static initialization
1094 // guard variable to be a 4-byte aligned, 4- byte word with the
1095 // following inline access protocol.
1096 // #define INITIALIZED 1
1097 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1098 // if (__cxa_guard_acquire(&obj_guard))
1099 // ...
1100 // }
John McCall0502a222011-06-17 07:33:57 +00001101 if (IsARM && !useInt8GuardVariable) {
John McCall355bba72012-03-30 21:00:39 +00001102 llvm::Value *V = Builder.CreateLoad(guard);
Tim Northoverc264e162013-01-31 12:13:10 +00001103 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1104 V = Builder.CreateAnd(V, Test1);
John McCall355bba72012-03-30 21:00:39 +00001105 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001106
1107 // Itanium C++ ABI 3.3.2:
1108 // The following is pseudo-code showing how these functions can be used:
1109 // if (obj_guard.first_byte == 0) {
1110 // if ( __cxa_guard_acquire (&obj_guard) ) {
1111 // try {
1112 // ... initialize the object ...;
1113 // } catch (...) {
1114 // __cxa_guard_abort (&obj_guard);
1115 // throw;
1116 // }
1117 // ... queue object destructor with __cxa_atexit() ...;
1118 // __cxa_guard_release (&obj_guard);
1119 // }
1120 // }
1121 } else {
1122 // Load the first byte of the guard variable.
Chandler Carruth0f30a122012-03-30 19:44:53 +00001123 llvm::LoadInst *LI =
John McCall355bba72012-03-30 21:00:39 +00001124 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Chandler Carruth0f30a122012-03-30 19:44:53 +00001125 LI->setAlignment(1);
John McCall5cd91b52010-09-08 01:44:27 +00001126
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001127 // Itanium ABI:
1128 // An implementation supporting thread-safety on multiprocessor
1129 // systems must also guarantee that references to the initialized
1130 // object do not occur before the load of the initialization flag.
1131 //
1132 // In LLVM, we do this by marking the load Acquire.
1133 if (threadsafe)
Chandler Carruth0f30a122012-03-30 19:44:53 +00001134 LI->setAtomic(llvm::Acquire);
Eli Friedmaneb43f4a2011-09-13 22:21:56 +00001135
John McCall355bba72012-03-30 21:00:39 +00001136 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
John McCall5cd91b52010-09-08 01:44:27 +00001137 }
1138
1139 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1140 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1141
1142 // Check if the first byte of the guard variable is zero.
John McCall355bba72012-03-30 21:00:39 +00001143 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall5cd91b52010-09-08 01:44:27 +00001144
1145 CGF.EmitBlock(InitCheckBlock);
1146
1147 // Variables used when coping with thread-safe statics and exceptions.
John McCall0502a222011-06-17 07:33:57 +00001148 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001149 // Call __cxa_guard_acquire.
1150 llvm::Value *V
John McCallbd7370a2013-02-28 19:01:20 +00001151 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001152
1153 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1154
1155 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1156 InitBlock, EndBlock);
1157
1158 // Call __cxa_guard_abort along the exceptional edge.
John McCall355bba72012-03-30 21:00:39 +00001159 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall5cd91b52010-09-08 01:44:27 +00001160
1161 CGF.EmitBlock(InitBlock);
1162 }
1163
1164 // Emit the initializer and add a global destructor if appropriate.
John McCall355bba72012-03-30 21:00:39 +00001165 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall5cd91b52010-09-08 01:44:27 +00001166
John McCall0502a222011-06-17 07:33:57 +00001167 if (threadsafe) {
John McCall5cd91b52010-09-08 01:44:27 +00001168 // Pop the guard-abort cleanup if we pushed one.
1169 CGF.PopCleanupBlock();
1170
1171 // Call __cxa_guard_release. This cannot throw.
John McCallbd7370a2013-02-28 19:01:20 +00001172 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001173 } else {
John McCall355bba72012-03-30 21:00:39 +00001174 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall5cd91b52010-09-08 01:44:27 +00001175 }
1176
1177 CGF.EmitBlock(EndBlock);
1178}
John McCall20bb1752012-05-01 06:13:13 +00001179
1180/// Register a global destructor using __cxa_atexit.
1181static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1182 llvm::Constant *dtor,
Richard Smith04e51762013-04-14 23:01:42 +00001183 llvm::Constant *addr,
1184 bool TLS) {
Bill Wendling4e3b54b2013-05-02 19:18:03 +00001185 const char *Name = "__cxa_atexit";
1186 if (TLS) {
1187 const llvm::Triple &T = CGF.getTarget().getTriple();
1188 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1189 }
Richard Smith04e51762013-04-14 23:01:42 +00001190
John McCall20bb1752012-05-01 06:13:13 +00001191 // We're assuming that the destructor function is something we can
1192 // reasonably call with the default CC. Go ahead and cast it to the
1193 // right prototype.
1194 llvm::Type *dtorTy =
1195 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1196
1197 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1198 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1199 llvm::FunctionType *atexitTy =
1200 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1201
1202 // Fetch the actual function.
Richard Smith04e51762013-04-14 23:01:42 +00001203 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCall20bb1752012-05-01 06:13:13 +00001204 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1205 fn->setDoesNotThrow();
1206
1207 // Create a variable that binds the atexit to this shared object.
1208 llvm::Constant *handle =
1209 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1210
1211 llvm::Value *args[] = {
1212 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1213 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1214 handle
1215 };
John McCallbd7370a2013-02-28 19:01:20 +00001216 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCall20bb1752012-05-01 06:13:13 +00001217}
1218
1219/// Register a global destructor as best as we know how.
1220void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smith04e51762013-04-14 23:01:42 +00001221 const VarDecl &D,
John McCall20bb1752012-05-01 06:13:13 +00001222 llvm::Constant *dtor,
1223 llvm::Constant *addr) {
1224 // Use __cxa_atexit if available.
Richard Smith04e51762013-04-14 23:01:42 +00001225 if (CGM.getCodeGenOpts().CXAAtExit)
1226 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1227
1228 if (D.getTLSKind())
1229 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCall20bb1752012-05-01 06:13:13 +00001230
1231 // In Apple kexts, we want to add a global destructor entry.
1232 // FIXME: shouldn't this be guarded by some variable?
Richard Smith7edf9e32012-11-01 22:30:59 +00001233 if (CGM.getLangOpts().AppleKext) {
John McCall20bb1752012-05-01 06:13:13 +00001234 // Generate a global destructor entry.
1235 return CGM.AddCXXDtorEntry(dtor, addr);
1236 }
1237
1238 CGF.registerGlobalDtorWithAtExit(dtor, addr);
1239}
Richard Smithb80a16e2013-04-19 16:42:07 +00001240
1241/// Get the appropriate linkage for the wrapper function. This is essentially
1242/// the weak form of the variable's linkage; every translation unit which wneeds
1243/// the wrapper emits a copy, and we want the linker to merge them.
1244static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1245 llvm::GlobalValue::LinkageTypes VarLinkage) {
1246 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1247 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1248 // For internal linkage variables, we don't need an external or weak wrapper.
1249 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1250 return VarLinkage;
1251 return llvm::GlobalValue::WeakODRLinkage;
1252}
1253
1254llvm::Function *
1255ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1256 llvm::GlobalVariable *Var) {
1257 // Mangle the name for the thread_local wrapper function.
1258 SmallString<256> WrapperName;
1259 {
1260 llvm::raw_svector_ostream Out(WrapperName);
1261 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1262 Out.flush();
1263 }
1264
1265 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1266 return cast<llvm::Function>(V);
1267
1268 llvm::Type *RetTy = Var->getType();
1269 if (VD->getType()->isReferenceType())
1270 RetTy = RetTy->getPointerElementType();
1271
1272 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1273 llvm::Function *Wrapper = llvm::Function::Create(
1274 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1275 &CGM.getModule());
1276 // Always resolve references to the wrapper at link time.
1277 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1278 return Wrapper;
1279}
1280
1281void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1282 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1283 llvm::Function *InitFunc) {
1284 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1285 const VarDecl *VD = Decls[I].first;
1286 llvm::GlobalVariable *Var = Decls[I].second;
1287
1288 // Mangle the name for the thread_local initialization function.
1289 SmallString<256> InitFnName;
1290 {
1291 llvm::raw_svector_ostream Out(InitFnName);
1292 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1293 Out.flush();
1294 }
1295
1296 // If we have a definition for the variable, emit the initialization
1297 // function as an alias to the global Init function (if any). Otherwise,
1298 // produce a declaration of the initialization function.
1299 llvm::GlobalValue *Init = 0;
1300 bool InitIsInitFunc = false;
1301 if (VD->hasDefinition()) {
1302 InitIsInitFunc = true;
1303 if (InitFunc)
1304 Init =
1305 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1306 InitFnName.str(), InitFunc, &CGM.getModule());
1307 } else {
1308 // Emit a weak global function referring to the initialization function.
1309 // This function will not exist if the TU defining the thread_local
1310 // variable in question does not need any dynamic initialization for
1311 // its thread_local variables.
1312 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1313 Init = llvm::Function::Create(
1314 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1315 &CGM.getModule());
1316 }
1317
1318 if (Init)
1319 Init->setVisibility(Var->getVisibility());
1320
1321 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1322 llvm::LLVMContext &Context = CGM.getModule().getContext();
1323 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1324 CGBuilderTy Builder(Entry);
1325 if (InitIsInitFunc) {
1326 if (Init)
1327 Builder.CreateCall(Init);
1328 } else {
1329 // Don't know whether we have an init function. Call it if it exists.
1330 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1331 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1332 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1333 Builder.CreateCondBr(Have, InitBB, ExitBB);
1334
1335 Builder.SetInsertPoint(InitBB);
1336 Builder.CreateCall(Init);
1337 Builder.CreateBr(ExitBB);
1338
1339 Builder.SetInsertPoint(ExitBB);
1340 }
1341
1342 // For a reference, the result of the wrapper function is a pointer to
1343 // the referenced object.
1344 llvm::Value *Val = Var;
1345 if (VD->getType()->isReferenceType()) {
1346 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1347 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1348 Val = LI;
1349 }
1350
1351 Builder.CreateRet(Val);
1352 }
1353}
1354
1355LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1356 const DeclRefExpr *DRE) {
1357 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1358 QualType T = VD->getType();
1359 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1360 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1361 llvm::Function *Wrapper =
1362 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1363
1364 Val = CGF.Builder.CreateCall(Wrapper);
1365
1366 LValue LV;
1367 if (VD->getType()->isReferenceType())
1368 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1369 else
1370 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1371 CGF.getContext().getDeclAlign(VD));
1372 // FIXME: need setObjCGCLValueClass?
1373 return LV;
1374}