blob: 5fd0499f67b7c8faaf09e4e242bc0f3687c90a80 [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"
David Majnemer1162d252014-06-22 19:05:33 +000028#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000032
33using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000034using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000035
36namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000037class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000038 /// VTables - All the vtables which have been defined.
39 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
40
John McCall475999d2010-08-22 00:05:51 +000041protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000042 bool UseARMMethodPtrABI;
43 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000044
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000045 ItaniumMangleContext &getMangleContext() {
46 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
47 }
48
Charles Davis4e786dd2010-05-25 19:52:27 +000049public:
Mark Seabornedf0d382013-07-24 16:25:13 +000050 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
51 bool UseARMMethodPtrABI = false,
52 bool UseARMGuardVarABI = false) :
53 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
54 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000055
Reid Kleckner40ca9132014-05-13 22:05:45 +000056 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000057
Craig Topper4f12f102014-03-12 06:41:41 +000058 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000059 // Structures with either a non-trivial destructor or a non-trivial
60 // copy constructor are always indirect.
61 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
62 // special members.
63 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000064 return RAA_Indirect;
65 return RAA_Default;
66 }
67
Craig Topper4f12f102014-03-12 06:41:41 +000068 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000069
Craig Topper4f12f102014-03-12 06:41:41 +000070 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +000071
Craig Topper4f12f102014-03-12 06:41:41 +000072 llvm::Value *
73 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
74 const Expr *E,
75 llvm::Value *&This,
76 llvm::Value *MemFnPtr,
77 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +000078
Craig Topper4f12f102014-03-12 06:41:41 +000079 llvm::Value *
80 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
81 llvm::Value *Base,
82 llvm::Value *MemPtr,
83 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +000084
John McCall7a9aac22010-08-23 01:21:21 +000085 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
86 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000087 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +000088 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000089 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +000090
Craig Topper4f12f102014-03-12 06:41:41 +000091 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000092
Craig Topper4f12f102014-03-12 06:41:41 +000093 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000094 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000095 CharUnits offset) override;
96 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +000097 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
98 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +000099
John McCall7a9aac22010-08-23 01:21:21 +0000100 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000101 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000102 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000103 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000104
John McCall7a9aac22010-08-23 01:21:21 +0000105 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000106 llvm::Value *Addr,
107 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000108
Craig Topper4f12f102014-03-12 06:41:41 +0000109 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr,
110 QualType type) override;
John McCall82fb8922012-09-25 10:10:39 +0000111
David Majnemere2cb8d12014-07-07 06:20:47 +0000112 void EmitFundamentalRTTIDescriptor(QualType Type);
113 void EmitFundamentalRTTIDescriptors();
114 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
115
David Majnemer1162d252014-06-22 19:05:33 +0000116 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
117 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
118 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
119 llvm::Value *ThisPtr,
120 llvm::Type *StdTypeInfoPtrTy) override;
121
122 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
123 QualType SrcRecordTy) override;
124
125 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
126 QualType SrcRecordTy, QualType DestTy,
127 QualType DestRecordTy,
128 llvm::BasicBlock *CastEnd) override;
129
130 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
131 QualType SrcRecordTy,
132 QualType DestTy) override;
133
134 bool EmitBadCastCall(CodeGenFunction &CGF) override;
135
Craig Topper4f12f102014-03-12 06:41:41 +0000136 llvm::Value *
137 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
138 const CXXRecordDecl *ClassDecl,
139 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000140
John McCall5d865c322010-08-31 07:33:07 +0000141 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
Craig Topper4f12f102014-03-12 06:41:41 +0000142 CXXCtorType T, CanQualType &ResTy,
143 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000144
Craig Topper4f12f102014-03-12 06:41:41 +0000145 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000146
John McCall5d865c322010-08-31 07:33:07 +0000147 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000148 CXXDtorType T, CanQualType &ResTy,
149 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000150
Reid Klecknere7de47e2013-07-22 13:51:44 +0000151 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000152 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000153 // Itanium does not emit any destructor variant as an inline thunk.
154 // Delegating may occur as an optimization, but all variants are either
155 // emitted with external linkage or as linkonce if they are inline and used.
156 return false;
157 }
158
Craig Topper4f12f102014-03-12 06:41:41 +0000159 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000160
Reid Kleckner89077a12013-12-17 19:46:40 +0000161 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000162 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000163
Craig Topper4f12f102014-03-12 06:41:41 +0000164 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000165
Reid Kleckner89077a12013-12-17 19:46:40 +0000166 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
167 const CXXConstructorDecl *D,
168 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000169 bool Delegating,
170 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000171
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000172 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
173 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000174 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000175
Craig Topper4f12f102014-03-12 06:41:41 +0000176 void emitVTableDefinitions(CodeGenVTables &CGVT,
177 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000178
179 llvm::Value *getVTableAddressPointInStructor(
180 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
181 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000182 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000183
184 llvm::Constant *
185 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000186 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000187
188 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000189 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000190
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000191 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000192 llvm::Value *This,
193 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000194
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000195 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
196 const CXXDestructorDecl *Dtor,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000197 CXXDtorType DtorType, llvm::Value *This,
198 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000199
Craig Topper4f12f102014-03-12 06:41:41 +0000200 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000201
Hans Wennborgc94391d2014-06-06 20:04:01 +0000202 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
203 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000204 // Allow inlining of thunks by emitting them with available_externally
205 // linkage together with vtables when needed.
206 if (ForVTable)
207 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
208 }
209
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000210 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000211 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000212
213 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000214 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000215
Craig Topper4f12f102014-03-12 06:41:41 +0000216 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
217 StringRef GetDeletedVirtualCallName() override
218 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000219
Craig Topper4f12f102014-03-12 06:41:41 +0000220 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000221 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
222 llvm::Value *NewPtr,
223 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000224 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000225 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000226 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
227 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000228 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000229
John McCallcdf7ef52010-11-06 09:44:32 +0000230 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000231 llvm::GlobalVariable *DeclPtr,
232 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000233 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000234 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000235
236 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
237 llvm::GlobalVariable *Var);
238 void EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +0000239 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Craig Topper4f12f102014-03-12 06:41:41 +0000240 llvm::Function *InitFunc) override;
Richard Smith0f383742014-03-26 22:48:22 +0000241 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
242 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000243
Craig Topper4f12f102014-03-12 06:41:41 +0000244 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000245
246 /**************************** RTTI Uniqueness ******************************/
247
248protected:
249 /// Returns true if the ABI requires RTTI type_info objects to be unique
250 /// across a program.
251 virtual bool shouldRTTIBeUnique() const { return true; }
252
253public:
254 /// What sort of unique-RTTI behavior should we use?
255 enum RTTIUniquenessKind {
256 /// We are guaranteeing, or need to guarantee, that the RTTI string
257 /// is unique.
258 RUK_Unique,
259
260 /// We are not guaranteeing uniqueness for the RTTI string, so we
261 /// can demote to hidden visibility but must use string comparisons.
262 RUK_NonUniqueHidden,
263
264 /// We are not guaranteeing uniqueness for the RTTI string, so we
265 /// have to use string comparisons, but we also have to emit it with
266 /// non-hidden visibility.
267 RUK_NonUniqueVisible
268 };
269
270 /// Return the required visibility status for the given type and linkage in
271 /// the current ABI.
272 RTTIUniquenessKind
273 classifyRTTIUniqueness(QualType CanTy,
274 llvm::GlobalValue::LinkageTypes Linkage) const;
275 friend class ItaniumRTTIBuilder;
Charles Davis4e786dd2010-05-25 19:52:27 +0000276};
John McCall86353412010-08-21 22:46:04 +0000277
278class ARMCXXABI : public ItaniumCXXABI {
279public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000280 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
281 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
282 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000283
Craig Topper4f12f102014-03-12 06:41:41 +0000284 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000285 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
286 isa<CXXDestructorDecl>(GD.getDecl()) &&
287 GD.getDtorType() != Dtor_Deleting));
288 }
John McCall5d865c322010-08-31 07:33:07 +0000289
Craig Topper4f12f102014-03-12 06:41:41 +0000290 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
291 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000292
Craig Topper4f12f102014-03-12 06:41:41 +0000293 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000294 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
295 llvm::Value *NewPtr,
296 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000297 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000298 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000299 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000300 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000301};
Tim Northovera2ee4332014-03-29 15:09:45 +0000302
303class iOS64CXXABI : public ARMCXXABI {
304public:
305 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000306
307 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000308 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000309};
Charles Davis4e786dd2010-05-25 19:52:27 +0000310}
311
Charles Davis53c59df2010-08-16 03:33:14 +0000312CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000313 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000314 // For IR-generation purposes, there's no significant difference
315 // between the ARM and iOS ABIs.
316 case TargetCXXABI::GenericARM:
317 case TargetCXXABI::iOS:
318 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000319
Tim Northovera2ee4332014-03-29 15:09:45 +0000320 case TargetCXXABI::iOS64:
321 return new iOS64CXXABI(CGM);
322
Tim Northover9bb857a2013-01-31 12:13:10 +0000323 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
324 // include the other 32-bit ARM oddities: constructor/destructor return values
325 // and array cookies.
326 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000327 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
328 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000329
John McCall57625922013-01-25 23:36:14 +0000330 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000331 if (CGM.getContext().getTargetInfo().getTriple().getArch()
332 == llvm::Triple::le32) {
333 // For PNaCl, use ARM-style method pointers so that PNaCl code
334 // does not assume anything about the alignment of function
335 // pointers.
336 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
337 /* UseARMGuardVarABI = */ false);
338 }
John McCall57625922013-01-25 23:36:14 +0000339 return new ItaniumCXXABI(CGM);
340
341 case TargetCXXABI::Microsoft:
342 llvm_unreachable("Microsoft ABI is not Itanium-based");
343 }
344 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000345}
346
Chris Lattnera5f58b02011-07-09 17:41:47 +0000347llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000348ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
349 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000350 return CGM.PtrDiffTy;
351 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000352}
353
John McCalld9c6c0b2010-08-22 00:59:17 +0000354/// In the Itanium and ARM ABIs, method pointers have the form:
355/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
356///
357/// In the Itanium ABI:
358/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
359/// - the this-adjustment is (memptr.adj)
360/// - the virtual offset is (memptr.ptr - 1)
361///
362/// In the ARM ABI:
363/// - method pointers are virtual if (memptr.adj & 1) is nonzero
364/// - the this-adjustment is (memptr.adj >> 1)
365/// - the virtual offset is (memptr.ptr)
366/// ARM uses 'adj' for the virtual flag because Thumb functions
367/// may be only single-byte aligned.
368///
369/// If the member is virtual, the adjusted 'this' pointer points
370/// to a vtable pointer from which the virtual offset is applied.
371///
372/// If the member is non-virtual, memptr.ptr is the address of
373/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000374llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
375 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
376 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000377 CGBuilderTy &Builder = CGF.Builder;
378
379 const FunctionProtoType *FPT =
380 MPT->getPointeeType()->getAs<FunctionProtoType>();
381 const CXXRecordDecl *RD =
382 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
383
Chris Lattner2192fe52011-07-18 04:24:23 +0000384 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000385 CGM.getTypes().GetFunctionType(
386 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000387
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000388 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000389
John McCalld9c6c0b2010-08-22 00:59:17 +0000390 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
391 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
392 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
393
John McCalla1dee5302010-08-22 10:59:02 +0000394 // Extract memptr.adj, which is in the second field.
395 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000396
397 // Compute the true adjustment.
398 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000399 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000400 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000401
402 // Apply the adjustment and cast back to the original struct type
403 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000404 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
405 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
406 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000407
408 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000409 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000410
411 // If the LSB in the function pointer is 1, the function pointer points to
412 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000413 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000414 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000415 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
416 else
417 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
418 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000419 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
420
421 // In the virtual path, the adjustment left 'This' pointing to the
422 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000423 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000424 CGF.EmitBlock(FnVirtual);
425
426 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000427 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000428 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000429
430 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000431 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000432 if (!UseARMMethodPtrABI)
433 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000434 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000435
436 // Load the virtual function to call.
437 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000438 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000439 CGF.EmitBranch(FnEnd);
440
441 // In the non-virtual path, the function pointer is actually a
442 // function pointer.
443 CGF.EmitBlock(FnNonVirtual);
444 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000445 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000446
447 // We're done.
448 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000449 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000450 Callee->addIncoming(VirtualFn, FnVirtual);
451 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
452 return Callee;
453}
John McCalla8bbb822010-08-22 03:04:22 +0000454
John McCallc134eb52010-08-31 21:07:20 +0000455/// Compute an l-value by applying the given pointer-to-member to a
456/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000457llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
458 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
459 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000460 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000461
462 CGBuilderTy &Builder = CGF.Builder;
463
Micah Villmowea2fea22012-10-25 15:39:14 +0000464 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000465
466 // Cast to char*.
467 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
468
469 // Apply the offset, which we assume is non-null.
470 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
471
472 // Cast the address to the appropriate pointer type, adopting the
473 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000474 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000475 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000476 return Builder.CreateBitCast(Addr, PType);
477}
478
John McCallc62bb392012-02-15 01:22:51 +0000479/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
480/// conversion.
481///
482/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000483///
484/// Obligatory offset/adjustment diagram:
485/// <-- offset --> <-- adjustment -->
486/// |--------------------------|----------------------|--------------------|
487/// ^Derived address point ^Base address point ^Member address point
488///
489/// So when converting a base member pointer to a derived member pointer,
490/// we add the offset to the adjustment because the address point has
491/// decreased; and conversely, when converting a derived MP to a base MP
492/// we subtract the offset from the adjustment because the address point
493/// has increased.
494///
495/// The standard forbids (at compile time) conversion to and from
496/// virtual bases, which is why we don't have to consider them here.
497///
498/// The standard forbids (at run time) casting a derived MP to a base
499/// MP when the derived MP does not point to a member of the base.
500/// This is why -1 is a reasonable choice for null data member
501/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000502llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000503ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
504 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000505 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000506 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000507 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
508 E->getCastKind() == CK_ReinterpretMemberPointer);
509
510 // Under Itanium, reinterprets don't require any additional processing.
511 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
512
513 // Use constant emission if we can.
514 if (isa<llvm::Constant>(src))
515 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
516
517 llvm::Constant *adj = getMemberPointerAdjustment(E);
518 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000519
520 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000521 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000522
John McCallc62bb392012-02-15 01:22:51 +0000523 const MemberPointerType *destTy =
524 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000525
John McCall7a9aac22010-08-23 01:21:21 +0000526 // For member data pointers, this is just a matter of adding the
527 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000528 if (destTy->isMemberDataPointer()) {
529 llvm::Value *dst;
530 if (isDerivedToBase)
531 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000532 else
John McCallc62bb392012-02-15 01:22:51 +0000533 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000534
535 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000536 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
537 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
538 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000539 }
540
John McCalla1dee5302010-08-22 10:59:02 +0000541 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000542 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000543 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
544 offset <<= 1;
545 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000546 }
547
John McCallc62bb392012-02-15 01:22:51 +0000548 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
549 llvm::Value *dstAdj;
550 if (isDerivedToBase)
551 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000552 else
John McCallc62bb392012-02-15 01:22:51 +0000553 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000554
John McCallc62bb392012-02-15 01:22:51 +0000555 return Builder.CreateInsertValue(src, dstAdj, 1);
556}
557
558llvm::Constant *
559ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
560 llvm::Constant *src) {
561 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
562 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
563 E->getCastKind() == CK_ReinterpretMemberPointer);
564
565 // Under Itanium, reinterprets don't require any additional processing.
566 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
567
568 // If the adjustment is trivial, we don't need to do anything.
569 llvm::Constant *adj = getMemberPointerAdjustment(E);
570 if (!adj) return src;
571
572 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
573
574 const MemberPointerType *destTy =
575 E->getType()->castAs<MemberPointerType>();
576
577 // For member data pointers, this is just a matter of adding the
578 // offset if the source is non-null.
579 if (destTy->isMemberDataPointer()) {
580 // null maps to null.
581 if (src->isAllOnesValue()) return src;
582
583 if (isDerivedToBase)
584 return llvm::ConstantExpr::getNSWSub(src, adj);
585 else
586 return llvm::ConstantExpr::getNSWAdd(src, adj);
587 }
588
589 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000590 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000591 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
592 offset <<= 1;
593 adj = llvm::ConstantInt::get(adj->getType(), offset);
594 }
595
596 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
597 llvm::Constant *dstAdj;
598 if (isDerivedToBase)
599 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
600 else
601 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
602
603 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000604}
John McCall84fa5102010-08-22 04:16:24 +0000605
606llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000607ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000608 // Itanium C++ ABI 2.3:
609 // A NULL pointer is represented as -1.
610 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000611 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000612
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000613 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000614 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000615 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000616}
617
John McCallf3a88602011-02-03 08:15:49 +0000618llvm::Constant *
619ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
620 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000621 // Itanium C++ ABI 2.3:
622 // A pointer to data member is an offset from the base address of
623 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000624 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000625}
626
John McCall2979fe02011-04-12 00:42:48 +0000627llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000628 return BuildMemberPointer(MD, CharUnits::Zero());
629}
630
631llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
632 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000633 assert(MD->isInstance() && "Member function must not be static!");
634 MD = MD->getCanonicalDecl();
635
636 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000637
638 // Get the function pointer (or index if this is a virtual function).
639 llvm::Constant *MemPtr[2];
640 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000641 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000642
Ken Dyckdf016282011-04-09 01:30:02 +0000643 const ASTContext &Context = getContext();
644 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000645 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000646 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000647
Mark Seabornedf0d382013-07-24 16:25:13 +0000648 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000649 // ARM C++ ABI 3.2.1:
650 // This ABI specifies that adj contains twice the this
651 // adjustment, plus 1 if the member function is virtual. The
652 // least significant bit of adj then makes exactly the same
653 // discrimination as the least significant bit of ptr does for
654 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000655 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
656 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000657 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000658 } else {
659 // Itanium C++ ABI 2.3:
660 // For a virtual function, [the pointer field] is 1 plus the
661 // virtual table offset (in bytes) of the function,
662 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000663 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
664 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000665 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000666 }
667 } else {
John McCall2979fe02011-04-12 00:42:48 +0000668 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000669 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000670 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000671 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000672 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000673 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000674 } else {
John McCall2979fe02011-04-12 00:42:48 +0000675 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
676 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000677 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000678 }
John McCall2979fe02011-04-12 00:42:48 +0000679 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000680
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000681 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000682 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
683 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000684 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000685 }
John McCall1c456c82010-08-22 06:43:33 +0000686
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000687 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000688}
689
Richard Smithdafff942012-01-14 04:30:29 +0000690llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
691 QualType MPType) {
692 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
693 const ValueDecl *MPD = MP.getMemberPointerDecl();
694 if (!MPD)
695 return EmitNullMemberPointer(MPT);
696
Reid Kleckner452abac2013-05-09 21:01:17 +0000697 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000698
699 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
700 return BuildMemberPointer(MD, ThisAdjustment);
701
702 CharUnits FieldOffset =
703 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
704 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
705}
706
John McCall131d97d2010-08-22 08:30:07 +0000707/// The comparison algorithm is pretty easy: the member pointers are
708/// the same if they're either bitwise identical *or* both null.
709///
710/// ARM is different here only because null-ness is more complicated.
711llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000712ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
713 llvm::Value *L,
714 llvm::Value *R,
715 const MemberPointerType *MPT,
716 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000717 CGBuilderTy &Builder = CGF.Builder;
718
John McCall131d97d2010-08-22 08:30:07 +0000719 llvm::ICmpInst::Predicate Eq;
720 llvm::Instruction::BinaryOps And, Or;
721 if (Inequality) {
722 Eq = llvm::ICmpInst::ICMP_NE;
723 And = llvm::Instruction::Or;
724 Or = llvm::Instruction::And;
725 } else {
726 Eq = llvm::ICmpInst::ICMP_EQ;
727 And = llvm::Instruction::And;
728 Or = llvm::Instruction::Or;
729 }
730
John McCall7a9aac22010-08-23 01:21:21 +0000731 // Member data pointers are easy because there's a unique null
732 // value, so it just comes down to bitwise equality.
733 if (MPT->isMemberDataPointer())
734 return Builder.CreateICmp(Eq, L, R);
735
736 // For member function pointers, the tautologies are more complex.
737 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000738 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000739 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000740 // (L == R) <==> (L.ptr == R.ptr &&
741 // (L.adj == R.adj ||
742 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000743 // The inequality tautologies have exactly the same structure, except
744 // applying De Morgan's laws.
745
746 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
747 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
748
John McCall131d97d2010-08-22 08:30:07 +0000749 // This condition tests whether L.ptr == R.ptr. This must always be
750 // true for equality to hold.
751 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
752
753 // This condition, together with the assumption that L.ptr == R.ptr,
754 // tests whether the pointers are both null. ARM imposes an extra
755 // condition.
756 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
757 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
758
759 // This condition tests whether L.adj == R.adj. If this isn't
760 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000761 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
762 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000763 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
764
765 // Null member function pointers on ARM clear the low bit of Adj,
766 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000767 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000768 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
769
770 // Compute (l.adj | r.adj) & 1 and test it against zero.
771 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
772 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
773 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
774 "cmp.or.adj");
775 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
776 }
777
778 // Tie together all our conditions.
779 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
780 Result = Builder.CreateBinOp(And, PtrEq, Result,
781 Inequality ? "memptr.ne" : "memptr.eq");
782 return Result;
783}
784
785llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000786ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
787 llvm::Value *MemPtr,
788 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000789 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000790
791 /// For member data pointers, this is just a check against -1.
792 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000793 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000794 llvm::Value *NegativeOne =
795 llvm::Constant::getAllOnesValue(MemPtr->getType());
796 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
797 }
John McCall131d97d2010-08-22 08:30:07 +0000798
Daniel Dunbar914bc412011-04-19 23:10:47 +0000799 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000800 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000801
802 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
803 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
804
Daniel Dunbar914bc412011-04-19 23:10:47 +0000805 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
806 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000807 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000808 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000809 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000810 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000811 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
812 "memptr.isvirtual");
813 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000814 }
815
816 return Result;
817}
John McCall1c456c82010-08-22 06:43:33 +0000818
Reid Kleckner40ca9132014-05-13 22:05:45 +0000819bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
820 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
821 if (!RD)
822 return false;
823
Reid Klecknerd355ca72014-05-15 01:26:32 +0000824 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
825 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
826 // special members.
827 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000828 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
829 return true;
830 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000831 return false;
832}
833
John McCall614dbdc2010-08-22 21:01:12 +0000834/// The Itanium ABI requires non-zero initialization only for data
835/// member pointers, for which '0' is a valid offset.
836bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
837 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000838}
John McCall5d865c322010-08-31 07:33:07 +0000839
John McCall82fb8922012-09-25 10:10:39 +0000840/// The Itanium ABI always places an offset to the complete object
841/// at entry -2 in the vtable.
842llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
843 llvm::Value *ptr,
844 QualType type) {
845 // Grab the vtable pointer as an intptr_t*.
846 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
847
848 // Track back to entry -2 and pull out the offset there.
849 llvm::Value *offsetPtr =
850 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
851 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
852 offset->setAlignment(CGF.PointerAlignInBytes);
853
854 // Apply the offset.
855 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
856 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
857}
858
David Majnemer1162d252014-06-22 19:05:33 +0000859static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
860 // void *__dynamic_cast(const void *sub,
861 // const abi::__class_type_info *src,
862 // const abi::__class_type_info *dst,
863 // std::ptrdiff_t src2dst_offset);
864
865 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
866 llvm::Type *PtrDiffTy =
867 CGF.ConvertType(CGF.getContext().getPointerDiffType());
868
869 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
870
871 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
872
873 // Mark the function as nounwind readonly.
874 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
875 llvm::Attribute::ReadOnly };
876 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
877 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
878
879 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
880}
881
882static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
883 // void __cxa_bad_cast();
884 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
885 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
886}
887
888/// \brief Compute the src2dst_offset hint as described in the
889/// Itanium C++ ABI [2.9.7]
890static CharUnits computeOffsetHint(ASTContext &Context,
891 const CXXRecordDecl *Src,
892 const CXXRecordDecl *Dst) {
893 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
894 /*DetectVirtual=*/false);
895
896 // If Dst is not derived from Src we can skip the whole computation below and
897 // return that Src is not a public base of Dst. Record all inheritance paths.
898 if (!Dst->isDerivedFrom(Src, Paths))
899 return CharUnits::fromQuantity(-2ULL);
900
901 unsigned NumPublicPaths = 0;
902 CharUnits Offset;
903
904 // Now walk all possible inheritance paths.
905 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
906 ++I) {
907 if (I->Access != AS_public) // Ignore non-public inheritance.
908 continue;
909
910 ++NumPublicPaths;
911
912 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
913 // If the path contains a virtual base class we can't give any hint.
914 // -1: no hint.
915 if (J->Base->isVirtual())
916 return CharUnits::fromQuantity(-1ULL);
917
918 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
919 continue;
920
921 // Accumulate the base class offsets.
922 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
923 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
924 }
925 }
926
927 // -2: Src is not a public base of Dst.
928 if (NumPublicPaths == 0)
929 return CharUnits::fromQuantity(-2ULL);
930
931 // -3: Src is a multiple public base type but never a virtual base type.
932 if (NumPublicPaths > 1)
933 return CharUnits::fromQuantity(-3ULL);
934
935 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
936 // Return the offset of Src from the origin of Dst.
937 return Offset;
938}
939
940static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
941 // void __cxa_bad_typeid();
942 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
943
944 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
945}
946
947bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
948 QualType SrcRecordTy) {
949 return IsDeref;
950}
951
952void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
953 llvm::Value *Fn = getBadTypeidFn(CGF);
954 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
955 CGF.Builder.CreateUnreachable();
956}
957
958llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
959 QualType SrcRecordTy,
960 llvm::Value *ThisPtr,
961 llvm::Type *StdTypeInfoPtrTy) {
962 llvm::Value *Value =
963 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
964
965 // Load the type info.
966 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
967 return CGF.Builder.CreateLoad(Value);
968}
969
970bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
971 QualType SrcRecordTy) {
972 return SrcIsPtr;
973}
974
975llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
976 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
977 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
978 llvm::Type *PtrDiffLTy =
979 CGF.ConvertType(CGF.getContext().getPointerDiffType());
980 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
981
982 llvm::Value *SrcRTTI =
983 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
984 llvm::Value *DestRTTI =
985 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
986
987 // Compute the offset hint.
988 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
989 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
990 llvm::Value *OffsetHint = llvm::ConstantInt::get(
991 PtrDiffLTy,
992 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
993
994 // Emit the call to __dynamic_cast.
995 Value = CGF.EmitCastToVoidPtr(Value);
996
997 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
998 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
999 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1000
1001 /// C++ [expr.dynamic.cast]p9:
1002 /// A failed cast to reference type throws std::bad_cast
1003 if (DestTy->isReferenceType()) {
1004 llvm::BasicBlock *BadCastBlock =
1005 CGF.createBasicBlock("dynamic_cast.bad_cast");
1006
1007 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1008 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1009
1010 CGF.EmitBlock(BadCastBlock);
1011 EmitBadCastCall(CGF);
1012 }
1013
1014 return Value;
1015}
1016
1017llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1018 llvm::Value *Value,
1019 QualType SrcRecordTy,
1020 QualType DestTy) {
1021 llvm::Type *PtrDiffLTy =
1022 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1023 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1024
1025 // Get the vtable pointer.
1026 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1027
1028 // Get the offset-to-top from the vtable.
1029 llvm::Value *OffsetToTop =
1030 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1031 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1032
1033 // Finally, add the offset to the pointer.
1034 Value = CGF.EmitCastToVoidPtr(Value);
1035 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1036
1037 return CGF.Builder.CreateBitCast(Value, DestLTy);
1038}
1039
1040bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1041 llvm::Value *Fn = getBadCastFn(CGF);
1042 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1043 CGF.Builder.CreateUnreachable();
1044 return true;
1045}
1046
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001047llvm::Value *
1048ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1049 llvm::Value *This,
1050 const CXXRecordDecl *ClassDecl,
1051 const CXXRecordDecl *BaseClassDecl) {
1052 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1053 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001054 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1055 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001056
1057 llvm::Value *VBaseOffsetPtr =
1058 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1059 "vbase.offset.ptr");
1060 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1061 CGM.PtrDiffTy->getPointerTo());
1062
1063 llvm::Value *VBaseOffset =
1064 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1065
1066 return VBaseOffset;
1067}
1068
John McCall5d865c322010-08-31 07:33:07 +00001069/// The generic ABI passes 'this', plus a VTT if it's initializing a
1070/// base subobject.
Reid Kleckner89077a12013-12-17 19:46:40 +00001071void
1072ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
1073 CXXCtorType Type, CanQualType &ResTy,
1074 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001075 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001076
Reid Kleckner89077a12013-12-17 19:46:40 +00001077 // All parameters are already in place except VTT, which goes after 'this'.
1078 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001079
1080 // Check if we need to add a VTT parameter (which has type void **).
1081 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
Reid Kleckner89077a12013-12-17 19:46:40 +00001082 ArgTys.insert(ArgTys.begin() + 1,
1083 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001084}
1085
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001086void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1087 // Just make sure we're in sync with TargetCXXABI.
1088 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1089
Rafael Espindolac3cde362013-12-09 14:51:17 +00001090 // The constructor used for constructing this as a base class;
1091 // ignores virtual bases.
1092 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1093
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001094 // The constructor used for constructing this as a complete class;
1095 // constucts the virtual bases, then calls the base constructor.
1096 if (!D->getParent()->isAbstract()) {
1097 // We don't need to emit the complete ctor if the class is abstract.
1098 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1099 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001100}
1101
John McCall5d865c322010-08-31 07:33:07 +00001102/// The generic ABI passes 'this', plus a VTT if it's destroying a
1103/// base subobject.
1104void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
1105 CXXDtorType Type,
1106 CanQualType &ResTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001107 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001108 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001109
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001110 // 'this' parameter is already there, as well as 'this' return if
1111 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
John McCall5d865c322010-08-31 07:33:07 +00001112
1113 // Check if we need to add a VTT parameter (which has type void **).
1114 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
1115 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
1116}
1117
Reid Klecknere7de47e2013-07-22 13:51:44 +00001118void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001119 // The destructor used for destructing this as a base class; ignores
1120 // virtual bases.
1121 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001122
1123 // The destructor used for destructing this as a most-derived class;
1124 // call the base destructor and then destructs any virtual bases.
1125 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1126
Rafael Espindolac3cde362013-12-09 14:51:17 +00001127 // The destructor in a virtual table is always a 'deleting'
1128 // destructor, which calls the complete destructor and then uses the
1129 // appropriate operator delete.
1130 if (D->isVirtual())
1131 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001132}
1133
Reid Kleckner89077a12013-12-17 19:46:40 +00001134void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1135 QualType &ResTy,
1136 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001137 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001138 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001139
1140 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001141 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001142 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001143
1144 // FIXME: avoid the fake decl
1145 QualType T = Context.getPointerType(Context.VoidPtrTy);
1146 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001147 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001148 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001149 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001150 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001151 }
1152}
1153
John McCall5d865c322010-08-31 07:33:07 +00001154void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1155 /// Initialize the 'this' slot.
1156 EmitThisParam(CGF);
1157
1158 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001159 if (getStructorImplicitParamDecl(CGF)) {
1160 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1161 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001162 }
John McCall5d865c322010-08-31 07:33:07 +00001163
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001164 /// If this is a function that the ABI specifies returns 'this', initialize
1165 /// the return slot to 'this' at the start of the function.
1166 ///
1167 /// Unlike the setting of return types, this is done within the ABI
1168 /// implementation instead of by clients of CGCXXABI because:
1169 /// 1) getThisValue is currently protected
1170 /// 2) in theory, an ABI could implement 'this' returns some other way;
1171 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001172 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001173 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001174}
1175
Reid Kleckner89077a12013-12-17 19:46:40 +00001176unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1177 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1178 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1179 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1180 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001181
Reid Kleckner89077a12013-12-17 19:46:40 +00001182 // Insert the implicit 'vtt' argument as the second argument.
1183 llvm::Value *VTT =
1184 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1185 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1186 Args.insert(Args.begin() + 1,
1187 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1188 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001189}
1190
1191void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1192 const CXXDestructorDecl *DD,
1193 CXXDtorType Type, bool ForVirtualBase,
1194 bool Delegating, llvm::Value *This) {
1195 GlobalDecl GD(DD, Type);
1196 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1197 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1198
Craig Topper8a13c412014-05-21 05:09:00 +00001199 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001200 if (getContext().getLangOpts().AppleKext)
1201 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1202
1203 if (!Callee)
1204 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1205
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001206 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1207 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001208}
1209
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001210void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1211 const CXXRecordDecl *RD) {
1212 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1213 if (VTable->hasInitializer())
1214 return;
1215
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001216 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001217 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1218 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001219 llvm::Constant *RTTI =
1220 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001221
1222 // Create and set the initializer.
1223 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1224 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001225 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001226 VTable->setInitializer(Init);
1227
1228 // Set the correct linkage.
1229 VTable->setLinkage(Linkage);
1230
1231 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001232 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001233
1234 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1235 // we will emit the typeinfo for the fundamental types. This is the
1236 // same behaviour as GCC.
1237 const DeclContext *DC = RD->getDeclContext();
1238 if (RD->getIdentifier() &&
1239 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1240 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1241 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1242 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001243 EmitFundamentalRTTIDescriptors();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001244}
1245
1246llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1247 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1248 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1249 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1250 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1251
1252 llvm::Value *VTableAddressPoint;
1253 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1254 // Get the secondary vpointer index.
1255 uint64_t VirtualPointerIndex =
1256 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1257
1258 /// Load the VTT.
1259 llvm::Value *VTT = CGF.LoadCXXVTT();
1260 if (VirtualPointerIndex)
1261 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1262
1263 // And load the address point from the VTT.
1264 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1265 } else {
1266 llvm::Constant *VTable =
1267 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001268 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1269 .getVTableLayout(VTableClass)
1270 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001271 VTableAddressPoint =
1272 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1273 }
1274
1275 return VTableAddressPoint;
1276}
1277
1278llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1279 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1280 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1281
1282 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001283 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1284 .getVTableLayout(VTableClass)
1285 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001286 llvm::Value *Indices[] = {
1287 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1288 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1289 };
1290
1291 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1292}
1293
1294llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1295 CharUnits VPtrOffset) {
1296 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1297
1298 llvm::GlobalVariable *&VTable = VTables[RD];
1299 if (VTable)
1300 return VTable;
1301
1302 // Queue up this v-table for possible deferred emission.
1303 CGM.addDeferredVTable(RD);
1304
1305 SmallString<256> OutName;
1306 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001307 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001308 Out.flush();
1309 StringRef Name = OutName.str();
1310
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001311 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001312 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1313 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1314
1315 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1316 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1317 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001318
1319 if (RD->hasAttr<DLLImportAttr>())
1320 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1321 else if (RD->hasAttr<DLLExportAttr>())
1322 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1323
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001324 return VTable;
1325}
1326
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001327llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1328 GlobalDecl GD,
1329 llvm::Value *This,
1330 llvm::Type *Ty) {
1331 GD = GD.getCanonicalDecl();
1332 Ty = Ty->getPointerTo()->getPointerTo();
1333 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1334
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001335 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001336 llvm::Value *VFuncPtr =
1337 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1338 return CGF.Builder.CreateLoad(VFuncPtr);
1339}
1340
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001341void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1342 const CXXDestructorDecl *Dtor,
1343 CXXDtorType DtorType,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001344 llvm::Value *This,
1345 const CXXMemberCallExpr *CE) {
1346 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001347 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1348
1349 const CGFunctionInfo *FInfo
1350 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1351 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001352 llvm::Value *Callee =
1353 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001354
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001355 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1356 /*ImplicitParam=*/nullptr, QualType(), CE);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001357}
1358
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001359void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001360 CodeGenVTables &VTables = CGM.getVTables();
1361 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001362 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001363}
1364
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001365static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1366 llvm::Value *Ptr,
1367 int64_t NonVirtualAdjustment,
1368 int64_t VirtualAdjustment,
1369 bool IsReturnAdjustment) {
1370 if (!NonVirtualAdjustment && !VirtualAdjustment)
1371 return Ptr;
1372
1373 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1374 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1375
1376 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1377 // Perform the non-virtual adjustment for a base-to-derived cast.
1378 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1379 }
1380
1381 if (VirtualAdjustment) {
1382 llvm::Type *PtrDiffTy =
1383 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1384
1385 // Perform the virtual adjustment.
1386 llvm::Value *VTablePtrPtr =
1387 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1388
1389 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1390
1391 llvm::Value *OffsetPtr =
1392 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1393
1394 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1395
1396 // Load the adjustment offset from the vtable.
1397 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1398
1399 // Adjust our pointer.
1400 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1401 }
1402
1403 if (NonVirtualAdjustment && IsReturnAdjustment) {
1404 // Perform the non-virtual adjustment for a derived-to-base cast.
1405 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1406 }
1407
1408 // Cast back to the original type.
1409 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1410}
1411
1412llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1413 llvm::Value *This,
1414 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001415 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1416 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001417 /*IsReturnAdjustment=*/false);
1418}
1419
1420llvm::Value *
1421ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1422 const ReturnAdjustment &RA) {
1423 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1424 RA.Virtual.Itanium.VBaseOffsetOffset,
1425 /*IsReturnAdjustment=*/true);
1426}
1427
John McCall5d865c322010-08-31 07:33:07 +00001428void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1429 RValue RV, QualType ResultType) {
1430 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1431 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1432
1433 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001434 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001435 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1436 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1437 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1438}
John McCall8ed55a52010-09-02 09:58:18 +00001439
1440/************************** Array allocation cookies **************************/
1441
John McCallb91cd662012-05-01 05:23:51 +00001442CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1443 // The array cookie is a size_t; pad that up to the element alignment.
1444 // The cookie is actually right-justified in that space.
1445 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1446 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001447}
1448
1449llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1450 llvm::Value *NewPtr,
1451 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001452 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001453 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001454 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001455
Micah Villmowea2fea22012-10-25 15:39:14 +00001456 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001457
John McCall9bca9232010-09-02 10:25:57 +00001458 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001459 QualType SizeTy = Ctx.getSizeType();
1460 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1461
1462 // The size of the cookie.
1463 CharUnits CookieSize =
1464 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001465 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001466
1467 // Compute an offset to the cookie.
1468 llvm::Value *CookiePtr = NewPtr;
1469 CharUnits CookieOffset = CookieSize - SizeSize;
1470 if (!CookieOffset.isZero())
1471 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1472 CookieOffset.getQuantity());
1473
1474 // Write the number of elements into the appropriate slot.
1475 llvm::Value *NumElementsPtr
1476 = CGF.Builder.CreateBitCast(CookiePtr,
1477 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1478 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1479
1480 // Finally, compute a pointer to the actual data buffer by skipping
1481 // over the cookie completely.
1482 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1483 CookieSize.getQuantity());
1484}
1485
John McCallb91cd662012-05-01 05:23:51 +00001486llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1487 llvm::Value *allocPtr,
1488 CharUnits cookieSize) {
1489 // The element size is right-justified in the cookie.
1490 llvm::Value *numElementsPtr = allocPtr;
1491 CharUnits numElementsOffset =
1492 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1493 if (!numElementsOffset.isZero())
1494 numElementsPtr =
1495 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1496 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001497
Micah Villmowea2fea22012-10-25 15:39:14 +00001498 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001499 numElementsPtr =
1500 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1501 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001502}
1503
John McCallb91cd662012-05-01 05:23:51 +00001504CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001505 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001506 // struct array_cookie {
1507 // std::size_t element_size; // element_size != 0
1508 // std::size_t element_count;
1509 // };
John McCallc19c7062013-01-25 23:36:19 +00001510 // But the base ABI doesn't give anything an alignment greater than
1511 // 8, so we can dismiss this as typical ABI-author blindness to
1512 // actual language complexity and round up to the element alignment.
1513 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1514 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001515}
1516
1517llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001518 llvm::Value *newPtr,
1519 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001520 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001521 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001522 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001523
John McCallc19c7062013-01-25 23:36:19 +00001524 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1525 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001526
1527 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001528 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001529
1530 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001531 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1532 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1533 getContext().getTypeSizeInChars(elementType).getQuantity());
1534 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001535
1536 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001537 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1538 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001539
1540 // Finally, compute a pointer to the actual data buffer by skipping
1541 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001542 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1543 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1544 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001545}
1546
John McCallb91cd662012-05-01 05:23:51 +00001547llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1548 llvm::Value *allocPtr,
1549 CharUnits cookieSize) {
1550 // The number of elements is at offset sizeof(size_t) relative to
1551 // the allocated pointer.
1552 llvm::Value *numElementsPtr
1553 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001554
Micah Villmowea2fea22012-10-25 15:39:14 +00001555 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001556 numElementsPtr =
1557 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1558 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001559}
1560
John McCall68ff0372010-09-08 01:44:27 +00001561/*********************** Static local initialization **************************/
1562
1563static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001564 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001565 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001566 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001567 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001568 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001569 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001570 llvm::AttributeSet::get(CGM.getLLVMContext(),
1571 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001572 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001573}
1574
1575static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001576 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001577 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001578 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001579 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001580 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001581 llvm::AttributeSet::get(CGM.getLLVMContext(),
1582 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001583 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001584}
1585
1586static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001587 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001588 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001589 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001590 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001591 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001592 llvm::AttributeSet::get(CGM.getLLVMContext(),
1593 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001594 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001595}
1596
1597namespace {
1598 struct CallGuardAbort : EHScopeStack::Cleanup {
1599 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001600 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001601
Craig Topper4f12f102014-03-12 06:41:41 +00001602 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001603 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1604 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001605 }
1606 };
1607}
1608
1609/// The ARM code here follows the Itanium code closely enough that we
1610/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001611void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1612 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001613 llvm::GlobalVariable *var,
1614 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001615 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001616
Richard Smithdbf74ba2013-04-14 23:01:42 +00001617 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001618 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001619 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1620 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001621
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001622 // If we have a global variable with internal linkage and thread-safe statics
1623 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001624 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1625
1626 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001627 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001628 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001629 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001630 // Guard variables are 64 bits in the generic ABI and size width on ARM
1631 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001632 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001633 }
John McCallb88a5662012-03-30 21:00:39 +00001634 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001635
John McCallb88a5662012-03-30 21:00:39 +00001636 // Create the guard variable if we don't already have it (as we
1637 // might if we're double-emitting this function body).
1638 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1639 if (!guard) {
1640 // Mangle the name for the guard.
1641 SmallString<256> guardName;
1642 {
1643 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001644 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001645 out.flush();
1646 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001647
John McCallb88a5662012-03-30 21:00:39 +00001648 // Create the guard variable with a zero-initializer.
1649 // Just absorb linkage and visibility from the guarded variable.
1650 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1651 false, var->getLinkage(),
1652 llvm::ConstantInt::get(guardTy, 0),
1653 guardName.str());
1654 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001655 // If the variable is thread-local, so is its guard variable.
1656 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001657
1658 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1659 }
John McCall87590e62012-03-30 07:09:50 +00001660
John McCall68ff0372010-09-08 01:44:27 +00001661 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001662 //
John McCall68ff0372010-09-08 01:44:27 +00001663 // Itanium C++ ABI 3.3.2:
1664 // The following is pseudo-code showing how these functions can be used:
1665 // if (obj_guard.first_byte == 0) {
1666 // if ( __cxa_guard_acquire (&obj_guard) ) {
1667 // try {
1668 // ... initialize the object ...;
1669 // } catch (...) {
1670 // __cxa_guard_abort (&obj_guard);
1671 // throw;
1672 // }
1673 // ... queue object destructor with __cxa_atexit() ...;
1674 // __cxa_guard_release (&obj_guard);
1675 // }
1676 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001677
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001678 // Load the first byte of the guard variable.
1679 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001680 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001681 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001682
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001683 // Itanium ABI:
1684 // An implementation supporting thread-safety on multiprocessor
1685 // systems must also guarantee that references to the initialized
1686 // object do not occur before the load of the initialization flag.
1687 //
1688 // In LLVM, we do this by marking the load Acquire.
1689 if (threadsafe)
1690 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001691
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001692 // For ARM, we should only check the first bit, rather than the entire byte:
1693 //
1694 // ARM C++ ABI 3.2.3.1:
1695 // To support the potential use of initialization guard variables
1696 // as semaphores that are the target of ARM SWP and LDREX/STREX
1697 // synchronizing instructions we define a static initialization
1698 // guard variable to be a 4-byte aligned, 4-byte word with the
1699 // following inline access protocol.
1700 // #define INITIALIZED 1
1701 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1702 // if (__cxa_guard_acquire(&obj_guard))
1703 // ...
1704 // }
1705 //
1706 // and similarly for ARM64:
1707 //
1708 // ARM64 C++ ABI 3.2.2:
1709 // This ABI instead only specifies the value bit 0 of the static guard
1710 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1711 // variable is not initialized and 1 when it is.
1712 llvm::Value *V =
1713 (UseARMGuardVarABI && !useInt8GuardVariable)
1714 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1715 : LI;
1716 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001717
1718 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1719 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1720
1721 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001722 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001723
1724 CGF.EmitBlock(InitCheckBlock);
1725
1726 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001727 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001728 // Call __cxa_guard_acquire.
1729 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001730 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001731
1732 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1733
1734 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1735 InitBlock, EndBlock);
1736
1737 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001738 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001739
1740 CGF.EmitBlock(InitBlock);
1741 }
1742
1743 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001744 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001745
John McCall5aa52592011-06-17 07:33:57 +00001746 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001747 // Pop the guard-abort cleanup if we pushed one.
1748 CGF.PopCleanupBlock();
1749
1750 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001751 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001752 } else {
John McCallb88a5662012-03-30 21:00:39 +00001753 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001754 }
1755
1756 CGF.EmitBlock(EndBlock);
1757}
John McCallc84ed6a2012-05-01 06:13:13 +00001758
1759/// Register a global destructor using __cxa_atexit.
1760static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1761 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001762 llvm::Constant *addr,
1763 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001764 const char *Name = "__cxa_atexit";
1765 if (TLS) {
1766 const llvm::Triple &T = CGF.getTarget().getTriple();
1767 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1768 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001769
John McCallc84ed6a2012-05-01 06:13:13 +00001770 // We're assuming that the destructor function is something we can
1771 // reasonably call with the default CC. Go ahead and cast it to the
1772 // right prototype.
1773 llvm::Type *dtorTy =
1774 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1775
1776 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1777 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1778 llvm::FunctionType *atexitTy =
1779 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1780
1781 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001782 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001783 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1784 fn->setDoesNotThrow();
1785
1786 // Create a variable that binds the atexit to this shared object.
1787 llvm::Constant *handle =
1788 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1789
1790 llvm::Value *args[] = {
1791 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1792 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1793 handle
1794 };
John McCall882987f2013-02-28 19:01:20 +00001795 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001796}
1797
1798/// Register a global destructor as best as we know how.
1799void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001800 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001801 llvm::Constant *dtor,
1802 llvm::Constant *addr) {
1803 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001804 if (CGM.getCodeGenOpts().CXAAtExit)
1805 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1806
1807 if (D.getTLSKind())
1808 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001809
1810 // In Apple kexts, we want to add a global destructor entry.
1811 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001812 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001813 // Generate a global destructor entry.
1814 return CGM.AddCXXDtorEntry(dtor, addr);
1815 }
1816
David Blaikieebe87e12013-08-27 23:57:18 +00001817 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001818}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001819
David Majnemer9b21c332014-07-11 20:28:10 +00001820static bool isThreadWrapperReplaceable(const VarDecl *VD,
1821 CodeGen::CodeGenModule &CGM) {
1822 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1823 // OS X prefers to have references to thread local variables to go through
1824 // the thread wrapper instead of directly referencing the backing variable.
1825 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1826 CGM.getTarget().getTriple().isMacOSX();
1827}
1828
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001829/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001830/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001831/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001832static llvm::GlobalValue::LinkageTypes
1833getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1834 llvm::GlobalValue::LinkageTypes VarLinkage =
1835 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1836
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001837 // For internal linkage variables, we don't need an external or weak wrapper.
1838 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1839 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001840
David Majnemer9b21c332014-07-11 20:28:10 +00001841 // If the thread wrapper is replaceable, give it appropriate linkage.
1842 if (isThreadWrapperReplaceable(VD, CGM)) {
1843 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1844 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1845 return llvm::GlobalVariable::WeakAnyLinkage;
1846 return VarLinkage;
1847 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001848 return llvm::GlobalValue::WeakODRLinkage;
1849}
1850
1851llvm::Function *
1852ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1853 llvm::GlobalVariable *Var) {
1854 // Mangle the name for the thread_local wrapper function.
1855 SmallString<256> WrapperName;
1856 {
1857 llvm::raw_svector_ostream Out(WrapperName);
1858 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1859 Out.flush();
1860 }
1861
1862 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1863 return cast<llvm::Function>(V);
1864
1865 llvm::Type *RetTy = Var->getType();
1866 if (VD->getType()->isReferenceType())
1867 RetTy = RetTy->getPointerElementType();
1868
1869 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00001870 llvm::Function *Wrapper =
1871 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1872 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001873 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00001874 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001875 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001876 return Wrapper;
1877}
1878
1879void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +00001880 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001881 llvm::Function *InitFunc) {
1882 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1883 const VarDecl *VD = Decls[I].first;
1884 llvm::GlobalVariable *Var = Decls[I].second;
1885
David Majnemer9b21c332014-07-11 20:28:10 +00001886 // Some targets require that all access to thread local variables go through
1887 // the thread wrapper. This means that we cannot attempt to create a thread
1888 // wrapper or a thread helper.
1889 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1890 continue;
1891
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001892 // Mangle the name for the thread_local initialization function.
1893 SmallString<256> InitFnName;
1894 {
1895 llvm::raw_svector_ostream Out(InitFnName);
1896 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1897 Out.flush();
1898 }
1899
1900 // If we have a definition for the variable, emit the initialization
1901 // function as an alias to the global Init function (if any). Otherwise,
1902 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001903 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001904 bool InitIsInitFunc = false;
1905 if (VD->hasDefinition()) {
1906 InitIsInitFunc = true;
1907 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001908 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1909 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001910 } else {
1911 // Emit a weak global function referring to the initialization function.
1912 // This function will not exist if the TU defining the thread_local
1913 // variable in question does not need any dynamic initialization for
1914 // its thread_local variables.
1915 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1916 Init = llvm::Function::Create(
1917 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1918 &CGM.getModule());
1919 }
1920
1921 if (Init)
1922 Init->setVisibility(Var->getVisibility());
1923
1924 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1925 llvm::LLVMContext &Context = CGM.getModule().getContext();
1926 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1927 CGBuilderTy Builder(Entry);
1928 if (InitIsInitFunc) {
1929 if (Init)
1930 Builder.CreateCall(Init);
1931 } else {
1932 // Don't know whether we have an init function. Call it if it exists.
1933 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1934 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1935 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1936 Builder.CreateCondBr(Have, InitBB, ExitBB);
1937
1938 Builder.SetInsertPoint(InitBB);
1939 Builder.CreateCall(Init);
1940 Builder.CreateBr(ExitBB);
1941
1942 Builder.SetInsertPoint(ExitBB);
1943 }
1944
1945 // For a reference, the result of the wrapper function is a pointer to
1946 // the referenced object.
1947 llvm::Value *Val = Var;
1948 if (VD->getType()->isReferenceType()) {
1949 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1950 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1951 Val = LI;
1952 }
1953
1954 Builder.CreateRet(Val);
1955 }
1956}
1957
Richard Smith0f383742014-03-26 22:48:22 +00001958LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1959 const VarDecl *VD,
1960 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001961 QualType T = VD->getType();
1962 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1963 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1964 llvm::Function *Wrapper =
1965 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1966
1967 Val = CGF.Builder.CreateCall(Wrapper);
1968
1969 LValue LV;
1970 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00001971 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001972 else
Richard Smith0f383742014-03-26 22:48:22 +00001973 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001974 // FIXME: need setObjCGCLValueClass?
1975 return LV;
1976}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001977
1978/// Return whether the given global decl needs a VTT parameter, which it does
1979/// if it's a base constructor or destructor with virtual bases.
1980bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1981 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1982
1983 // We don't have any virtual bases, just return early.
1984 if (!MD->getParent()->getNumVBases())
1985 return false;
1986
1987 // Check if we have a base constructor.
1988 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1989 return true;
1990
1991 // Check if we have a base destructor.
1992 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1993 return true;
1994
1995 return false;
1996}
David Majnemere2cb8d12014-07-07 06:20:47 +00001997
1998namespace {
1999class ItaniumRTTIBuilder {
2000 CodeGenModule &CGM; // Per-module state.
2001 llvm::LLVMContext &VMContext;
2002 const ItaniumCXXABI &CXXABI; // Per-module state.
2003
2004 /// Fields - The fields of the RTTI descriptor currently being built.
2005 SmallVector<llvm::Constant *, 16> Fields;
2006
2007 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2008 llvm::GlobalVariable *
2009 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2010
2011 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2012 /// descriptor of the given type.
2013 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2014
2015 /// BuildVTablePointer - Build the vtable pointer for the given type.
2016 void BuildVTablePointer(const Type *Ty);
2017
2018 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2019 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2020 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2021
2022 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2023 /// classes with bases that do not satisfy the abi::__si_class_type_info
2024 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2025 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2026
2027 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2028 /// for pointer types.
2029 void BuildPointerTypeInfo(QualType PointeeTy);
2030
2031 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2032 /// type_info for an object type.
2033 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2034
2035 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2036 /// struct, used for member pointer types.
2037 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2038
2039public:
2040 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2041 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2042
2043 // Pointer type info flags.
2044 enum {
2045 /// PTI_Const - Type has const qualifier.
2046 PTI_Const = 0x1,
2047
2048 /// PTI_Volatile - Type has volatile qualifier.
2049 PTI_Volatile = 0x2,
2050
2051 /// PTI_Restrict - Type has restrict qualifier.
2052 PTI_Restrict = 0x4,
2053
2054 /// PTI_Incomplete - Type is incomplete.
2055 PTI_Incomplete = 0x8,
2056
2057 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2058 /// (in pointer to member).
2059 PTI_ContainingClassIncomplete = 0x10
2060 };
2061
2062 // VMI type info flags.
2063 enum {
2064 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2065 VMI_NonDiamondRepeat = 0x1,
2066
2067 /// VMI_DiamondShaped - Class is diamond shaped.
2068 VMI_DiamondShaped = 0x2
2069 };
2070
2071 // Base class type info flags.
2072 enum {
2073 /// BCTI_Virtual - Base class is virtual.
2074 BCTI_Virtual = 0x1,
2075
2076 /// BCTI_Public - Base class is public.
2077 BCTI_Public = 0x2
2078 };
2079
2080 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2081 ///
2082 /// \param Force - true to force the creation of this RTTI value
2083 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2084};
2085}
2086
2087llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2088 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2089 SmallString<256> OutName;
2090 llvm::raw_svector_ostream Out(OutName);
2091 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2092 Out.flush();
2093 StringRef Name = OutName.str();
2094
2095 // We know that the mangled name of the type starts at index 4 of the
2096 // mangled name of the typename, so we can just index into it in order to
2097 // get the mangled name of the type.
2098 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2099 Name.substr(4));
2100
2101 llvm::GlobalVariable *GV =
2102 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2103
2104 GV->setInitializer(Init);
2105
2106 return GV;
2107}
2108
2109llvm::Constant *
2110ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2111 // Mangle the RTTI name.
2112 SmallString<256> OutName;
2113 llvm::raw_svector_ostream Out(OutName);
2114 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2115 Out.flush();
2116 StringRef Name = OutName.str();
2117
2118 // Look for an existing global.
2119 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2120
2121 if (!GV) {
2122 // Create a new global variable.
2123 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2124 /*Constant=*/true,
2125 llvm::GlobalValue::ExternalLinkage, nullptr,
2126 Name);
2127 }
2128
2129 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2130}
2131
2132/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2133/// info for that type is defined in the standard library.
2134static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2135 // Itanium C++ ABI 2.9.2:
2136 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2137 // the run-time support library. Specifically, the run-time support
2138 // library should contain type_info objects for the types X, X* and
2139 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2140 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2141 // long, unsigned long, long long, unsigned long long, float, double,
2142 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2143 // half-precision floating point types.
2144 switch (Ty->getKind()) {
2145 case BuiltinType::Void:
2146 case BuiltinType::NullPtr:
2147 case BuiltinType::Bool:
2148 case BuiltinType::WChar_S:
2149 case BuiltinType::WChar_U:
2150 case BuiltinType::Char_U:
2151 case BuiltinType::Char_S:
2152 case BuiltinType::UChar:
2153 case BuiltinType::SChar:
2154 case BuiltinType::Short:
2155 case BuiltinType::UShort:
2156 case BuiltinType::Int:
2157 case BuiltinType::UInt:
2158 case BuiltinType::Long:
2159 case BuiltinType::ULong:
2160 case BuiltinType::LongLong:
2161 case BuiltinType::ULongLong:
2162 case BuiltinType::Half:
2163 case BuiltinType::Float:
2164 case BuiltinType::Double:
2165 case BuiltinType::LongDouble:
2166 case BuiltinType::Char16:
2167 case BuiltinType::Char32:
2168 case BuiltinType::Int128:
2169 case BuiltinType::UInt128:
2170 case BuiltinType::OCLImage1d:
2171 case BuiltinType::OCLImage1dArray:
2172 case BuiltinType::OCLImage1dBuffer:
2173 case BuiltinType::OCLImage2d:
2174 case BuiltinType::OCLImage2dArray:
2175 case BuiltinType::OCLImage3d:
2176 case BuiltinType::OCLSampler:
2177 case BuiltinType::OCLEvent:
2178 return true;
2179
2180 case BuiltinType::Dependent:
2181#define BUILTIN_TYPE(Id, SingletonId)
2182#define PLACEHOLDER_TYPE(Id, SingletonId) \
2183 case BuiltinType::Id:
2184#include "clang/AST/BuiltinTypes.def"
2185 llvm_unreachable("asking for RRTI for a placeholder type!");
2186
2187 case BuiltinType::ObjCId:
2188 case BuiltinType::ObjCClass:
2189 case BuiltinType::ObjCSel:
2190 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2191 }
2192
2193 llvm_unreachable("Invalid BuiltinType Kind!");
2194}
2195
2196static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2197 QualType PointeeTy = PointerTy->getPointeeType();
2198 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2199 if (!BuiltinTy)
2200 return false;
2201
2202 // Check the qualifiers.
2203 Qualifiers Quals = PointeeTy.getQualifiers();
2204 Quals.removeConst();
2205
2206 if (!Quals.empty())
2207 return false;
2208
2209 return TypeInfoIsInStandardLibrary(BuiltinTy);
2210}
2211
2212/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2213/// information for the given type exists in the standard library.
2214static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2215 // Type info for builtin types is defined in the standard library.
2216 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2217 return TypeInfoIsInStandardLibrary(BuiltinTy);
2218
2219 // Type info for some pointer types to builtin types is defined in the
2220 // standard library.
2221 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2222 return TypeInfoIsInStandardLibrary(PointerTy);
2223
2224 return false;
2225}
2226
2227/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2228/// the given type exists somewhere else, and that we should not emit the type
2229/// information in this translation unit. Assumes that it is not a
2230/// standard-library type.
2231static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2232 QualType Ty) {
2233 ASTContext &Context = CGM.getContext();
2234
2235 // If RTTI is disabled, assume it might be disabled in the
2236 // translation unit that defines any potential key function, too.
2237 if (!Context.getLangOpts().RTTI) return false;
2238
2239 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2240 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2241 if (!RD->hasDefinition())
2242 return false;
2243
2244 if (!RD->isDynamicClass())
2245 return false;
2246
2247 // FIXME: this may need to be reconsidered if the key function
2248 // changes.
2249 return CGM.getVTables().isVTableExternal(RD);
2250 }
2251
2252 return false;
2253}
2254
2255/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2256static bool IsIncompleteClassType(const RecordType *RecordTy) {
2257 return !RecordTy->getDecl()->isCompleteDefinition();
2258}
2259
2260/// ContainsIncompleteClassType - Returns whether the given type contains an
2261/// incomplete class type. This is true if
2262///
2263/// * The given type is an incomplete class type.
2264/// * The given type is a pointer type whose pointee type contains an
2265/// incomplete class type.
2266/// * The given type is a member pointer type whose class is an incomplete
2267/// class type.
2268/// * The given type is a member pointer type whoise pointee type contains an
2269/// incomplete class type.
2270/// is an indirect or direct pointer to an incomplete class type.
2271static bool ContainsIncompleteClassType(QualType Ty) {
2272 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2273 if (IsIncompleteClassType(RecordTy))
2274 return true;
2275 }
2276
2277 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2278 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2279
2280 if (const MemberPointerType *MemberPointerTy =
2281 dyn_cast<MemberPointerType>(Ty)) {
2282 // Check if the class type is incomplete.
2283 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2284 if (IsIncompleteClassType(ClassType))
2285 return true;
2286
2287 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2288 }
2289
2290 return false;
2291}
2292
2293// CanUseSingleInheritance - Return whether the given record decl has a "single,
2294// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2295// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2296static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2297 // Check the number of bases.
2298 if (RD->getNumBases() != 1)
2299 return false;
2300
2301 // Get the base.
2302 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2303
2304 // Check that the base is not virtual.
2305 if (Base->isVirtual())
2306 return false;
2307
2308 // Check that the base is public.
2309 if (Base->getAccessSpecifier() != AS_public)
2310 return false;
2311
2312 // Check that the class is dynamic iff the base is.
2313 const CXXRecordDecl *BaseDecl =
2314 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2315 if (!BaseDecl->isEmpty() &&
2316 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2317 return false;
2318
2319 return true;
2320}
2321
2322void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2323 // abi::__class_type_info.
2324 static const char * const ClassTypeInfo =
2325 "_ZTVN10__cxxabiv117__class_type_infoE";
2326 // abi::__si_class_type_info.
2327 static const char * const SIClassTypeInfo =
2328 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2329 // abi::__vmi_class_type_info.
2330 static const char * const VMIClassTypeInfo =
2331 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2332
2333 const char *VTableName = nullptr;
2334
2335 switch (Ty->getTypeClass()) {
2336#define TYPE(Class, Base)
2337#define ABSTRACT_TYPE(Class, Base)
2338#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2339#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2340#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2341#include "clang/AST/TypeNodes.def"
2342 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2343
2344 case Type::LValueReference:
2345 case Type::RValueReference:
2346 llvm_unreachable("References shouldn't get here");
2347
2348 case Type::Auto:
2349 llvm_unreachable("Undeduced auto type shouldn't get here");
2350
2351 case Type::Builtin:
2352 // GCC treats vector and complex types as fundamental types.
2353 case Type::Vector:
2354 case Type::ExtVector:
2355 case Type::Complex:
2356 case Type::Atomic:
2357 // FIXME: GCC treats block pointers as fundamental types?!
2358 case Type::BlockPointer:
2359 // abi::__fundamental_type_info.
2360 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2361 break;
2362
2363 case Type::ConstantArray:
2364 case Type::IncompleteArray:
2365 case Type::VariableArray:
2366 // abi::__array_type_info.
2367 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2368 break;
2369
2370 case Type::FunctionNoProto:
2371 case Type::FunctionProto:
2372 // abi::__function_type_info.
2373 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2374 break;
2375
2376 case Type::Enum:
2377 // abi::__enum_type_info.
2378 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2379 break;
2380
2381 case Type::Record: {
2382 const CXXRecordDecl *RD =
2383 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2384
2385 if (!RD->hasDefinition() || !RD->getNumBases()) {
2386 VTableName = ClassTypeInfo;
2387 } else if (CanUseSingleInheritance(RD)) {
2388 VTableName = SIClassTypeInfo;
2389 } else {
2390 VTableName = VMIClassTypeInfo;
2391 }
2392
2393 break;
2394 }
2395
2396 case Type::ObjCObject:
2397 // Ignore protocol qualifiers.
2398 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2399
2400 // Handle id and Class.
2401 if (isa<BuiltinType>(Ty)) {
2402 VTableName = ClassTypeInfo;
2403 break;
2404 }
2405
2406 assert(isa<ObjCInterfaceType>(Ty));
2407 // Fall through.
2408
2409 case Type::ObjCInterface:
2410 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2411 VTableName = SIClassTypeInfo;
2412 } else {
2413 VTableName = ClassTypeInfo;
2414 }
2415 break;
2416
2417 case Type::ObjCObjectPointer:
2418 case Type::Pointer:
2419 // abi::__pointer_type_info.
2420 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2421 break;
2422
2423 case Type::MemberPointer:
2424 // abi::__pointer_to_member_type_info.
2425 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2426 break;
2427 }
2428
2429 llvm::Constant *VTable =
2430 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2431
2432 llvm::Type *PtrDiffTy =
2433 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2434
2435 // The vtable address point is 2.
2436 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2437 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2438 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2439
2440 Fields.push_back(VTable);
2441}
2442
2443/// \brief Return the linkage that the type info and type info name constants
2444/// should have for the given type.
2445static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2446 QualType Ty) {
2447 // Itanium C++ ABI 2.9.5p7:
2448 // In addition, it and all of the intermediate abi::__pointer_type_info
2449 // structs in the chain down to the abi::__class_type_info for the
2450 // incomplete class type must be prevented from resolving to the
2451 // corresponding type_info structs for the complete class type, possibly
2452 // by making them local static objects. Finally, a dummy class RTTI is
2453 // generated for the incomplete type that will not resolve to the final
2454 // complete class RTTI (because the latter need not exist), possibly by
2455 // making it a local static object.
2456 if (ContainsIncompleteClassType(Ty))
2457 return llvm::GlobalValue::InternalLinkage;
2458
2459 switch (Ty->getLinkage()) {
2460 case NoLinkage:
2461 case InternalLinkage:
2462 case UniqueExternalLinkage:
2463 return llvm::GlobalValue::InternalLinkage;
2464
2465 case VisibleNoLinkage:
2466 case ExternalLinkage:
2467 if (!CGM.getLangOpts().RTTI) {
2468 // RTTI is not enabled, which means that this type info struct is going
2469 // to be used for exception handling. Give it linkonce_odr linkage.
2470 return llvm::GlobalValue::LinkOnceODRLinkage;
2471 }
2472
2473 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2474 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2475 if (RD->hasAttr<WeakAttr>())
2476 return llvm::GlobalValue::WeakODRLinkage;
2477 if (RD->isDynamicClass())
2478 return CGM.getVTableLinkage(RD);
2479 }
2480
2481 return llvm::GlobalValue::LinkOnceODRLinkage;
2482 }
2483
2484 llvm_unreachable("Invalid linkage!");
2485}
2486
2487llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2488 // We want to operate on the canonical type.
2489 Ty = CGM.getContext().getCanonicalType(Ty);
2490
2491 // Check if we've already emitted an RTTI descriptor for this type.
2492 SmallString<256> OutName;
2493 llvm::raw_svector_ostream Out(OutName);
2494 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2495 Out.flush();
2496 StringRef Name = OutName.str();
2497
2498 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2499 if (OldGV && !OldGV->isDeclaration()) {
2500 assert(!OldGV->hasAvailableExternallyLinkage() &&
2501 "available_externally typeinfos not yet implemented");
2502
2503 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2504 }
2505
2506 // Check if there is already an external RTTI descriptor for this type.
2507 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2508 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2509 return GetAddrOfExternalRTTIDescriptor(Ty);
2510
2511 // Emit the standard library with external linkage.
2512 llvm::GlobalVariable::LinkageTypes Linkage;
2513 if (IsStdLib)
2514 Linkage = llvm::GlobalValue::ExternalLinkage;
2515 else
2516 Linkage = getTypeInfoLinkage(CGM, Ty);
2517
2518 // Add the vtable pointer.
2519 BuildVTablePointer(cast<Type>(Ty));
2520
2521 // And the name.
2522 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2523 llvm::Constant *TypeNameField;
2524
2525 // If we're supposed to demote the visibility, be sure to set a flag
2526 // to use a string comparison for type_info comparisons.
2527 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2528 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2529 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2530 // The flag is the sign bit, which on ARM64 is defined to be clear
2531 // for global pointers. This is very ARM64-specific.
2532 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2533 llvm::Constant *flag =
2534 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2535 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2536 TypeNameField =
2537 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2538 } else {
2539 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2540 }
2541 Fields.push_back(TypeNameField);
2542
2543 switch (Ty->getTypeClass()) {
2544#define TYPE(Class, Base)
2545#define ABSTRACT_TYPE(Class, Base)
2546#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2547#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2548#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2549#include "clang/AST/TypeNodes.def"
2550 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2551
2552 // GCC treats vector types as fundamental types.
2553 case Type::Builtin:
2554 case Type::Vector:
2555 case Type::ExtVector:
2556 case Type::Complex:
2557 case Type::BlockPointer:
2558 // Itanium C++ ABI 2.9.5p4:
2559 // abi::__fundamental_type_info adds no data members to std::type_info.
2560 break;
2561
2562 case Type::LValueReference:
2563 case Type::RValueReference:
2564 llvm_unreachable("References shouldn't get here");
2565
2566 case Type::Auto:
2567 llvm_unreachable("Undeduced auto type shouldn't get here");
2568
2569 case Type::ConstantArray:
2570 case Type::IncompleteArray:
2571 case Type::VariableArray:
2572 // Itanium C++ ABI 2.9.5p5:
2573 // abi::__array_type_info adds no data members to std::type_info.
2574 break;
2575
2576 case Type::FunctionNoProto:
2577 case Type::FunctionProto:
2578 // Itanium C++ ABI 2.9.5p5:
2579 // abi::__function_type_info adds no data members to std::type_info.
2580 break;
2581
2582 case Type::Enum:
2583 // Itanium C++ ABI 2.9.5p5:
2584 // abi::__enum_type_info adds no data members to std::type_info.
2585 break;
2586
2587 case Type::Record: {
2588 const CXXRecordDecl *RD =
2589 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2590 if (!RD->hasDefinition() || !RD->getNumBases()) {
2591 // We don't need to emit any fields.
2592 break;
2593 }
2594
2595 if (CanUseSingleInheritance(RD))
2596 BuildSIClassTypeInfo(RD);
2597 else
2598 BuildVMIClassTypeInfo(RD);
2599
2600 break;
2601 }
2602
2603 case Type::ObjCObject:
2604 case Type::ObjCInterface:
2605 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2606 break;
2607
2608 case Type::ObjCObjectPointer:
2609 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2610 break;
2611
2612 case Type::Pointer:
2613 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2614 break;
2615
2616 case Type::MemberPointer:
2617 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2618 break;
2619
2620 case Type::Atomic:
2621 // No fields, at least for the moment.
2622 break;
2623 }
2624
2625 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2626
2627 llvm::GlobalVariable *GV =
2628 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2629 /*Constant=*/true, Linkage, Init, Name);
2630
2631 // If there's already an old global variable, replace it with the new one.
2632 if (OldGV) {
2633 GV->takeName(OldGV);
2634 llvm::Constant *NewPtr =
2635 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2636 OldGV->replaceAllUsesWith(NewPtr);
2637 OldGV->eraseFromParent();
2638 }
2639
2640 // The Itanium ABI specifies that type_info objects must be globally
2641 // unique, with one exception: if the type is an incomplete class
2642 // type or a (possibly indirect) pointer to one. That exception
2643 // affects the general case of comparing type_info objects produced
2644 // by the typeid operator, which is why the comparison operators on
2645 // std::type_info generally use the type_info name pointers instead
2646 // of the object addresses. However, the language's built-in uses
2647 // of RTTI generally require class types to be complete, even when
2648 // manipulating pointers to those class types. This allows the
2649 // implementation of dynamic_cast to rely on address equality tests,
2650 // which is much faster.
2651
2652 // All of this is to say that it's important that both the type_info
2653 // object and the type_info name be uniqued when weakly emitted.
2654
2655 // Give the type_info object and name the formal visibility of the
2656 // type itself.
2657 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2658 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2659 // If the linkage is local, only default visibility makes sense.
2660 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2661 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2662 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2663 else
2664 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2665 TypeName->setVisibility(llvmVisibility);
2666 GV->setVisibility(llvmVisibility);
2667
2668 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2669}
2670
2671/// ComputeQualifierFlags - Compute the pointer type info flags from the
2672/// given qualifier.
2673static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2674 unsigned Flags = 0;
2675
2676 if (Quals.hasConst())
2677 Flags |= ItaniumRTTIBuilder::PTI_Const;
2678 if (Quals.hasVolatile())
2679 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2680 if (Quals.hasRestrict())
2681 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2682
2683 return Flags;
2684}
2685
2686/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2687/// for the given Objective-C object type.
2688void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2689 // Drop qualifiers.
2690 const Type *T = OT->getBaseType().getTypePtr();
2691 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2692
2693 // The builtin types are abi::__class_type_infos and don't require
2694 // extra fields.
2695 if (isa<BuiltinType>(T)) return;
2696
2697 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2698 ObjCInterfaceDecl *Super = Class->getSuperClass();
2699
2700 // Root classes are also __class_type_info.
2701 if (!Super) return;
2702
2703 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2704
2705 // Everything else is single inheritance.
2706 llvm::Constant *BaseTypeInfo =
2707 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2708 Fields.push_back(BaseTypeInfo);
2709}
2710
2711/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2712/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2713void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2714 // Itanium C++ ABI 2.9.5p6b:
2715 // It adds to abi::__class_type_info a single member pointing to the
2716 // type_info structure for the base type,
2717 llvm::Constant *BaseTypeInfo =
2718 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2719 Fields.push_back(BaseTypeInfo);
2720}
2721
2722namespace {
2723 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2724 /// a class hierarchy.
2725 struct SeenBases {
2726 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2727 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2728 };
2729}
2730
2731/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2732/// abi::__vmi_class_type_info.
2733///
2734static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2735 SeenBases &Bases) {
2736
2737 unsigned Flags = 0;
2738
2739 const CXXRecordDecl *BaseDecl =
2740 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2741
2742 if (Base->isVirtual()) {
2743 // Mark the virtual base as seen.
2744 if (!Bases.VirtualBases.insert(BaseDecl)) {
2745 // If this virtual base has been seen before, then the class is diamond
2746 // shaped.
2747 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2748 } else {
2749 if (Bases.NonVirtualBases.count(BaseDecl))
2750 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2751 }
2752 } else {
2753 // Mark the non-virtual base as seen.
2754 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
2755 // If this non-virtual base has been seen before, then the class has non-
2756 // diamond shaped repeated inheritance.
2757 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2758 } else {
2759 if (Bases.VirtualBases.count(BaseDecl))
2760 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2761 }
2762 }
2763
2764 // Walk all bases.
2765 for (const auto &I : BaseDecl->bases())
2766 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2767
2768 return Flags;
2769}
2770
2771static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2772 unsigned Flags = 0;
2773 SeenBases Bases;
2774
2775 // Walk all bases.
2776 for (const auto &I : RD->bases())
2777 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2778
2779 return Flags;
2780}
2781
2782/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2783/// classes with bases that do not satisfy the abi::__si_class_type_info
2784/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2785void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2786 llvm::Type *UnsignedIntLTy =
2787 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2788
2789 // Itanium C++ ABI 2.9.5p6c:
2790 // __flags is a word with flags describing details about the class
2791 // structure, which may be referenced by using the __flags_masks
2792 // enumeration. These flags refer to both direct and indirect bases.
2793 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2794 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2795
2796 // Itanium C++ ABI 2.9.5p6c:
2797 // __base_count is a word with the number of direct proper base class
2798 // descriptions that follow.
2799 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2800
2801 if (!RD->getNumBases())
2802 return;
2803
2804 llvm::Type *LongLTy =
2805 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2806
2807 // Now add the base class descriptions.
2808
2809 // Itanium C++ ABI 2.9.5p6c:
2810 // __base_info[] is an array of base class descriptions -- one for every
2811 // direct proper base. Each description is of the type:
2812 //
2813 // struct abi::__base_class_type_info {
2814 // public:
2815 // const __class_type_info *__base_type;
2816 // long __offset_flags;
2817 //
2818 // enum __offset_flags_masks {
2819 // __virtual_mask = 0x1,
2820 // __public_mask = 0x2,
2821 // __offset_shift = 8
2822 // };
2823 // };
2824 for (const auto &Base : RD->bases()) {
2825 // The __base_type member points to the RTTI for the base type.
2826 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2827
2828 const CXXRecordDecl *BaseDecl =
2829 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2830
2831 int64_t OffsetFlags = 0;
2832
2833 // All but the lower 8 bits of __offset_flags are a signed offset.
2834 // For a non-virtual base, this is the offset in the object of the base
2835 // subobject. For a virtual base, this is the offset in the virtual table of
2836 // the virtual base offset for the virtual base referenced (negative).
2837 CharUnits Offset;
2838 if (Base.isVirtual())
2839 Offset =
2840 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2841 else {
2842 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2843 Offset = Layout.getBaseClassOffset(BaseDecl);
2844 };
2845
2846 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2847
2848 // The low-order byte of __offset_flags contains flags, as given by the
2849 // masks from the enumeration __offset_flags_masks.
2850 if (Base.isVirtual())
2851 OffsetFlags |= BCTI_Virtual;
2852 if (Base.getAccessSpecifier() == AS_public)
2853 OffsetFlags |= BCTI_Public;
2854
2855 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2856 }
2857}
2858
2859/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2860/// used for pointer types.
2861void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2862 Qualifiers Quals;
2863 QualType UnqualifiedPointeeTy =
2864 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2865
2866 // Itanium C++ ABI 2.9.5p7:
2867 // __flags is a flag word describing the cv-qualification and other
2868 // attributes of the type pointed to
2869 unsigned Flags = ComputeQualifierFlags(Quals);
2870
2871 // Itanium C++ ABI 2.9.5p7:
2872 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2873 // incomplete class type, the incomplete target type flag is set.
2874 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2875 Flags |= PTI_Incomplete;
2876
2877 llvm::Type *UnsignedIntLTy =
2878 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2879 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2880
2881 // Itanium C++ ABI 2.9.5p7:
2882 // __pointee is a pointer to the std::type_info derivation for the
2883 // unqualified type being pointed to.
2884 llvm::Constant *PointeeTypeInfo =
2885 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2886 Fields.push_back(PointeeTypeInfo);
2887}
2888
2889/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2890/// struct, used for member pointer types.
2891void
2892ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2893 QualType PointeeTy = Ty->getPointeeType();
2894
2895 Qualifiers Quals;
2896 QualType UnqualifiedPointeeTy =
2897 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2898
2899 // Itanium C++ ABI 2.9.5p7:
2900 // __flags is a flag word describing the cv-qualification and other
2901 // attributes of the type pointed to.
2902 unsigned Flags = ComputeQualifierFlags(Quals);
2903
2904 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
2905
2906 // Itanium C++ ABI 2.9.5p7:
2907 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2908 // incomplete class type, the incomplete target type flag is set.
2909 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2910 Flags |= PTI_Incomplete;
2911
2912 if (IsIncompleteClassType(ClassType))
2913 Flags |= PTI_ContainingClassIncomplete;
2914
2915 llvm::Type *UnsignedIntLTy =
2916 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2917 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2918
2919 // Itanium C++ ABI 2.9.5p7:
2920 // __pointee is a pointer to the std::type_info derivation for the
2921 // unqualified type being pointed to.
2922 llvm::Constant *PointeeTypeInfo =
2923 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2924 Fields.push_back(PointeeTypeInfo);
2925
2926 // Itanium C++ ABI 2.9.5p9:
2927 // __context is a pointer to an abi::__class_type_info corresponding to the
2928 // class type containing the member pointed to
2929 // (e.g., the "A" in "int A::*").
2930 Fields.push_back(
2931 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
2932}
2933
2934llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
2935 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
2936}
2937
2938void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
2939 QualType PointerType = getContext().getPointerType(Type);
2940 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
2941 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
2942 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
2943 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
2944}
2945
2946void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
2947 QualType FundamentalTypes[] = {
2948 getContext().VoidTy, getContext().NullPtrTy,
2949 getContext().BoolTy, getContext().WCharTy,
2950 getContext().CharTy, getContext().UnsignedCharTy,
2951 getContext().SignedCharTy, getContext().ShortTy,
2952 getContext().UnsignedShortTy, getContext().IntTy,
2953 getContext().UnsignedIntTy, getContext().LongTy,
2954 getContext().UnsignedLongTy, getContext().LongLongTy,
2955 getContext().UnsignedLongLongTy, getContext().HalfTy,
2956 getContext().FloatTy, getContext().DoubleTy,
2957 getContext().LongDoubleTy, getContext().Char16Ty,
2958 getContext().Char32Ty,
2959 };
2960 for (const QualType &FundamentalType : FundamentalTypes)
2961 EmitFundamentalRTTIDescriptor(FundamentalType);
2962}
2963
2964/// What sort of uniqueness rules should we use for the RTTI for the
2965/// given type?
2966ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
2967 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
2968 if (shouldRTTIBeUnique())
2969 return RUK_Unique;
2970
2971 // It's only necessary for linkonce_odr or weak_odr linkage.
2972 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
2973 Linkage != llvm::GlobalValue::WeakODRLinkage)
2974 return RUK_Unique;
2975
2976 // It's only necessary with default visibility.
2977 if (CanTy->getVisibility() != DefaultVisibility)
2978 return RUK_Unique;
2979
2980 // If we're not required to publish this symbol, hide it.
2981 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
2982 return RUK_NonUniqueHidden;
2983
2984 // If we're required to publish this symbol, as we might be under an
2985 // explicit instantiation, leave it with default visibility but
2986 // enable string-comparisons.
2987 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
2988 return RUK_NonUniqueVisible;
2989}