blob: 25e2715daafce659bdbf245dae3a347812e28cf3 [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
Craig Topper4f12f102014-03-12 06:41:41 +0000141 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000142
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000143 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
144 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000145
Reid Klecknere7de47e2013-07-22 13:51:44 +0000146 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000148 // Itanium does not emit any destructor variant as an inline thunk.
149 // Delegating may occur as an optimization, but all variants are either
150 // emitted with external linkage or as linkonce if they are inline and used.
151 return false;
152 }
153
Craig Topper4f12f102014-03-12 06:41:41 +0000154 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000155
Reid Kleckner89077a12013-12-17 19:46:40 +0000156 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000157 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000158
Craig Topper4f12f102014-03-12 06:41:41 +0000159 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000160
Reid Kleckner89077a12013-12-17 19:46:40 +0000161 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
162 const CXXConstructorDecl *D,
163 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000164 bool Delegating,
165 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000166
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000167 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
168 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000169 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000170
Craig Topper4f12f102014-03-12 06:41:41 +0000171 void emitVTableDefinitions(CodeGenVTables &CGVT,
172 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000173
174 llvm::Value *getVTableAddressPointInStructor(
175 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
176 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000177 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000178
179 llvm::Constant *
180 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000181 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000182
183 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000184 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000185
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000186 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000187 llvm::Value *This,
188 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000189
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000190 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
191 const CXXDestructorDecl *Dtor,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000192 CXXDtorType DtorType, llvm::Value *This,
193 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000194
Craig Topper4f12f102014-03-12 06:41:41 +0000195 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000196
Hans Wennborgc94391d2014-06-06 20:04:01 +0000197 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
198 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000199 // Allow inlining of thunks by emitting them with available_externally
200 // linkage together with vtables when needed.
201 if (ForVTable)
202 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
203 }
204
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000205 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000206 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000207
208 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000209 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000210
Craig Topper4f12f102014-03-12 06:41:41 +0000211 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
212 StringRef GetDeletedVirtualCallName() override
213 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000214
Craig Topper4f12f102014-03-12 06:41:41 +0000215 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000216 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
217 llvm::Value *NewPtr,
218 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000219 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000220 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000221 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
222 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000223 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000224
John McCallcdf7ef52010-11-06 09:44:32 +0000225 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000226 llvm::GlobalVariable *DeclPtr,
227 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000228 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000229 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000230
231 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
232 llvm::GlobalVariable *Var);
233 void EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +0000234 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Craig Topper4f12f102014-03-12 06:41:41 +0000235 llvm::Function *InitFunc) override;
Richard Smith0f383742014-03-26 22:48:22 +0000236 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
237 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000238
Craig Topper4f12f102014-03-12 06:41:41 +0000239 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000240
241 /**************************** RTTI Uniqueness ******************************/
242
243protected:
244 /// Returns true if the ABI requires RTTI type_info objects to be unique
245 /// across a program.
246 virtual bool shouldRTTIBeUnique() const { return true; }
247
248public:
249 /// What sort of unique-RTTI behavior should we use?
250 enum RTTIUniquenessKind {
251 /// We are guaranteeing, or need to guarantee, that the RTTI string
252 /// is unique.
253 RUK_Unique,
254
255 /// We are not guaranteeing uniqueness for the RTTI string, so we
256 /// can demote to hidden visibility but must use string comparisons.
257 RUK_NonUniqueHidden,
258
259 /// We are not guaranteeing uniqueness for the RTTI string, so we
260 /// have to use string comparisons, but we also have to emit it with
261 /// non-hidden visibility.
262 RUK_NonUniqueVisible
263 };
264
265 /// Return the required visibility status for the given type and linkage in
266 /// the current ABI.
267 RTTIUniquenessKind
268 classifyRTTIUniqueness(QualType CanTy,
269 llvm::GlobalValue::LinkageTypes Linkage) const;
270 friend class ItaniumRTTIBuilder;
Charles Davis4e786dd2010-05-25 19:52:27 +0000271};
John McCall86353412010-08-21 22:46:04 +0000272
273class ARMCXXABI : public ItaniumCXXABI {
274public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000275 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
276 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
277 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000278
Craig Topper4f12f102014-03-12 06:41:41 +0000279 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000280 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
281 isa<CXXDestructorDecl>(GD.getDecl()) &&
282 GD.getDtorType() != Dtor_Deleting));
283 }
John McCall5d865c322010-08-31 07:33:07 +0000284
Craig Topper4f12f102014-03-12 06:41:41 +0000285 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
286 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000287
Craig Topper4f12f102014-03-12 06:41:41 +0000288 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000289 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
290 llvm::Value *NewPtr,
291 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000292 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000293 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000294 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000295 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000296};
Tim Northovera2ee4332014-03-29 15:09:45 +0000297
298class iOS64CXXABI : public ARMCXXABI {
299public:
300 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000301
302 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000303 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000304};
Charles Davis4e786dd2010-05-25 19:52:27 +0000305}
306
Charles Davis53c59df2010-08-16 03:33:14 +0000307CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000308 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000309 // For IR-generation purposes, there's no significant difference
310 // between the ARM and iOS ABIs.
311 case TargetCXXABI::GenericARM:
312 case TargetCXXABI::iOS:
313 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000314
Tim Northovera2ee4332014-03-29 15:09:45 +0000315 case TargetCXXABI::iOS64:
316 return new iOS64CXXABI(CGM);
317
Tim Northover9bb857a2013-01-31 12:13:10 +0000318 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
319 // include the other 32-bit ARM oddities: constructor/destructor return values
320 // and array cookies.
321 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000322 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
323 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000324
John McCall57625922013-01-25 23:36:14 +0000325 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000326 if (CGM.getContext().getTargetInfo().getTriple().getArch()
327 == llvm::Triple::le32) {
328 // For PNaCl, use ARM-style method pointers so that PNaCl code
329 // does not assume anything about the alignment of function
330 // pointers.
331 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
332 /* UseARMGuardVarABI = */ false);
333 }
John McCall57625922013-01-25 23:36:14 +0000334 return new ItaniumCXXABI(CGM);
335
336 case TargetCXXABI::Microsoft:
337 llvm_unreachable("Microsoft ABI is not Itanium-based");
338 }
339 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000340}
341
Chris Lattnera5f58b02011-07-09 17:41:47 +0000342llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000343ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
344 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000345 return CGM.PtrDiffTy;
346 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000347}
348
John McCalld9c6c0b2010-08-22 00:59:17 +0000349/// In the Itanium and ARM ABIs, method pointers have the form:
350/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
351///
352/// In the Itanium ABI:
353/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
354/// - the this-adjustment is (memptr.adj)
355/// - the virtual offset is (memptr.ptr - 1)
356///
357/// In the ARM ABI:
358/// - method pointers are virtual if (memptr.adj & 1) is nonzero
359/// - the this-adjustment is (memptr.adj >> 1)
360/// - the virtual offset is (memptr.ptr)
361/// ARM uses 'adj' for the virtual flag because Thumb functions
362/// may be only single-byte aligned.
363///
364/// If the member is virtual, the adjusted 'this' pointer points
365/// to a vtable pointer from which the virtual offset is applied.
366///
367/// If the member is non-virtual, memptr.ptr is the address of
368/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000369llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
370 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
371 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000372 CGBuilderTy &Builder = CGF.Builder;
373
374 const FunctionProtoType *FPT =
375 MPT->getPointeeType()->getAs<FunctionProtoType>();
376 const CXXRecordDecl *RD =
377 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
378
Chris Lattner2192fe52011-07-18 04:24:23 +0000379 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000380 CGM.getTypes().GetFunctionType(
381 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000382
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000383 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000384
John McCalld9c6c0b2010-08-22 00:59:17 +0000385 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
386 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
387 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
388
John McCalla1dee5302010-08-22 10:59:02 +0000389 // Extract memptr.adj, which is in the second field.
390 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000391
392 // Compute the true adjustment.
393 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000394 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000395 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000396
397 // Apply the adjustment and cast back to the original struct type
398 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000399 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
400 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
401 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000402
403 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000404 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000405
406 // If the LSB in the function pointer is 1, the function pointer points to
407 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000408 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000409 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000410 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
411 else
412 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
413 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000414 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
415
416 // In the virtual path, the adjustment left 'This' pointing to the
417 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000418 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000419 CGF.EmitBlock(FnVirtual);
420
421 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000422 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000423 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000424
425 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000426 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000427 if (!UseARMMethodPtrABI)
428 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000429 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000430
431 // Load the virtual function to call.
432 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000433 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000434 CGF.EmitBranch(FnEnd);
435
436 // In the non-virtual path, the function pointer is actually a
437 // function pointer.
438 CGF.EmitBlock(FnNonVirtual);
439 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000440 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000441
442 // We're done.
443 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000444 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000445 Callee->addIncoming(VirtualFn, FnVirtual);
446 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
447 return Callee;
448}
John McCalla8bbb822010-08-22 03:04:22 +0000449
John McCallc134eb52010-08-31 21:07:20 +0000450/// Compute an l-value by applying the given pointer-to-member to a
451/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000452llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
453 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
454 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000455 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000456
457 CGBuilderTy &Builder = CGF.Builder;
458
Micah Villmowea2fea22012-10-25 15:39:14 +0000459 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000460
461 // Cast to char*.
462 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
463
464 // Apply the offset, which we assume is non-null.
465 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
466
467 // Cast the address to the appropriate pointer type, adopting the
468 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000469 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000470 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000471 return Builder.CreateBitCast(Addr, PType);
472}
473
John McCallc62bb392012-02-15 01:22:51 +0000474/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
475/// conversion.
476///
477/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000478///
479/// Obligatory offset/adjustment diagram:
480/// <-- offset --> <-- adjustment -->
481/// |--------------------------|----------------------|--------------------|
482/// ^Derived address point ^Base address point ^Member address point
483///
484/// So when converting a base member pointer to a derived member pointer,
485/// we add the offset to the adjustment because the address point has
486/// decreased; and conversely, when converting a derived MP to a base MP
487/// we subtract the offset from the adjustment because the address point
488/// has increased.
489///
490/// The standard forbids (at compile time) conversion to and from
491/// virtual bases, which is why we don't have to consider them here.
492///
493/// The standard forbids (at run time) casting a derived MP to a base
494/// MP when the derived MP does not point to a member of the base.
495/// This is why -1 is a reasonable choice for null data member
496/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000497llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000498ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
499 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000500 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000501 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000502 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
503 E->getCastKind() == CK_ReinterpretMemberPointer);
504
505 // Under Itanium, reinterprets don't require any additional processing.
506 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
507
508 // Use constant emission if we can.
509 if (isa<llvm::Constant>(src))
510 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
511
512 llvm::Constant *adj = getMemberPointerAdjustment(E);
513 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000514
515 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000516 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000517
John McCallc62bb392012-02-15 01:22:51 +0000518 const MemberPointerType *destTy =
519 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000520
John McCall7a9aac22010-08-23 01:21:21 +0000521 // For member data pointers, this is just a matter of adding the
522 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000523 if (destTy->isMemberDataPointer()) {
524 llvm::Value *dst;
525 if (isDerivedToBase)
526 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000527 else
John McCallc62bb392012-02-15 01:22:51 +0000528 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000529
530 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000531 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
532 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
533 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000534 }
535
John McCalla1dee5302010-08-22 10:59:02 +0000536 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000537 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000538 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
539 offset <<= 1;
540 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000541 }
542
John McCallc62bb392012-02-15 01:22:51 +0000543 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
544 llvm::Value *dstAdj;
545 if (isDerivedToBase)
546 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000547 else
John McCallc62bb392012-02-15 01:22:51 +0000548 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000549
John McCallc62bb392012-02-15 01:22:51 +0000550 return Builder.CreateInsertValue(src, dstAdj, 1);
551}
552
553llvm::Constant *
554ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
555 llvm::Constant *src) {
556 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
557 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
558 E->getCastKind() == CK_ReinterpretMemberPointer);
559
560 // Under Itanium, reinterprets don't require any additional processing.
561 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
562
563 // If the adjustment is trivial, we don't need to do anything.
564 llvm::Constant *adj = getMemberPointerAdjustment(E);
565 if (!adj) return src;
566
567 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
568
569 const MemberPointerType *destTy =
570 E->getType()->castAs<MemberPointerType>();
571
572 // For member data pointers, this is just a matter of adding the
573 // offset if the source is non-null.
574 if (destTy->isMemberDataPointer()) {
575 // null maps to null.
576 if (src->isAllOnesValue()) return src;
577
578 if (isDerivedToBase)
579 return llvm::ConstantExpr::getNSWSub(src, adj);
580 else
581 return llvm::ConstantExpr::getNSWAdd(src, adj);
582 }
583
584 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000585 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000586 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
587 offset <<= 1;
588 adj = llvm::ConstantInt::get(adj->getType(), offset);
589 }
590
591 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
592 llvm::Constant *dstAdj;
593 if (isDerivedToBase)
594 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
595 else
596 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
597
598 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000599}
John McCall84fa5102010-08-22 04:16:24 +0000600
601llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000602ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000603 // Itanium C++ ABI 2.3:
604 // A NULL pointer is represented as -1.
605 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000606 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000607
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000608 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000609 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000610 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000611}
612
John McCallf3a88602011-02-03 08:15:49 +0000613llvm::Constant *
614ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
615 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000616 // Itanium C++ ABI 2.3:
617 // A pointer to data member is an offset from the base address of
618 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000619 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000620}
621
John McCall2979fe02011-04-12 00:42:48 +0000622llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000623 return BuildMemberPointer(MD, CharUnits::Zero());
624}
625
626llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
627 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000628 assert(MD->isInstance() && "Member function must not be static!");
629 MD = MD->getCanonicalDecl();
630
631 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000632
633 // Get the function pointer (or index if this is a virtual function).
634 llvm::Constant *MemPtr[2];
635 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000636 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000637
Ken Dyckdf016282011-04-09 01:30:02 +0000638 const ASTContext &Context = getContext();
639 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000640 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000641 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000642
Mark Seabornedf0d382013-07-24 16:25:13 +0000643 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000644 // ARM C++ ABI 3.2.1:
645 // This ABI specifies that adj contains twice the this
646 // adjustment, plus 1 if the member function is virtual. The
647 // least significant bit of adj then makes exactly the same
648 // discrimination as the least significant bit of ptr does for
649 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000650 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
651 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000652 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000653 } else {
654 // Itanium C++ ABI 2.3:
655 // For a virtual function, [the pointer field] is 1 plus the
656 // virtual table offset (in bytes) of the function,
657 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000658 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
659 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000660 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000661 }
662 } else {
John McCall2979fe02011-04-12 00:42:48 +0000663 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000664 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000665 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000666 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000667 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000668 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000669 } else {
John McCall2979fe02011-04-12 00:42:48 +0000670 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
671 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000672 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000673 }
John McCall2979fe02011-04-12 00:42:48 +0000674 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000675
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000676 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000677 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
678 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000679 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000680 }
John McCall1c456c82010-08-22 06:43:33 +0000681
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000682 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000683}
684
Richard Smithdafff942012-01-14 04:30:29 +0000685llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
686 QualType MPType) {
687 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
688 const ValueDecl *MPD = MP.getMemberPointerDecl();
689 if (!MPD)
690 return EmitNullMemberPointer(MPT);
691
Reid Kleckner452abac2013-05-09 21:01:17 +0000692 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000693
694 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
695 return BuildMemberPointer(MD, ThisAdjustment);
696
697 CharUnits FieldOffset =
698 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
699 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
700}
701
John McCall131d97d2010-08-22 08:30:07 +0000702/// The comparison algorithm is pretty easy: the member pointers are
703/// the same if they're either bitwise identical *or* both null.
704///
705/// ARM is different here only because null-ness is more complicated.
706llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000707ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
708 llvm::Value *L,
709 llvm::Value *R,
710 const MemberPointerType *MPT,
711 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000712 CGBuilderTy &Builder = CGF.Builder;
713
John McCall131d97d2010-08-22 08:30:07 +0000714 llvm::ICmpInst::Predicate Eq;
715 llvm::Instruction::BinaryOps And, Or;
716 if (Inequality) {
717 Eq = llvm::ICmpInst::ICMP_NE;
718 And = llvm::Instruction::Or;
719 Or = llvm::Instruction::And;
720 } else {
721 Eq = llvm::ICmpInst::ICMP_EQ;
722 And = llvm::Instruction::And;
723 Or = llvm::Instruction::Or;
724 }
725
John McCall7a9aac22010-08-23 01:21:21 +0000726 // Member data pointers are easy because there's a unique null
727 // value, so it just comes down to bitwise equality.
728 if (MPT->isMemberDataPointer())
729 return Builder.CreateICmp(Eq, L, R);
730
731 // For member function pointers, the tautologies are more complex.
732 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000733 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000734 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000735 // (L == R) <==> (L.ptr == R.ptr &&
736 // (L.adj == R.adj ||
737 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000738 // The inequality tautologies have exactly the same structure, except
739 // applying De Morgan's laws.
740
741 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
742 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
743
John McCall131d97d2010-08-22 08:30:07 +0000744 // This condition tests whether L.ptr == R.ptr. This must always be
745 // true for equality to hold.
746 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
747
748 // This condition, together with the assumption that L.ptr == R.ptr,
749 // tests whether the pointers are both null. ARM imposes an extra
750 // condition.
751 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
752 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
753
754 // This condition tests whether L.adj == R.adj. If this isn't
755 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000756 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
757 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000758 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
759
760 // Null member function pointers on ARM clear the low bit of Adj,
761 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000762 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000763 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
764
765 // Compute (l.adj | r.adj) & 1 and test it against zero.
766 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
767 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
768 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
769 "cmp.or.adj");
770 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
771 }
772
773 // Tie together all our conditions.
774 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
775 Result = Builder.CreateBinOp(And, PtrEq, Result,
776 Inequality ? "memptr.ne" : "memptr.eq");
777 return Result;
778}
779
780llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000781ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
782 llvm::Value *MemPtr,
783 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000784 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000785
786 /// For member data pointers, this is just a check against -1.
787 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000788 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000789 llvm::Value *NegativeOne =
790 llvm::Constant::getAllOnesValue(MemPtr->getType());
791 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
792 }
John McCall131d97d2010-08-22 08:30:07 +0000793
Daniel Dunbar914bc412011-04-19 23:10:47 +0000794 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000795 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000796
797 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
798 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
799
Daniel Dunbar914bc412011-04-19 23:10:47 +0000800 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
801 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000802 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000803 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000804 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000805 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000806 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
807 "memptr.isvirtual");
808 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000809 }
810
811 return Result;
812}
John McCall1c456c82010-08-22 06:43:33 +0000813
Reid Kleckner40ca9132014-05-13 22:05:45 +0000814bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
815 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
816 if (!RD)
817 return false;
818
Reid Klecknerd355ca72014-05-15 01:26:32 +0000819 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
820 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
821 // special members.
822 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000823 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
824 return true;
825 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000826 return false;
827}
828
John McCall614dbdc2010-08-22 21:01:12 +0000829/// The Itanium ABI requires non-zero initialization only for data
830/// member pointers, for which '0' is a valid offset.
831bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
832 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000833}
John McCall5d865c322010-08-31 07:33:07 +0000834
John McCall82fb8922012-09-25 10:10:39 +0000835/// The Itanium ABI always places an offset to the complete object
836/// at entry -2 in the vtable.
837llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
838 llvm::Value *ptr,
839 QualType type) {
840 // Grab the vtable pointer as an intptr_t*.
841 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
842
843 // Track back to entry -2 and pull out the offset there.
844 llvm::Value *offsetPtr =
845 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
846 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
847 offset->setAlignment(CGF.PointerAlignInBytes);
848
849 // Apply the offset.
850 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
851 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
852}
853
David Majnemer1162d252014-06-22 19:05:33 +0000854static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
855 // void *__dynamic_cast(const void *sub,
856 // const abi::__class_type_info *src,
857 // const abi::__class_type_info *dst,
858 // std::ptrdiff_t src2dst_offset);
859
860 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
861 llvm::Type *PtrDiffTy =
862 CGF.ConvertType(CGF.getContext().getPointerDiffType());
863
864 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
865
866 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
867
868 // Mark the function as nounwind readonly.
869 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
870 llvm::Attribute::ReadOnly };
871 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
872 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
873
874 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
875}
876
877static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
878 // void __cxa_bad_cast();
879 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
880 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
881}
882
883/// \brief Compute the src2dst_offset hint as described in the
884/// Itanium C++ ABI [2.9.7]
885static CharUnits computeOffsetHint(ASTContext &Context,
886 const CXXRecordDecl *Src,
887 const CXXRecordDecl *Dst) {
888 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
889 /*DetectVirtual=*/false);
890
891 // If Dst is not derived from Src we can skip the whole computation below and
892 // return that Src is not a public base of Dst. Record all inheritance paths.
893 if (!Dst->isDerivedFrom(Src, Paths))
894 return CharUnits::fromQuantity(-2ULL);
895
896 unsigned NumPublicPaths = 0;
897 CharUnits Offset;
898
899 // Now walk all possible inheritance paths.
900 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
901 ++I) {
902 if (I->Access != AS_public) // Ignore non-public inheritance.
903 continue;
904
905 ++NumPublicPaths;
906
907 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
908 // If the path contains a virtual base class we can't give any hint.
909 // -1: no hint.
910 if (J->Base->isVirtual())
911 return CharUnits::fromQuantity(-1ULL);
912
913 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
914 continue;
915
916 // Accumulate the base class offsets.
917 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
918 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
919 }
920 }
921
922 // -2: Src is not a public base of Dst.
923 if (NumPublicPaths == 0)
924 return CharUnits::fromQuantity(-2ULL);
925
926 // -3: Src is a multiple public base type but never a virtual base type.
927 if (NumPublicPaths > 1)
928 return CharUnits::fromQuantity(-3ULL);
929
930 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
931 // Return the offset of Src from the origin of Dst.
932 return Offset;
933}
934
935static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
936 // void __cxa_bad_typeid();
937 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
938
939 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
940}
941
942bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
943 QualType SrcRecordTy) {
944 return IsDeref;
945}
946
947void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
948 llvm::Value *Fn = getBadTypeidFn(CGF);
949 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
950 CGF.Builder.CreateUnreachable();
951}
952
953llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
954 QualType SrcRecordTy,
955 llvm::Value *ThisPtr,
956 llvm::Type *StdTypeInfoPtrTy) {
957 llvm::Value *Value =
958 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
959
960 // Load the type info.
961 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
962 return CGF.Builder.CreateLoad(Value);
963}
964
965bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
966 QualType SrcRecordTy) {
967 return SrcIsPtr;
968}
969
970llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
971 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
972 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
973 llvm::Type *PtrDiffLTy =
974 CGF.ConvertType(CGF.getContext().getPointerDiffType());
975 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
976
977 llvm::Value *SrcRTTI =
978 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
979 llvm::Value *DestRTTI =
980 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
981
982 // Compute the offset hint.
983 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
984 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
985 llvm::Value *OffsetHint = llvm::ConstantInt::get(
986 PtrDiffLTy,
987 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
988
989 // Emit the call to __dynamic_cast.
990 Value = CGF.EmitCastToVoidPtr(Value);
991
992 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
993 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
994 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
995
996 /// C++ [expr.dynamic.cast]p9:
997 /// A failed cast to reference type throws std::bad_cast
998 if (DestTy->isReferenceType()) {
999 llvm::BasicBlock *BadCastBlock =
1000 CGF.createBasicBlock("dynamic_cast.bad_cast");
1001
1002 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1003 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1004
1005 CGF.EmitBlock(BadCastBlock);
1006 EmitBadCastCall(CGF);
1007 }
1008
1009 return Value;
1010}
1011
1012llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1013 llvm::Value *Value,
1014 QualType SrcRecordTy,
1015 QualType DestTy) {
1016 llvm::Type *PtrDiffLTy =
1017 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1018 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1019
1020 // Get the vtable pointer.
1021 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1022
1023 // Get the offset-to-top from the vtable.
1024 llvm::Value *OffsetToTop =
1025 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1026 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1027
1028 // Finally, add the offset to the pointer.
1029 Value = CGF.EmitCastToVoidPtr(Value);
1030 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1031
1032 return CGF.Builder.CreateBitCast(Value, DestLTy);
1033}
1034
1035bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1036 llvm::Value *Fn = getBadCastFn(CGF);
1037 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1038 CGF.Builder.CreateUnreachable();
1039 return true;
1040}
1041
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001042llvm::Value *
1043ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1044 llvm::Value *This,
1045 const CXXRecordDecl *ClassDecl,
1046 const CXXRecordDecl *BaseClassDecl) {
1047 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1048 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001049 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1050 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001051
1052 llvm::Value *VBaseOffsetPtr =
1053 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1054 "vbase.offset.ptr");
1055 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1056 CGM.PtrDiffTy->getPointerTo());
1057
1058 llvm::Value *VBaseOffset =
1059 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1060
1061 return VBaseOffset;
1062}
1063
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001064void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1065 // Just make sure we're in sync with TargetCXXABI.
1066 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1067
Rafael Espindolac3cde362013-12-09 14:51:17 +00001068 // The constructor used for constructing this as a base class;
1069 // ignores virtual bases.
1070 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1071
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001072 // The constructor used for constructing this as a complete class;
1073 // constucts the virtual bases, then calls the base constructor.
1074 if (!D->getParent()->isAbstract()) {
1075 // We don't need to emit the complete ctor if the class is abstract.
1076 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1077 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001078}
1079
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001080void
1081ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1082 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001083 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001084
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001085 // All parameters are already in place except VTT, which goes after 'this'.
1086 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001087
1088 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001089 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1090 ArgTys.insert(ArgTys.begin() + 1,
1091 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001092}
1093
Reid Klecknere7de47e2013-07-22 13:51:44 +00001094void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001095 // The destructor used for destructing this as a base class; ignores
1096 // virtual bases.
1097 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001098
1099 // The destructor used for destructing this as a most-derived class;
1100 // call the base destructor and then destructs any virtual bases.
1101 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1102
Rafael Espindolac3cde362013-12-09 14:51:17 +00001103 // The destructor in a virtual table is always a 'deleting'
1104 // destructor, which calls the complete destructor and then uses the
1105 // appropriate operator delete.
1106 if (D->isVirtual())
1107 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001108}
1109
Reid Kleckner89077a12013-12-17 19:46:40 +00001110void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1111 QualType &ResTy,
1112 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001113 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001114 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001115
1116 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001117 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001118 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001119
1120 // FIXME: avoid the fake decl
1121 QualType T = Context.getPointerType(Context.VoidPtrTy);
1122 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001123 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001124 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001125 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001126 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001127 }
1128}
1129
John McCall5d865c322010-08-31 07:33:07 +00001130void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1131 /// Initialize the 'this' slot.
1132 EmitThisParam(CGF);
1133
1134 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001135 if (getStructorImplicitParamDecl(CGF)) {
1136 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1137 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001138 }
John McCall5d865c322010-08-31 07:33:07 +00001139
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001140 /// If this is a function that the ABI specifies returns 'this', initialize
1141 /// the return slot to 'this' at the start of the function.
1142 ///
1143 /// Unlike the setting of return types, this is done within the ABI
1144 /// implementation instead of by clients of CGCXXABI because:
1145 /// 1) getThisValue is currently protected
1146 /// 2) in theory, an ABI could implement 'this' returns some other way;
1147 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001148 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001149 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001150}
1151
Reid Kleckner89077a12013-12-17 19:46:40 +00001152unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1153 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1154 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1155 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1156 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001157
Reid Kleckner89077a12013-12-17 19:46:40 +00001158 // Insert the implicit 'vtt' argument as the second argument.
1159 llvm::Value *VTT =
1160 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1161 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1162 Args.insert(Args.begin() + 1,
1163 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1164 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001165}
1166
1167void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1168 const CXXDestructorDecl *DD,
1169 CXXDtorType Type, bool ForVirtualBase,
1170 bool Delegating, llvm::Value *This) {
1171 GlobalDecl GD(DD, Type);
1172 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1173 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1174
Craig Topper8a13c412014-05-21 05:09:00 +00001175 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001176 if (getContext().getLangOpts().AppleKext)
1177 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1178
1179 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001180 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001181
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001182 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1183 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001184}
1185
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001186void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1187 const CXXRecordDecl *RD) {
1188 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1189 if (VTable->hasInitializer())
1190 return;
1191
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001192 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001193 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1194 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001195 llvm::Constant *RTTI =
1196 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001197
1198 // Create and set the initializer.
1199 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1200 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001201 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001202 VTable->setInitializer(Init);
1203
1204 // Set the correct linkage.
1205 VTable->setLinkage(Linkage);
1206
1207 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001208 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001209
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001210 // Use pointer alignment for the vtable. Otherwise we would align them based
1211 // on the size of the initializer which doesn't make sense as only single
1212 // values are read.
1213 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1214 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1215
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001216 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1217 // we will emit the typeinfo for the fundamental types. This is the
1218 // same behaviour as GCC.
1219 const DeclContext *DC = RD->getDeclContext();
1220 if (RD->getIdentifier() &&
1221 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1222 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1223 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1224 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001225 EmitFundamentalRTTIDescriptors();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001226}
1227
1228llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1229 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1230 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1231 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1232 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1233
1234 llvm::Value *VTableAddressPoint;
1235 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1236 // Get the secondary vpointer index.
1237 uint64_t VirtualPointerIndex =
1238 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1239
1240 /// Load the VTT.
1241 llvm::Value *VTT = CGF.LoadCXXVTT();
1242 if (VirtualPointerIndex)
1243 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1244
1245 // And load the address point from the VTT.
1246 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1247 } else {
1248 llvm::Constant *VTable =
1249 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001250 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1251 .getVTableLayout(VTableClass)
1252 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001253 VTableAddressPoint =
1254 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1255 }
1256
1257 return VTableAddressPoint;
1258}
1259
1260llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1261 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1262 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1263
1264 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001265 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1266 .getVTableLayout(VTableClass)
1267 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001268 llvm::Value *Indices[] = {
1269 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1270 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1271 };
1272
1273 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1274}
1275
1276llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1277 CharUnits VPtrOffset) {
1278 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1279
1280 llvm::GlobalVariable *&VTable = VTables[RD];
1281 if (VTable)
1282 return VTable;
1283
1284 // Queue up this v-table for possible deferred emission.
1285 CGM.addDeferredVTable(RD);
1286
1287 SmallString<256> OutName;
1288 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001289 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001290 Out.flush();
1291 StringRef Name = OutName.str();
1292
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001293 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001294 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1295 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1296
1297 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1298 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1299 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001300
1301 if (RD->hasAttr<DLLImportAttr>())
1302 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1303 else if (RD->hasAttr<DLLExportAttr>())
1304 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1305
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001306 return VTable;
1307}
1308
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001309llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1310 GlobalDecl GD,
1311 llvm::Value *This,
1312 llvm::Type *Ty) {
1313 GD = GD.getCanonicalDecl();
1314 Ty = Ty->getPointerTo()->getPointerTo();
1315 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1316
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001317 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001318 llvm::Value *VFuncPtr =
1319 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1320 return CGF.Builder.CreateLoad(VFuncPtr);
1321}
1322
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001323void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1324 const CXXDestructorDecl *Dtor,
1325 CXXDtorType DtorType,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001326 llvm::Value *This,
1327 const CXXMemberCallExpr *CE) {
1328 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001329 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1330
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001331 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1332 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001333 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001334 llvm::Value *Callee =
1335 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001336
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001337 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1338 /*ImplicitParam=*/nullptr, QualType(), CE);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001339}
1340
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001341void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001342 CodeGenVTables &VTables = CGM.getVTables();
1343 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001344 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001345}
1346
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001347static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1348 llvm::Value *Ptr,
1349 int64_t NonVirtualAdjustment,
1350 int64_t VirtualAdjustment,
1351 bool IsReturnAdjustment) {
1352 if (!NonVirtualAdjustment && !VirtualAdjustment)
1353 return Ptr;
1354
1355 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1356 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1357
1358 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1359 // Perform the non-virtual adjustment for a base-to-derived cast.
1360 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1361 }
1362
1363 if (VirtualAdjustment) {
1364 llvm::Type *PtrDiffTy =
1365 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1366
1367 // Perform the virtual adjustment.
1368 llvm::Value *VTablePtrPtr =
1369 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1370
1371 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1372
1373 llvm::Value *OffsetPtr =
1374 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1375
1376 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1377
1378 // Load the adjustment offset from the vtable.
1379 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1380
1381 // Adjust our pointer.
1382 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1383 }
1384
1385 if (NonVirtualAdjustment && IsReturnAdjustment) {
1386 // Perform the non-virtual adjustment for a derived-to-base cast.
1387 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1388 }
1389
1390 // Cast back to the original type.
1391 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1392}
1393
1394llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1395 llvm::Value *This,
1396 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001397 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1398 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001399 /*IsReturnAdjustment=*/false);
1400}
1401
1402llvm::Value *
1403ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1404 const ReturnAdjustment &RA) {
1405 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1406 RA.Virtual.Itanium.VBaseOffsetOffset,
1407 /*IsReturnAdjustment=*/true);
1408}
1409
John McCall5d865c322010-08-31 07:33:07 +00001410void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1411 RValue RV, QualType ResultType) {
1412 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1413 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1414
1415 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001416 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001417 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1418 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1419 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1420}
John McCall8ed55a52010-09-02 09:58:18 +00001421
1422/************************** Array allocation cookies **************************/
1423
John McCallb91cd662012-05-01 05:23:51 +00001424CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1425 // The array cookie is a size_t; pad that up to the element alignment.
1426 // The cookie is actually right-justified in that space.
1427 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1428 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001429}
1430
1431llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1432 llvm::Value *NewPtr,
1433 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001434 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001435 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001436 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001437
Micah Villmowea2fea22012-10-25 15:39:14 +00001438 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001439
John McCall9bca9232010-09-02 10:25:57 +00001440 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001441 QualType SizeTy = Ctx.getSizeType();
1442 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1443
1444 // The size of the cookie.
1445 CharUnits CookieSize =
1446 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001447 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001448
1449 // Compute an offset to the cookie.
1450 llvm::Value *CookiePtr = NewPtr;
1451 CharUnits CookieOffset = CookieSize - SizeSize;
1452 if (!CookieOffset.isZero())
1453 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1454 CookieOffset.getQuantity());
1455
1456 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001457 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1458 llvm::Value *NumElementsPtr =
1459 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1460 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001461 if (CGM.getLangOpts().Sanitize.Address && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001462 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001463 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001464 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1465 llvm::FunctionType *FTy =
1466 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1467 llvm::Constant *F =
1468 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1469 CGF.Builder.CreateCall(F, NumElementsPtr);
1470 }
John McCall8ed55a52010-09-02 09:58:18 +00001471
1472 // Finally, compute a pointer to the actual data buffer by skipping
1473 // over the cookie completely.
1474 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1475 CookieSize.getQuantity());
1476}
1477
John McCallb91cd662012-05-01 05:23:51 +00001478llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1479 llvm::Value *allocPtr,
1480 CharUnits cookieSize) {
1481 // The element size is right-justified in the cookie.
1482 llvm::Value *numElementsPtr = allocPtr;
1483 CharUnits numElementsOffset =
1484 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1485 if (!numElementsOffset.isZero())
1486 numElementsPtr =
1487 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1488 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001489
Micah Villmowea2fea22012-10-25 15:39:14 +00001490 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001491 numElementsPtr =
1492 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001493 if (!CGM.getLangOpts().Sanitize.Address || AS != 0)
1494 return CGF.Builder.CreateLoad(numElementsPtr);
1495 // In asan mode emit a function call instead of a regular load and let the
1496 // run-time deal with it: if the shadow is properly poisoned return the
1497 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1498 // We can't simply ignore this load using nosanitize metadata because
1499 // the metadata may be lost.
1500 llvm::FunctionType *FTy =
1501 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1502 llvm::Constant *F =
1503 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1504 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001505}
1506
John McCallb91cd662012-05-01 05:23:51 +00001507CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001508 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001509 // struct array_cookie {
1510 // std::size_t element_size; // element_size != 0
1511 // std::size_t element_count;
1512 // };
John McCallc19c7062013-01-25 23:36:19 +00001513 // But the base ABI doesn't give anything an alignment greater than
1514 // 8, so we can dismiss this as typical ABI-author blindness to
1515 // actual language complexity and round up to the element alignment.
1516 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1517 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001518}
1519
1520llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001521 llvm::Value *newPtr,
1522 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001523 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001524 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001525 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001526
John McCallc19c7062013-01-25 23:36:19 +00001527 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1528 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001529
1530 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001531 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001532
1533 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001534 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1535 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1536 getContext().getTypeSizeInChars(elementType).getQuantity());
1537 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001538
1539 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001540 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1541 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001542
1543 // Finally, compute a pointer to the actual data buffer by skipping
1544 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001545 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1546 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1547 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001548}
1549
John McCallb91cd662012-05-01 05:23:51 +00001550llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1551 llvm::Value *allocPtr,
1552 CharUnits cookieSize) {
1553 // The number of elements is at offset sizeof(size_t) relative to
1554 // the allocated pointer.
1555 llvm::Value *numElementsPtr
1556 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001557
Micah Villmowea2fea22012-10-25 15:39:14 +00001558 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001559 numElementsPtr =
1560 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1561 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001562}
1563
John McCall68ff0372010-09-08 01:44:27 +00001564/*********************** Static local initialization **************************/
1565
1566static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001567 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001568 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001569 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001570 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001571 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001572 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001573 llvm::AttributeSet::get(CGM.getLLVMContext(),
1574 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001575 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001576}
1577
1578static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001579 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001580 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001581 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001582 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001583 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001584 llvm::AttributeSet::get(CGM.getLLVMContext(),
1585 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001586 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001587}
1588
1589static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001590 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001591 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001592 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001593 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001594 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001595 llvm::AttributeSet::get(CGM.getLLVMContext(),
1596 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001597 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001598}
1599
1600namespace {
1601 struct CallGuardAbort : EHScopeStack::Cleanup {
1602 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001603 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001604
Craig Topper4f12f102014-03-12 06:41:41 +00001605 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001606 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1607 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001608 }
1609 };
1610}
1611
1612/// The ARM code here follows the Itanium code closely enough that we
1613/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001614void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1615 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001616 llvm::GlobalVariable *var,
1617 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001618 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001619
Richard Smithdbf74ba2013-04-14 23:01:42 +00001620 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001621 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001622 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1623 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001624
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001625 // If we have a global variable with internal linkage and thread-safe statics
1626 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001627 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1628
1629 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001630 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001631 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001632 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001633 // Guard variables are 64 bits in the generic ABI and size width on ARM
1634 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001635 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001636 }
John McCallb88a5662012-03-30 21:00:39 +00001637 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001638
John McCallb88a5662012-03-30 21:00:39 +00001639 // Create the guard variable if we don't already have it (as we
1640 // might if we're double-emitting this function body).
1641 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1642 if (!guard) {
1643 // Mangle the name for the guard.
1644 SmallString<256> guardName;
1645 {
1646 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001647 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001648 out.flush();
1649 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001650
John McCallb88a5662012-03-30 21:00:39 +00001651 // Create the guard variable with a zero-initializer.
1652 // Just absorb linkage and visibility from the guarded variable.
1653 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1654 false, var->getLinkage(),
1655 llvm::ConstantInt::get(guardTy, 0),
1656 guardName.str());
1657 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001658 // If the variable is thread-local, so is its guard variable.
1659 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001660
1661 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1662 }
John McCall87590e62012-03-30 07:09:50 +00001663
John McCall68ff0372010-09-08 01:44:27 +00001664 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001665 //
John McCall68ff0372010-09-08 01:44:27 +00001666 // Itanium C++ ABI 3.3.2:
1667 // The following is pseudo-code showing how these functions can be used:
1668 // if (obj_guard.first_byte == 0) {
1669 // if ( __cxa_guard_acquire (&obj_guard) ) {
1670 // try {
1671 // ... initialize the object ...;
1672 // } catch (...) {
1673 // __cxa_guard_abort (&obj_guard);
1674 // throw;
1675 // }
1676 // ... queue object destructor with __cxa_atexit() ...;
1677 // __cxa_guard_release (&obj_guard);
1678 // }
1679 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001680
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001681 // Load the first byte of the guard variable.
1682 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001683 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001684 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001685
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001686 // Itanium ABI:
1687 // An implementation supporting thread-safety on multiprocessor
1688 // systems must also guarantee that references to the initialized
1689 // object do not occur before the load of the initialization flag.
1690 //
1691 // In LLVM, we do this by marking the load Acquire.
1692 if (threadsafe)
1693 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001694
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001695 // For ARM, we should only check the first bit, rather than the entire byte:
1696 //
1697 // ARM C++ ABI 3.2.3.1:
1698 // To support the potential use of initialization guard variables
1699 // as semaphores that are the target of ARM SWP and LDREX/STREX
1700 // synchronizing instructions we define a static initialization
1701 // guard variable to be a 4-byte aligned, 4-byte word with the
1702 // following inline access protocol.
1703 // #define INITIALIZED 1
1704 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1705 // if (__cxa_guard_acquire(&obj_guard))
1706 // ...
1707 // }
1708 //
1709 // and similarly for ARM64:
1710 //
1711 // ARM64 C++ ABI 3.2.2:
1712 // This ABI instead only specifies the value bit 0 of the static guard
1713 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1714 // variable is not initialized and 1 when it is.
1715 llvm::Value *V =
1716 (UseARMGuardVarABI && !useInt8GuardVariable)
1717 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1718 : LI;
1719 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001720
1721 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1722 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1723
1724 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001725 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001726
1727 CGF.EmitBlock(InitCheckBlock);
1728
1729 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001730 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001731 // Call __cxa_guard_acquire.
1732 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001733 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001734
1735 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1736
1737 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1738 InitBlock, EndBlock);
1739
1740 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001741 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001742
1743 CGF.EmitBlock(InitBlock);
1744 }
1745
1746 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001747 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001748
John McCall5aa52592011-06-17 07:33:57 +00001749 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001750 // Pop the guard-abort cleanup if we pushed one.
1751 CGF.PopCleanupBlock();
1752
1753 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001754 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001755 } else {
John McCallb88a5662012-03-30 21:00:39 +00001756 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001757 }
1758
1759 CGF.EmitBlock(EndBlock);
1760}
John McCallc84ed6a2012-05-01 06:13:13 +00001761
1762/// Register a global destructor using __cxa_atexit.
1763static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1764 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001765 llvm::Constant *addr,
1766 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001767 const char *Name = "__cxa_atexit";
1768 if (TLS) {
1769 const llvm::Triple &T = CGF.getTarget().getTriple();
1770 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1771 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001772
John McCallc84ed6a2012-05-01 06:13:13 +00001773 // We're assuming that the destructor function is something we can
1774 // reasonably call with the default CC. Go ahead and cast it to the
1775 // right prototype.
1776 llvm::Type *dtorTy =
1777 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1778
1779 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1780 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1781 llvm::FunctionType *atexitTy =
1782 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1783
1784 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001785 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001786 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1787 fn->setDoesNotThrow();
1788
1789 // Create a variable that binds the atexit to this shared object.
1790 llvm::Constant *handle =
1791 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1792
1793 llvm::Value *args[] = {
1794 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1795 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1796 handle
1797 };
John McCall882987f2013-02-28 19:01:20 +00001798 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001799}
1800
1801/// Register a global destructor as best as we know how.
1802void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001803 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001804 llvm::Constant *dtor,
1805 llvm::Constant *addr) {
1806 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001807 if (CGM.getCodeGenOpts().CXAAtExit)
1808 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1809
1810 if (D.getTLSKind())
1811 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001812
1813 // In Apple kexts, we want to add a global destructor entry.
1814 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001815 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001816 // Generate a global destructor entry.
1817 return CGM.AddCXXDtorEntry(dtor, addr);
1818 }
1819
David Blaikieebe87e12013-08-27 23:57:18 +00001820 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001821}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001822
David Majnemer9b21c332014-07-11 20:28:10 +00001823static bool isThreadWrapperReplaceable(const VarDecl *VD,
1824 CodeGen::CodeGenModule &CGM) {
1825 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1826 // OS X prefers to have references to thread local variables to go through
1827 // the thread wrapper instead of directly referencing the backing variable.
1828 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1829 CGM.getTarget().getTriple().isMacOSX();
1830}
1831
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001832/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001833/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001834/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001835static llvm::GlobalValue::LinkageTypes
1836getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1837 llvm::GlobalValue::LinkageTypes VarLinkage =
1838 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1839
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001840 // For internal linkage variables, we don't need an external or weak wrapper.
1841 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1842 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001843
David Majnemer9b21c332014-07-11 20:28:10 +00001844 // If the thread wrapper is replaceable, give it appropriate linkage.
1845 if (isThreadWrapperReplaceable(VD, CGM)) {
1846 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1847 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1848 return llvm::GlobalVariable::WeakAnyLinkage;
1849 return VarLinkage;
1850 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001851 return llvm::GlobalValue::WeakODRLinkage;
1852}
1853
1854llvm::Function *
1855ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1856 llvm::GlobalVariable *Var) {
1857 // Mangle the name for the thread_local wrapper function.
1858 SmallString<256> WrapperName;
1859 {
1860 llvm::raw_svector_ostream Out(WrapperName);
1861 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1862 Out.flush();
1863 }
1864
1865 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1866 return cast<llvm::Function>(V);
1867
1868 llvm::Type *RetTy = Var->getType();
1869 if (VD->getType()->isReferenceType())
1870 RetTy = RetTy->getPointerElementType();
1871
1872 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00001873 llvm::Function *Wrapper =
1874 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1875 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001876 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00001877 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001878 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001879 return Wrapper;
1880}
1881
1882void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +00001883 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001884 llvm::Function *InitFunc) {
1885 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1886 const VarDecl *VD = Decls[I].first;
1887 llvm::GlobalVariable *Var = Decls[I].second;
1888
David Majnemer9b21c332014-07-11 20:28:10 +00001889 // Some targets require that all access to thread local variables go through
1890 // the thread wrapper. This means that we cannot attempt to create a thread
1891 // wrapper or a thread helper.
1892 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1893 continue;
1894
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001895 // Mangle the name for the thread_local initialization function.
1896 SmallString<256> InitFnName;
1897 {
1898 llvm::raw_svector_ostream Out(InitFnName);
1899 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1900 Out.flush();
1901 }
1902
1903 // If we have a definition for the variable, emit the initialization
1904 // function as an alias to the global Init function (if any). Otherwise,
1905 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001906 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001907 bool InitIsInitFunc = false;
1908 if (VD->hasDefinition()) {
1909 InitIsInitFunc = true;
1910 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001911 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1912 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001913 } else {
1914 // Emit a weak global function referring to the initialization function.
1915 // This function will not exist if the TU defining the thread_local
1916 // variable in question does not need any dynamic initialization for
1917 // its thread_local variables.
1918 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1919 Init = llvm::Function::Create(
1920 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1921 &CGM.getModule());
1922 }
1923
1924 if (Init)
1925 Init->setVisibility(Var->getVisibility());
1926
1927 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1928 llvm::LLVMContext &Context = CGM.getModule().getContext();
1929 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1930 CGBuilderTy Builder(Entry);
1931 if (InitIsInitFunc) {
1932 if (Init)
1933 Builder.CreateCall(Init);
1934 } else {
1935 // Don't know whether we have an init function. Call it if it exists.
1936 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1937 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1938 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1939 Builder.CreateCondBr(Have, InitBB, ExitBB);
1940
1941 Builder.SetInsertPoint(InitBB);
1942 Builder.CreateCall(Init);
1943 Builder.CreateBr(ExitBB);
1944
1945 Builder.SetInsertPoint(ExitBB);
1946 }
1947
1948 // For a reference, the result of the wrapper function is a pointer to
1949 // the referenced object.
1950 llvm::Value *Val = Var;
1951 if (VD->getType()->isReferenceType()) {
1952 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1953 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1954 Val = LI;
1955 }
1956
1957 Builder.CreateRet(Val);
1958 }
1959}
1960
Richard Smith0f383742014-03-26 22:48:22 +00001961LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1962 const VarDecl *VD,
1963 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001964 QualType T = VD->getType();
1965 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1966 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1967 llvm::Function *Wrapper =
1968 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1969
1970 Val = CGF.Builder.CreateCall(Wrapper);
1971
1972 LValue LV;
1973 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00001974 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001975 else
Richard Smith0f383742014-03-26 22:48:22 +00001976 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001977 // FIXME: need setObjCGCLValueClass?
1978 return LV;
1979}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001980
1981/// Return whether the given global decl needs a VTT parameter, which it does
1982/// if it's a base constructor or destructor with virtual bases.
1983bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1984 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1985
1986 // We don't have any virtual bases, just return early.
1987 if (!MD->getParent()->getNumVBases())
1988 return false;
1989
1990 // Check if we have a base constructor.
1991 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1992 return true;
1993
1994 // Check if we have a base destructor.
1995 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1996 return true;
1997
1998 return false;
1999}
David Majnemere2cb8d12014-07-07 06:20:47 +00002000
2001namespace {
2002class ItaniumRTTIBuilder {
2003 CodeGenModule &CGM; // Per-module state.
2004 llvm::LLVMContext &VMContext;
2005 const ItaniumCXXABI &CXXABI; // Per-module state.
2006
2007 /// Fields - The fields of the RTTI descriptor currently being built.
2008 SmallVector<llvm::Constant *, 16> Fields;
2009
2010 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2011 llvm::GlobalVariable *
2012 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2013
2014 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2015 /// descriptor of the given type.
2016 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2017
2018 /// BuildVTablePointer - Build the vtable pointer for the given type.
2019 void BuildVTablePointer(const Type *Ty);
2020
2021 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2022 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2023 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2024
2025 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2026 /// classes with bases that do not satisfy the abi::__si_class_type_info
2027 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2028 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2029
2030 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2031 /// for pointer types.
2032 void BuildPointerTypeInfo(QualType PointeeTy);
2033
2034 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2035 /// type_info for an object type.
2036 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2037
2038 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2039 /// struct, used for member pointer types.
2040 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2041
2042public:
2043 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2044 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2045
2046 // Pointer type info flags.
2047 enum {
2048 /// PTI_Const - Type has const qualifier.
2049 PTI_Const = 0x1,
2050
2051 /// PTI_Volatile - Type has volatile qualifier.
2052 PTI_Volatile = 0x2,
2053
2054 /// PTI_Restrict - Type has restrict qualifier.
2055 PTI_Restrict = 0x4,
2056
2057 /// PTI_Incomplete - Type is incomplete.
2058 PTI_Incomplete = 0x8,
2059
2060 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2061 /// (in pointer to member).
2062 PTI_ContainingClassIncomplete = 0x10
2063 };
2064
2065 // VMI type info flags.
2066 enum {
2067 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2068 VMI_NonDiamondRepeat = 0x1,
2069
2070 /// VMI_DiamondShaped - Class is diamond shaped.
2071 VMI_DiamondShaped = 0x2
2072 };
2073
2074 // Base class type info flags.
2075 enum {
2076 /// BCTI_Virtual - Base class is virtual.
2077 BCTI_Virtual = 0x1,
2078
2079 /// BCTI_Public - Base class is public.
2080 BCTI_Public = 0x2
2081 };
2082
2083 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2084 ///
2085 /// \param Force - true to force the creation of this RTTI value
2086 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2087};
2088}
2089
2090llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2091 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2092 SmallString<256> OutName;
2093 llvm::raw_svector_ostream Out(OutName);
2094 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2095 Out.flush();
2096 StringRef Name = OutName.str();
2097
2098 // We know that the mangled name of the type starts at index 4 of the
2099 // mangled name of the typename, so we can just index into it in order to
2100 // get the mangled name of the type.
2101 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2102 Name.substr(4));
2103
2104 llvm::GlobalVariable *GV =
2105 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2106
2107 GV->setInitializer(Init);
2108
2109 return GV;
2110}
2111
2112llvm::Constant *
2113ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2114 // Mangle the RTTI name.
2115 SmallString<256> OutName;
2116 llvm::raw_svector_ostream Out(OutName);
2117 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2118 Out.flush();
2119 StringRef Name = OutName.str();
2120
2121 // Look for an existing global.
2122 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2123
2124 if (!GV) {
2125 // Create a new global variable.
2126 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2127 /*Constant=*/true,
2128 llvm::GlobalValue::ExternalLinkage, nullptr,
2129 Name);
2130 }
2131
2132 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2133}
2134
2135/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2136/// info for that type is defined in the standard library.
2137static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2138 // Itanium C++ ABI 2.9.2:
2139 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2140 // the run-time support library. Specifically, the run-time support
2141 // library should contain type_info objects for the types X, X* and
2142 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2143 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2144 // long, unsigned long, long long, unsigned long long, float, double,
2145 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2146 // half-precision floating point types.
2147 switch (Ty->getKind()) {
2148 case BuiltinType::Void:
2149 case BuiltinType::NullPtr:
2150 case BuiltinType::Bool:
2151 case BuiltinType::WChar_S:
2152 case BuiltinType::WChar_U:
2153 case BuiltinType::Char_U:
2154 case BuiltinType::Char_S:
2155 case BuiltinType::UChar:
2156 case BuiltinType::SChar:
2157 case BuiltinType::Short:
2158 case BuiltinType::UShort:
2159 case BuiltinType::Int:
2160 case BuiltinType::UInt:
2161 case BuiltinType::Long:
2162 case BuiltinType::ULong:
2163 case BuiltinType::LongLong:
2164 case BuiltinType::ULongLong:
2165 case BuiltinType::Half:
2166 case BuiltinType::Float:
2167 case BuiltinType::Double:
2168 case BuiltinType::LongDouble:
2169 case BuiltinType::Char16:
2170 case BuiltinType::Char32:
2171 case BuiltinType::Int128:
2172 case BuiltinType::UInt128:
2173 case BuiltinType::OCLImage1d:
2174 case BuiltinType::OCLImage1dArray:
2175 case BuiltinType::OCLImage1dBuffer:
2176 case BuiltinType::OCLImage2d:
2177 case BuiltinType::OCLImage2dArray:
2178 case BuiltinType::OCLImage3d:
2179 case BuiltinType::OCLSampler:
2180 case BuiltinType::OCLEvent:
2181 return true;
2182
2183 case BuiltinType::Dependent:
2184#define BUILTIN_TYPE(Id, SingletonId)
2185#define PLACEHOLDER_TYPE(Id, SingletonId) \
2186 case BuiltinType::Id:
2187#include "clang/AST/BuiltinTypes.def"
2188 llvm_unreachable("asking for RRTI for a placeholder type!");
2189
2190 case BuiltinType::ObjCId:
2191 case BuiltinType::ObjCClass:
2192 case BuiltinType::ObjCSel:
2193 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2194 }
2195
2196 llvm_unreachable("Invalid BuiltinType Kind!");
2197}
2198
2199static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2200 QualType PointeeTy = PointerTy->getPointeeType();
2201 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2202 if (!BuiltinTy)
2203 return false;
2204
2205 // Check the qualifiers.
2206 Qualifiers Quals = PointeeTy.getQualifiers();
2207 Quals.removeConst();
2208
2209 if (!Quals.empty())
2210 return false;
2211
2212 return TypeInfoIsInStandardLibrary(BuiltinTy);
2213}
2214
2215/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2216/// information for the given type exists in the standard library.
2217static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2218 // Type info for builtin types is defined in the standard library.
2219 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2220 return TypeInfoIsInStandardLibrary(BuiltinTy);
2221
2222 // Type info for some pointer types to builtin types is defined in the
2223 // standard library.
2224 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2225 return TypeInfoIsInStandardLibrary(PointerTy);
2226
2227 return false;
2228}
2229
2230/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2231/// the given type exists somewhere else, and that we should not emit the type
2232/// information in this translation unit. Assumes that it is not a
2233/// standard-library type.
2234static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2235 QualType Ty) {
2236 ASTContext &Context = CGM.getContext();
2237
2238 // If RTTI is disabled, assume it might be disabled in the
2239 // translation unit that defines any potential key function, too.
2240 if (!Context.getLangOpts().RTTI) return false;
2241
2242 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2243 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2244 if (!RD->hasDefinition())
2245 return false;
2246
2247 if (!RD->isDynamicClass())
2248 return false;
2249
2250 // FIXME: this may need to be reconsidered if the key function
2251 // changes.
2252 return CGM.getVTables().isVTableExternal(RD);
2253 }
2254
2255 return false;
2256}
2257
2258/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2259static bool IsIncompleteClassType(const RecordType *RecordTy) {
2260 return !RecordTy->getDecl()->isCompleteDefinition();
2261}
2262
2263/// ContainsIncompleteClassType - Returns whether the given type contains an
2264/// incomplete class type. This is true if
2265///
2266/// * The given type is an incomplete class type.
2267/// * The given type is a pointer type whose pointee type contains an
2268/// incomplete class type.
2269/// * The given type is a member pointer type whose class is an incomplete
2270/// class type.
2271/// * The given type is a member pointer type whoise pointee type contains an
2272/// incomplete class type.
2273/// is an indirect or direct pointer to an incomplete class type.
2274static bool ContainsIncompleteClassType(QualType Ty) {
2275 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2276 if (IsIncompleteClassType(RecordTy))
2277 return true;
2278 }
2279
2280 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2281 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2282
2283 if (const MemberPointerType *MemberPointerTy =
2284 dyn_cast<MemberPointerType>(Ty)) {
2285 // Check if the class type is incomplete.
2286 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2287 if (IsIncompleteClassType(ClassType))
2288 return true;
2289
2290 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2291 }
2292
2293 return false;
2294}
2295
2296// CanUseSingleInheritance - Return whether the given record decl has a "single,
2297// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2298// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2299static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2300 // Check the number of bases.
2301 if (RD->getNumBases() != 1)
2302 return false;
2303
2304 // Get the base.
2305 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2306
2307 // Check that the base is not virtual.
2308 if (Base->isVirtual())
2309 return false;
2310
2311 // Check that the base is public.
2312 if (Base->getAccessSpecifier() != AS_public)
2313 return false;
2314
2315 // Check that the class is dynamic iff the base is.
2316 const CXXRecordDecl *BaseDecl =
2317 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2318 if (!BaseDecl->isEmpty() &&
2319 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2320 return false;
2321
2322 return true;
2323}
2324
2325void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2326 // abi::__class_type_info.
2327 static const char * const ClassTypeInfo =
2328 "_ZTVN10__cxxabiv117__class_type_infoE";
2329 // abi::__si_class_type_info.
2330 static const char * const SIClassTypeInfo =
2331 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2332 // abi::__vmi_class_type_info.
2333 static const char * const VMIClassTypeInfo =
2334 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2335
2336 const char *VTableName = nullptr;
2337
2338 switch (Ty->getTypeClass()) {
2339#define TYPE(Class, Base)
2340#define ABSTRACT_TYPE(Class, Base)
2341#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2342#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2343#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2344#include "clang/AST/TypeNodes.def"
2345 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2346
2347 case Type::LValueReference:
2348 case Type::RValueReference:
2349 llvm_unreachable("References shouldn't get here");
2350
2351 case Type::Auto:
2352 llvm_unreachable("Undeduced auto type shouldn't get here");
2353
2354 case Type::Builtin:
2355 // GCC treats vector and complex types as fundamental types.
2356 case Type::Vector:
2357 case Type::ExtVector:
2358 case Type::Complex:
2359 case Type::Atomic:
2360 // FIXME: GCC treats block pointers as fundamental types?!
2361 case Type::BlockPointer:
2362 // abi::__fundamental_type_info.
2363 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2364 break;
2365
2366 case Type::ConstantArray:
2367 case Type::IncompleteArray:
2368 case Type::VariableArray:
2369 // abi::__array_type_info.
2370 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2371 break;
2372
2373 case Type::FunctionNoProto:
2374 case Type::FunctionProto:
2375 // abi::__function_type_info.
2376 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2377 break;
2378
2379 case Type::Enum:
2380 // abi::__enum_type_info.
2381 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2382 break;
2383
2384 case Type::Record: {
2385 const CXXRecordDecl *RD =
2386 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2387
2388 if (!RD->hasDefinition() || !RD->getNumBases()) {
2389 VTableName = ClassTypeInfo;
2390 } else if (CanUseSingleInheritance(RD)) {
2391 VTableName = SIClassTypeInfo;
2392 } else {
2393 VTableName = VMIClassTypeInfo;
2394 }
2395
2396 break;
2397 }
2398
2399 case Type::ObjCObject:
2400 // Ignore protocol qualifiers.
2401 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2402
2403 // Handle id and Class.
2404 if (isa<BuiltinType>(Ty)) {
2405 VTableName = ClassTypeInfo;
2406 break;
2407 }
2408
2409 assert(isa<ObjCInterfaceType>(Ty));
2410 // Fall through.
2411
2412 case Type::ObjCInterface:
2413 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2414 VTableName = SIClassTypeInfo;
2415 } else {
2416 VTableName = ClassTypeInfo;
2417 }
2418 break;
2419
2420 case Type::ObjCObjectPointer:
2421 case Type::Pointer:
2422 // abi::__pointer_type_info.
2423 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2424 break;
2425
2426 case Type::MemberPointer:
2427 // abi::__pointer_to_member_type_info.
2428 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2429 break;
2430 }
2431
2432 llvm::Constant *VTable =
2433 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2434
2435 llvm::Type *PtrDiffTy =
2436 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2437
2438 // The vtable address point is 2.
2439 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2440 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2441 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2442
2443 Fields.push_back(VTable);
2444}
2445
2446/// \brief Return the linkage that the type info and type info name constants
2447/// should have for the given type.
2448static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2449 QualType Ty) {
2450 // Itanium C++ ABI 2.9.5p7:
2451 // In addition, it and all of the intermediate abi::__pointer_type_info
2452 // structs in the chain down to the abi::__class_type_info for the
2453 // incomplete class type must be prevented from resolving to the
2454 // corresponding type_info structs for the complete class type, possibly
2455 // by making them local static objects. Finally, a dummy class RTTI is
2456 // generated for the incomplete type that will not resolve to the final
2457 // complete class RTTI (because the latter need not exist), possibly by
2458 // making it a local static object.
2459 if (ContainsIncompleteClassType(Ty))
2460 return llvm::GlobalValue::InternalLinkage;
2461
2462 switch (Ty->getLinkage()) {
2463 case NoLinkage:
2464 case InternalLinkage:
2465 case UniqueExternalLinkage:
2466 return llvm::GlobalValue::InternalLinkage;
2467
2468 case VisibleNoLinkage:
2469 case ExternalLinkage:
2470 if (!CGM.getLangOpts().RTTI) {
2471 // RTTI is not enabled, which means that this type info struct is going
2472 // to be used for exception handling. Give it linkonce_odr linkage.
2473 return llvm::GlobalValue::LinkOnceODRLinkage;
2474 }
2475
2476 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2477 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2478 if (RD->hasAttr<WeakAttr>())
2479 return llvm::GlobalValue::WeakODRLinkage;
2480 if (RD->isDynamicClass())
2481 return CGM.getVTableLinkage(RD);
2482 }
2483
2484 return llvm::GlobalValue::LinkOnceODRLinkage;
2485 }
2486
2487 llvm_unreachable("Invalid linkage!");
2488}
2489
2490llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2491 // We want to operate on the canonical type.
2492 Ty = CGM.getContext().getCanonicalType(Ty);
2493
2494 // Check if we've already emitted an RTTI descriptor for this type.
2495 SmallString<256> OutName;
2496 llvm::raw_svector_ostream Out(OutName);
2497 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2498 Out.flush();
2499 StringRef Name = OutName.str();
2500
2501 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2502 if (OldGV && !OldGV->isDeclaration()) {
2503 assert(!OldGV->hasAvailableExternallyLinkage() &&
2504 "available_externally typeinfos not yet implemented");
2505
2506 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2507 }
2508
2509 // Check if there is already an external RTTI descriptor for this type.
2510 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2511 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2512 return GetAddrOfExternalRTTIDescriptor(Ty);
2513
2514 // Emit the standard library with external linkage.
2515 llvm::GlobalVariable::LinkageTypes Linkage;
2516 if (IsStdLib)
2517 Linkage = llvm::GlobalValue::ExternalLinkage;
2518 else
2519 Linkage = getTypeInfoLinkage(CGM, Ty);
2520
2521 // Add the vtable pointer.
2522 BuildVTablePointer(cast<Type>(Ty));
2523
2524 // And the name.
2525 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2526 llvm::Constant *TypeNameField;
2527
2528 // If we're supposed to demote the visibility, be sure to set a flag
2529 // to use a string comparison for type_info comparisons.
2530 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2531 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2532 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2533 // The flag is the sign bit, which on ARM64 is defined to be clear
2534 // for global pointers. This is very ARM64-specific.
2535 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2536 llvm::Constant *flag =
2537 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2538 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2539 TypeNameField =
2540 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2541 } else {
2542 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2543 }
2544 Fields.push_back(TypeNameField);
2545
2546 switch (Ty->getTypeClass()) {
2547#define TYPE(Class, Base)
2548#define ABSTRACT_TYPE(Class, Base)
2549#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2550#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2551#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2552#include "clang/AST/TypeNodes.def"
2553 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2554
2555 // GCC treats vector types as fundamental types.
2556 case Type::Builtin:
2557 case Type::Vector:
2558 case Type::ExtVector:
2559 case Type::Complex:
2560 case Type::BlockPointer:
2561 // Itanium C++ ABI 2.9.5p4:
2562 // abi::__fundamental_type_info adds no data members to std::type_info.
2563 break;
2564
2565 case Type::LValueReference:
2566 case Type::RValueReference:
2567 llvm_unreachable("References shouldn't get here");
2568
2569 case Type::Auto:
2570 llvm_unreachable("Undeduced auto type shouldn't get here");
2571
2572 case Type::ConstantArray:
2573 case Type::IncompleteArray:
2574 case Type::VariableArray:
2575 // Itanium C++ ABI 2.9.5p5:
2576 // abi::__array_type_info adds no data members to std::type_info.
2577 break;
2578
2579 case Type::FunctionNoProto:
2580 case Type::FunctionProto:
2581 // Itanium C++ ABI 2.9.5p5:
2582 // abi::__function_type_info adds no data members to std::type_info.
2583 break;
2584
2585 case Type::Enum:
2586 // Itanium C++ ABI 2.9.5p5:
2587 // abi::__enum_type_info adds no data members to std::type_info.
2588 break;
2589
2590 case Type::Record: {
2591 const CXXRecordDecl *RD =
2592 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2593 if (!RD->hasDefinition() || !RD->getNumBases()) {
2594 // We don't need to emit any fields.
2595 break;
2596 }
2597
2598 if (CanUseSingleInheritance(RD))
2599 BuildSIClassTypeInfo(RD);
2600 else
2601 BuildVMIClassTypeInfo(RD);
2602
2603 break;
2604 }
2605
2606 case Type::ObjCObject:
2607 case Type::ObjCInterface:
2608 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2609 break;
2610
2611 case Type::ObjCObjectPointer:
2612 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2613 break;
2614
2615 case Type::Pointer:
2616 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2617 break;
2618
2619 case Type::MemberPointer:
2620 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2621 break;
2622
2623 case Type::Atomic:
2624 // No fields, at least for the moment.
2625 break;
2626 }
2627
2628 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2629
2630 llvm::GlobalVariable *GV =
2631 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2632 /*Constant=*/true, Linkage, Init, Name);
2633
2634 // If there's already an old global variable, replace it with the new one.
2635 if (OldGV) {
2636 GV->takeName(OldGV);
2637 llvm::Constant *NewPtr =
2638 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2639 OldGV->replaceAllUsesWith(NewPtr);
2640 OldGV->eraseFromParent();
2641 }
2642
2643 // The Itanium ABI specifies that type_info objects must be globally
2644 // unique, with one exception: if the type is an incomplete class
2645 // type or a (possibly indirect) pointer to one. That exception
2646 // affects the general case of comparing type_info objects produced
2647 // by the typeid operator, which is why the comparison operators on
2648 // std::type_info generally use the type_info name pointers instead
2649 // of the object addresses. However, the language's built-in uses
2650 // of RTTI generally require class types to be complete, even when
2651 // manipulating pointers to those class types. This allows the
2652 // implementation of dynamic_cast to rely on address equality tests,
2653 // which is much faster.
2654
2655 // All of this is to say that it's important that both the type_info
2656 // object and the type_info name be uniqued when weakly emitted.
2657
2658 // Give the type_info object and name the formal visibility of the
2659 // type itself.
2660 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2661 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2662 // If the linkage is local, only default visibility makes sense.
2663 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2664 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2665 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2666 else
2667 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2668 TypeName->setVisibility(llvmVisibility);
2669 GV->setVisibility(llvmVisibility);
2670
2671 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2672}
2673
2674/// ComputeQualifierFlags - Compute the pointer type info flags from the
2675/// given qualifier.
2676static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2677 unsigned Flags = 0;
2678
2679 if (Quals.hasConst())
2680 Flags |= ItaniumRTTIBuilder::PTI_Const;
2681 if (Quals.hasVolatile())
2682 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2683 if (Quals.hasRestrict())
2684 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2685
2686 return Flags;
2687}
2688
2689/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2690/// for the given Objective-C object type.
2691void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2692 // Drop qualifiers.
2693 const Type *T = OT->getBaseType().getTypePtr();
2694 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2695
2696 // The builtin types are abi::__class_type_infos and don't require
2697 // extra fields.
2698 if (isa<BuiltinType>(T)) return;
2699
2700 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2701 ObjCInterfaceDecl *Super = Class->getSuperClass();
2702
2703 // Root classes are also __class_type_info.
2704 if (!Super) return;
2705
2706 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2707
2708 // Everything else is single inheritance.
2709 llvm::Constant *BaseTypeInfo =
2710 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2711 Fields.push_back(BaseTypeInfo);
2712}
2713
2714/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2715/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2716void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2717 // Itanium C++ ABI 2.9.5p6b:
2718 // It adds to abi::__class_type_info a single member pointing to the
2719 // type_info structure for the base type,
2720 llvm::Constant *BaseTypeInfo =
2721 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2722 Fields.push_back(BaseTypeInfo);
2723}
2724
2725namespace {
2726 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2727 /// a class hierarchy.
2728 struct SeenBases {
2729 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2730 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2731 };
2732}
2733
2734/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2735/// abi::__vmi_class_type_info.
2736///
2737static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2738 SeenBases &Bases) {
2739
2740 unsigned Flags = 0;
2741
2742 const CXXRecordDecl *BaseDecl =
2743 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2744
2745 if (Base->isVirtual()) {
2746 // Mark the virtual base as seen.
2747 if (!Bases.VirtualBases.insert(BaseDecl)) {
2748 // If this virtual base has been seen before, then the class is diamond
2749 // shaped.
2750 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2751 } else {
2752 if (Bases.NonVirtualBases.count(BaseDecl))
2753 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2754 }
2755 } else {
2756 // Mark the non-virtual base as seen.
2757 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
2758 // If this non-virtual base has been seen before, then the class has non-
2759 // diamond shaped repeated inheritance.
2760 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2761 } else {
2762 if (Bases.VirtualBases.count(BaseDecl))
2763 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2764 }
2765 }
2766
2767 // Walk all bases.
2768 for (const auto &I : BaseDecl->bases())
2769 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2770
2771 return Flags;
2772}
2773
2774static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2775 unsigned Flags = 0;
2776 SeenBases Bases;
2777
2778 // Walk all bases.
2779 for (const auto &I : RD->bases())
2780 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2781
2782 return Flags;
2783}
2784
2785/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2786/// classes with bases that do not satisfy the abi::__si_class_type_info
2787/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2788void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2789 llvm::Type *UnsignedIntLTy =
2790 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2791
2792 // Itanium C++ ABI 2.9.5p6c:
2793 // __flags is a word with flags describing details about the class
2794 // structure, which may be referenced by using the __flags_masks
2795 // enumeration. These flags refer to both direct and indirect bases.
2796 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2797 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2798
2799 // Itanium C++ ABI 2.9.5p6c:
2800 // __base_count is a word with the number of direct proper base class
2801 // descriptions that follow.
2802 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2803
2804 if (!RD->getNumBases())
2805 return;
2806
2807 llvm::Type *LongLTy =
2808 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2809
2810 // Now add the base class descriptions.
2811
2812 // Itanium C++ ABI 2.9.5p6c:
2813 // __base_info[] is an array of base class descriptions -- one for every
2814 // direct proper base. Each description is of the type:
2815 //
2816 // struct abi::__base_class_type_info {
2817 // public:
2818 // const __class_type_info *__base_type;
2819 // long __offset_flags;
2820 //
2821 // enum __offset_flags_masks {
2822 // __virtual_mask = 0x1,
2823 // __public_mask = 0x2,
2824 // __offset_shift = 8
2825 // };
2826 // };
2827 for (const auto &Base : RD->bases()) {
2828 // The __base_type member points to the RTTI for the base type.
2829 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2830
2831 const CXXRecordDecl *BaseDecl =
2832 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2833
2834 int64_t OffsetFlags = 0;
2835
2836 // All but the lower 8 bits of __offset_flags are a signed offset.
2837 // For a non-virtual base, this is the offset in the object of the base
2838 // subobject. For a virtual base, this is the offset in the virtual table of
2839 // the virtual base offset for the virtual base referenced (negative).
2840 CharUnits Offset;
2841 if (Base.isVirtual())
2842 Offset =
2843 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2844 else {
2845 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2846 Offset = Layout.getBaseClassOffset(BaseDecl);
2847 };
2848
2849 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2850
2851 // The low-order byte of __offset_flags contains flags, as given by the
2852 // masks from the enumeration __offset_flags_masks.
2853 if (Base.isVirtual())
2854 OffsetFlags |= BCTI_Virtual;
2855 if (Base.getAccessSpecifier() == AS_public)
2856 OffsetFlags |= BCTI_Public;
2857
2858 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2859 }
2860}
2861
2862/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2863/// used for pointer types.
2864void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2865 Qualifiers Quals;
2866 QualType UnqualifiedPointeeTy =
2867 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2868
2869 // Itanium C++ ABI 2.9.5p7:
2870 // __flags is a flag word describing the cv-qualification and other
2871 // attributes of the type pointed to
2872 unsigned Flags = ComputeQualifierFlags(Quals);
2873
2874 // Itanium C++ ABI 2.9.5p7:
2875 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2876 // incomplete class type, the incomplete target type flag is set.
2877 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2878 Flags |= PTI_Incomplete;
2879
2880 llvm::Type *UnsignedIntLTy =
2881 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2882 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2883
2884 // Itanium C++ ABI 2.9.5p7:
2885 // __pointee is a pointer to the std::type_info derivation for the
2886 // unqualified type being pointed to.
2887 llvm::Constant *PointeeTypeInfo =
2888 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2889 Fields.push_back(PointeeTypeInfo);
2890}
2891
2892/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2893/// struct, used for member pointer types.
2894void
2895ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2896 QualType PointeeTy = Ty->getPointeeType();
2897
2898 Qualifiers Quals;
2899 QualType UnqualifiedPointeeTy =
2900 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2901
2902 // Itanium C++ ABI 2.9.5p7:
2903 // __flags is a flag word describing the cv-qualification and other
2904 // attributes of the type pointed to.
2905 unsigned Flags = ComputeQualifierFlags(Quals);
2906
2907 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
2908
2909 // Itanium C++ ABI 2.9.5p7:
2910 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2911 // incomplete class type, the incomplete target type flag is set.
2912 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2913 Flags |= PTI_Incomplete;
2914
2915 if (IsIncompleteClassType(ClassType))
2916 Flags |= PTI_ContainingClassIncomplete;
2917
2918 llvm::Type *UnsignedIntLTy =
2919 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2920 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2921
2922 // Itanium C++ ABI 2.9.5p7:
2923 // __pointee is a pointer to the std::type_info derivation for the
2924 // unqualified type being pointed to.
2925 llvm::Constant *PointeeTypeInfo =
2926 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2927 Fields.push_back(PointeeTypeInfo);
2928
2929 // Itanium C++ ABI 2.9.5p9:
2930 // __context is a pointer to an abi::__class_type_info corresponding to the
2931 // class type containing the member pointed to
2932 // (e.g., the "A" in "int A::*").
2933 Fields.push_back(
2934 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
2935}
2936
2937llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
2938 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
2939}
2940
2941void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
2942 QualType PointerType = getContext().getPointerType(Type);
2943 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
2944 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
2945 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
2946 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
2947}
2948
2949void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
2950 QualType FundamentalTypes[] = {
2951 getContext().VoidTy, getContext().NullPtrTy,
2952 getContext().BoolTy, getContext().WCharTy,
2953 getContext().CharTy, getContext().UnsignedCharTy,
2954 getContext().SignedCharTy, getContext().ShortTy,
2955 getContext().UnsignedShortTy, getContext().IntTy,
2956 getContext().UnsignedIntTy, getContext().LongTy,
2957 getContext().UnsignedLongTy, getContext().LongLongTy,
2958 getContext().UnsignedLongLongTy, getContext().HalfTy,
2959 getContext().FloatTy, getContext().DoubleTy,
2960 getContext().LongDoubleTy, getContext().Char16Ty,
2961 getContext().Char32Ty,
2962 };
2963 for (const QualType &FundamentalType : FundamentalTypes)
2964 EmitFundamentalRTTIDescriptor(FundamentalType);
2965}
2966
2967/// What sort of uniqueness rules should we use for the RTTI for the
2968/// given type?
2969ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
2970 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
2971 if (shouldRTTIBeUnique())
2972 return RUK_Unique;
2973
2974 // It's only necessary for linkonce_odr or weak_odr linkage.
2975 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
2976 Linkage != llvm::GlobalValue::WeakODRLinkage)
2977 return RUK_Unique;
2978
2979 // It's only necessary with default visibility.
2980 if (CanTy->getVisibility() != DefaultVisibility)
2981 return RUK_Unique;
2982
2983 // If we're not required to publish this symbol, hide it.
2984 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
2985 return RUK_NonUniqueHidden;
2986
2987 // If we're required to publish this symbol, as we might be under an
2988 // explicit instantiation, leave it with default visibility but
2989 // enable string-comparisons.
2990 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
2991 return RUK_NonUniqueVisible;
2992}