blob: 60b6ecd4ded61dac2e39658933711cdec2100904 [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)
1180 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1181
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
1210 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1211 // we will emit the typeinfo for the fundamental types. This is the
1212 // same behaviour as GCC.
1213 const DeclContext *DC = RD->getDeclContext();
1214 if (RD->getIdentifier() &&
1215 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1216 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1217 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1218 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001219 EmitFundamentalRTTIDescriptors();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001220}
1221
1222llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1223 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1224 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1225 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1226 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1227
1228 llvm::Value *VTableAddressPoint;
1229 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1230 // Get the secondary vpointer index.
1231 uint64_t VirtualPointerIndex =
1232 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1233
1234 /// Load the VTT.
1235 llvm::Value *VTT = CGF.LoadCXXVTT();
1236 if (VirtualPointerIndex)
1237 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1238
1239 // And load the address point from the VTT.
1240 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1241 } else {
1242 llvm::Constant *VTable =
1243 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001244 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1245 .getVTableLayout(VTableClass)
1246 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001247 VTableAddressPoint =
1248 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1249 }
1250
1251 return VTableAddressPoint;
1252}
1253
1254llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1255 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1256 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1257
1258 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001259 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1260 .getVTableLayout(VTableClass)
1261 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001262 llvm::Value *Indices[] = {
1263 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1264 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1265 };
1266
1267 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1268}
1269
1270llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1271 CharUnits VPtrOffset) {
1272 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1273
1274 llvm::GlobalVariable *&VTable = VTables[RD];
1275 if (VTable)
1276 return VTable;
1277
1278 // Queue up this v-table for possible deferred emission.
1279 CGM.addDeferredVTable(RD);
1280
1281 SmallString<256> OutName;
1282 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001283 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001284 Out.flush();
1285 StringRef Name = OutName.str();
1286
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001287 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001288 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1289 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1290
1291 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1292 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1293 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001294
1295 if (RD->hasAttr<DLLImportAttr>())
1296 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1297 else if (RD->hasAttr<DLLExportAttr>())
1298 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1299
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001300 return VTable;
1301}
1302
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001303llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1304 GlobalDecl GD,
1305 llvm::Value *This,
1306 llvm::Type *Ty) {
1307 GD = GD.getCanonicalDecl();
1308 Ty = Ty->getPointerTo()->getPointerTo();
1309 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1310
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001311 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001312 llvm::Value *VFuncPtr =
1313 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1314 return CGF.Builder.CreateLoad(VFuncPtr);
1315}
1316
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001317void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1318 const CXXDestructorDecl *Dtor,
1319 CXXDtorType DtorType,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001320 llvm::Value *This,
1321 const CXXMemberCallExpr *CE) {
1322 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001323 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1324
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001325 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1326 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001327 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001328 llvm::Value *Callee =
1329 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001330
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001331 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1332 /*ImplicitParam=*/nullptr, QualType(), CE);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001333}
1334
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001335void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001336 CodeGenVTables &VTables = CGM.getVTables();
1337 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001338 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001339}
1340
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001341static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1342 llvm::Value *Ptr,
1343 int64_t NonVirtualAdjustment,
1344 int64_t VirtualAdjustment,
1345 bool IsReturnAdjustment) {
1346 if (!NonVirtualAdjustment && !VirtualAdjustment)
1347 return Ptr;
1348
1349 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1350 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1351
1352 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1353 // Perform the non-virtual adjustment for a base-to-derived cast.
1354 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1355 }
1356
1357 if (VirtualAdjustment) {
1358 llvm::Type *PtrDiffTy =
1359 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1360
1361 // Perform the virtual adjustment.
1362 llvm::Value *VTablePtrPtr =
1363 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1364
1365 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1366
1367 llvm::Value *OffsetPtr =
1368 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1369
1370 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1371
1372 // Load the adjustment offset from the vtable.
1373 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1374
1375 // Adjust our pointer.
1376 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1377 }
1378
1379 if (NonVirtualAdjustment && IsReturnAdjustment) {
1380 // Perform the non-virtual adjustment for a derived-to-base cast.
1381 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1382 }
1383
1384 // Cast back to the original type.
1385 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1386}
1387
1388llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1389 llvm::Value *This,
1390 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001391 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1392 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001393 /*IsReturnAdjustment=*/false);
1394}
1395
1396llvm::Value *
1397ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1398 const ReturnAdjustment &RA) {
1399 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1400 RA.Virtual.Itanium.VBaseOffsetOffset,
1401 /*IsReturnAdjustment=*/true);
1402}
1403
John McCall5d865c322010-08-31 07:33:07 +00001404void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1405 RValue RV, QualType ResultType) {
1406 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1407 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1408
1409 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001410 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001411 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1412 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1413 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1414}
John McCall8ed55a52010-09-02 09:58:18 +00001415
1416/************************** Array allocation cookies **************************/
1417
John McCallb91cd662012-05-01 05:23:51 +00001418CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1419 // The array cookie is a size_t; pad that up to the element alignment.
1420 // The cookie is actually right-justified in that space.
1421 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1422 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001423}
1424
1425llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1426 llvm::Value *NewPtr,
1427 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001428 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001429 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001430 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001431
Micah Villmowea2fea22012-10-25 15:39:14 +00001432 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001433
John McCall9bca9232010-09-02 10:25:57 +00001434 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001435 QualType SizeTy = Ctx.getSizeType();
1436 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1437
1438 // The size of the cookie.
1439 CharUnits CookieSize =
1440 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001441 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001442
1443 // Compute an offset to the cookie.
1444 llvm::Value *CookiePtr = NewPtr;
1445 CharUnits CookieOffset = CookieSize - SizeSize;
1446 if (!CookieOffset.isZero())
1447 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1448 CookieOffset.getQuantity());
1449
1450 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001451 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1452 llvm::Value *NumElementsPtr =
1453 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1454 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001455 if (CGM.getLangOpts().Sanitize.Address && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001456 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001457 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001458 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1459 llvm::FunctionType *FTy =
1460 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1461 llvm::Constant *F =
1462 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1463 CGF.Builder.CreateCall(F, NumElementsPtr);
1464 }
John McCall8ed55a52010-09-02 09:58:18 +00001465
1466 // Finally, compute a pointer to the actual data buffer by skipping
1467 // over the cookie completely.
1468 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1469 CookieSize.getQuantity());
1470}
1471
John McCallb91cd662012-05-01 05:23:51 +00001472llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1473 llvm::Value *allocPtr,
1474 CharUnits cookieSize) {
1475 // The element size is right-justified in the cookie.
1476 llvm::Value *numElementsPtr = allocPtr;
1477 CharUnits numElementsOffset =
1478 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1479 if (!numElementsOffset.isZero())
1480 numElementsPtr =
1481 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1482 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001483
Micah Villmowea2fea22012-10-25 15:39:14 +00001484 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001485 numElementsPtr =
1486 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001487 if (!CGM.getLangOpts().Sanitize.Address || AS != 0)
1488 return CGF.Builder.CreateLoad(numElementsPtr);
1489 // In asan mode emit a function call instead of a regular load and let the
1490 // run-time deal with it: if the shadow is properly poisoned return the
1491 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1492 // We can't simply ignore this load using nosanitize metadata because
1493 // the metadata may be lost.
1494 llvm::FunctionType *FTy =
1495 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1496 llvm::Constant *F =
1497 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1498 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001499}
1500
John McCallb91cd662012-05-01 05:23:51 +00001501CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001502 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001503 // struct array_cookie {
1504 // std::size_t element_size; // element_size != 0
1505 // std::size_t element_count;
1506 // };
John McCallc19c7062013-01-25 23:36:19 +00001507 // But the base ABI doesn't give anything an alignment greater than
1508 // 8, so we can dismiss this as typical ABI-author blindness to
1509 // actual language complexity and round up to the element alignment.
1510 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1511 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001512}
1513
1514llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001515 llvm::Value *newPtr,
1516 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001517 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001518 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001519 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001520
John McCallc19c7062013-01-25 23:36:19 +00001521 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1522 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001523
1524 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001525 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001526
1527 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001528 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1529 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1530 getContext().getTypeSizeInChars(elementType).getQuantity());
1531 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001532
1533 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001534 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1535 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001536
1537 // Finally, compute a pointer to the actual data buffer by skipping
1538 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001539 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1540 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1541 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001542}
1543
John McCallb91cd662012-05-01 05:23:51 +00001544llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1545 llvm::Value *allocPtr,
1546 CharUnits cookieSize) {
1547 // The number of elements is at offset sizeof(size_t) relative to
1548 // the allocated pointer.
1549 llvm::Value *numElementsPtr
1550 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001551
Micah Villmowea2fea22012-10-25 15:39:14 +00001552 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001553 numElementsPtr =
1554 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1555 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001556}
1557
John McCall68ff0372010-09-08 01:44:27 +00001558/*********************** Static local initialization **************************/
1559
1560static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001561 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001562 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001563 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001564 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001565 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001566 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001567 llvm::AttributeSet::get(CGM.getLLVMContext(),
1568 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001569 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001570}
1571
1572static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001573 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001574 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001575 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001576 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001577 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001578 llvm::AttributeSet::get(CGM.getLLVMContext(),
1579 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001580 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001581}
1582
1583static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001584 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001585 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001586 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001587 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001588 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001589 llvm::AttributeSet::get(CGM.getLLVMContext(),
1590 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001591 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001592}
1593
1594namespace {
1595 struct CallGuardAbort : EHScopeStack::Cleanup {
1596 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001597 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001598
Craig Topper4f12f102014-03-12 06:41:41 +00001599 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001600 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1601 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001602 }
1603 };
1604}
1605
1606/// The ARM code here follows the Itanium code closely enough that we
1607/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001608void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1609 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001610 llvm::GlobalVariable *var,
1611 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001612 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001613
Richard Smithdbf74ba2013-04-14 23:01:42 +00001614 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001615 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001616 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1617 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001618
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001619 // If we have a global variable with internal linkage and thread-safe statics
1620 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001621 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1622
1623 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001624 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001625 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001626 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001627 // Guard variables are 64 bits in the generic ABI and size width on ARM
1628 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001629 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001630 }
John McCallb88a5662012-03-30 21:00:39 +00001631 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001632
John McCallb88a5662012-03-30 21:00:39 +00001633 // Create the guard variable if we don't already have it (as we
1634 // might if we're double-emitting this function body).
1635 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1636 if (!guard) {
1637 // Mangle the name for the guard.
1638 SmallString<256> guardName;
1639 {
1640 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001641 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001642 out.flush();
1643 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001644
John McCallb88a5662012-03-30 21:00:39 +00001645 // Create the guard variable with a zero-initializer.
1646 // Just absorb linkage and visibility from the guarded variable.
1647 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1648 false, var->getLinkage(),
1649 llvm::ConstantInt::get(guardTy, 0),
1650 guardName.str());
1651 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001652 // If the variable is thread-local, so is its guard variable.
1653 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001654
1655 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1656 }
John McCall87590e62012-03-30 07:09:50 +00001657
John McCall68ff0372010-09-08 01:44:27 +00001658 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001659 //
John McCall68ff0372010-09-08 01:44:27 +00001660 // Itanium C++ ABI 3.3.2:
1661 // The following is pseudo-code showing how these functions can be used:
1662 // if (obj_guard.first_byte == 0) {
1663 // if ( __cxa_guard_acquire (&obj_guard) ) {
1664 // try {
1665 // ... initialize the object ...;
1666 // } catch (...) {
1667 // __cxa_guard_abort (&obj_guard);
1668 // throw;
1669 // }
1670 // ... queue object destructor with __cxa_atexit() ...;
1671 // __cxa_guard_release (&obj_guard);
1672 // }
1673 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001674
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001675 // Load the first byte of the guard variable.
1676 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001677 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001678 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001679
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001680 // Itanium ABI:
1681 // An implementation supporting thread-safety on multiprocessor
1682 // systems must also guarantee that references to the initialized
1683 // object do not occur before the load of the initialization flag.
1684 //
1685 // In LLVM, we do this by marking the load Acquire.
1686 if (threadsafe)
1687 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001688
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001689 // For ARM, we should only check the first bit, rather than the entire byte:
1690 //
1691 // ARM C++ ABI 3.2.3.1:
1692 // To support the potential use of initialization guard variables
1693 // as semaphores that are the target of ARM SWP and LDREX/STREX
1694 // synchronizing instructions we define a static initialization
1695 // guard variable to be a 4-byte aligned, 4-byte word with the
1696 // following inline access protocol.
1697 // #define INITIALIZED 1
1698 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1699 // if (__cxa_guard_acquire(&obj_guard))
1700 // ...
1701 // }
1702 //
1703 // and similarly for ARM64:
1704 //
1705 // ARM64 C++ ABI 3.2.2:
1706 // This ABI instead only specifies the value bit 0 of the static guard
1707 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1708 // variable is not initialized and 1 when it is.
1709 llvm::Value *V =
1710 (UseARMGuardVarABI && !useInt8GuardVariable)
1711 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1712 : LI;
1713 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001714
1715 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1716 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1717
1718 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001719 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001720
1721 CGF.EmitBlock(InitCheckBlock);
1722
1723 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001724 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001725 // Call __cxa_guard_acquire.
1726 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001727 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001728
1729 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1730
1731 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1732 InitBlock, EndBlock);
1733
1734 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001735 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001736
1737 CGF.EmitBlock(InitBlock);
1738 }
1739
1740 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001741 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001742
John McCall5aa52592011-06-17 07:33:57 +00001743 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001744 // Pop the guard-abort cleanup if we pushed one.
1745 CGF.PopCleanupBlock();
1746
1747 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001748 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001749 } else {
John McCallb88a5662012-03-30 21:00:39 +00001750 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001751 }
1752
1753 CGF.EmitBlock(EndBlock);
1754}
John McCallc84ed6a2012-05-01 06:13:13 +00001755
1756/// Register a global destructor using __cxa_atexit.
1757static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1758 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001759 llvm::Constant *addr,
1760 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001761 const char *Name = "__cxa_atexit";
1762 if (TLS) {
1763 const llvm::Triple &T = CGF.getTarget().getTriple();
1764 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1765 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001766
John McCallc84ed6a2012-05-01 06:13:13 +00001767 // We're assuming that the destructor function is something we can
1768 // reasonably call with the default CC. Go ahead and cast it to the
1769 // right prototype.
1770 llvm::Type *dtorTy =
1771 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1772
1773 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1774 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1775 llvm::FunctionType *atexitTy =
1776 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1777
1778 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001779 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001780 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1781 fn->setDoesNotThrow();
1782
1783 // Create a variable that binds the atexit to this shared object.
1784 llvm::Constant *handle =
1785 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1786
1787 llvm::Value *args[] = {
1788 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1789 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1790 handle
1791 };
John McCall882987f2013-02-28 19:01:20 +00001792 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001793}
1794
1795/// Register a global destructor as best as we know how.
1796void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001797 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001798 llvm::Constant *dtor,
1799 llvm::Constant *addr) {
1800 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001801 if (CGM.getCodeGenOpts().CXAAtExit)
1802 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1803
1804 if (D.getTLSKind())
1805 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001806
1807 // In Apple kexts, we want to add a global destructor entry.
1808 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001809 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001810 // Generate a global destructor entry.
1811 return CGM.AddCXXDtorEntry(dtor, addr);
1812 }
1813
David Blaikieebe87e12013-08-27 23:57:18 +00001814 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001815}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001816
David Majnemer9b21c332014-07-11 20:28:10 +00001817static bool isThreadWrapperReplaceable(const VarDecl *VD,
1818 CodeGen::CodeGenModule &CGM) {
1819 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1820 // OS X prefers to have references to thread local variables to go through
1821 // the thread wrapper instead of directly referencing the backing variable.
1822 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1823 CGM.getTarget().getTriple().isMacOSX();
1824}
1825
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001826/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001827/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001828/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001829static llvm::GlobalValue::LinkageTypes
1830getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1831 llvm::GlobalValue::LinkageTypes VarLinkage =
1832 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1833
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001834 // For internal linkage variables, we don't need an external or weak wrapper.
1835 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1836 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001837
David Majnemer9b21c332014-07-11 20:28:10 +00001838 // If the thread wrapper is replaceable, give it appropriate linkage.
1839 if (isThreadWrapperReplaceable(VD, CGM)) {
1840 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1841 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1842 return llvm::GlobalVariable::WeakAnyLinkage;
1843 return VarLinkage;
1844 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001845 return llvm::GlobalValue::WeakODRLinkage;
1846}
1847
1848llvm::Function *
1849ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1850 llvm::GlobalVariable *Var) {
1851 // Mangle the name for the thread_local wrapper function.
1852 SmallString<256> WrapperName;
1853 {
1854 llvm::raw_svector_ostream Out(WrapperName);
1855 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1856 Out.flush();
1857 }
1858
1859 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1860 return cast<llvm::Function>(V);
1861
1862 llvm::Type *RetTy = Var->getType();
1863 if (VD->getType()->isReferenceType())
1864 RetTy = RetTy->getPointerElementType();
1865
1866 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00001867 llvm::Function *Wrapper =
1868 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1869 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001870 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00001871 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001872 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001873 return Wrapper;
1874}
1875
1876void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Craig Topper00bbdcf2014-06-28 23:22:23 +00001877 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001878 llvm::Function *InitFunc) {
1879 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1880 const VarDecl *VD = Decls[I].first;
1881 llvm::GlobalVariable *Var = Decls[I].second;
1882
David Majnemer9b21c332014-07-11 20:28:10 +00001883 // Some targets require that all access to thread local variables go through
1884 // the thread wrapper. This means that we cannot attempt to create a thread
1885 // wrapper or a thread helper.
1886 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1887 continue;
1888
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001889 // Mangle the name for the thread_local initialization function.
1890 SmallString<256> InitFnName;
1891 {
1892 llvm::raw_svector_ostream Out(InitFnName);
1893 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1894 Out.flush();
1895 }
1896
1897 // If we have a definition for the variable, emit the initialization
1898 // function as an alias to the global Init function (if any). Otherwise,
1899 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001900 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001901 bool InitIsInitFunc = false;
1902 if (VD->hasDefinition()) {
1903 InitIsInitFunc = true;
1904 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001905 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1906 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001907 } else {
1908 // Emit a weak global function referring to the initialization function.
1909 // This function will not exist if the TU defining the thread_local
1910 // variable in question does not need any dynamic initialization for
1911 // its thread_local variables.
1912 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1913 Init = llvm::Function::Create(
1914 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1915 &CGM.getModule());
1916 }
1917
1918 if (Init)
1919 Init->setVisibility(Var->getVisibility());
1920
1921 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1922 llvm::LLVMContext &Context = CGM.getModule().getContext();
1923 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1924 CGBuilderTy Builder(Entry);
1925 if (InitIsInitFunc) {
1926 if (Init)
1927 Builder.CreateCall(Init);
1928 } else {
1929 // Don't know whether we have an init function. Call it if it exists.
1930 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1931 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1932 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1933 Builder.CreateCondBr(Have, InitBB, ExitBB);
1934
1935 Builder.SetInsertPoint(InitBB);
1936 Builder.CreateCall(Init);
1937 Builder.CreateBr(ExitBB);
1938
1939 Builder.SetInsertPoint(ExitBB);
1940 }
1941
1942 // For a reference, the result of the wrapper function is a pointer to
1943 // the referenced object.
1944 llvm::Value *Val = Var;
1945 if (VD->getType()->isReferenceType()) {
1946 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1947 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1948 Val = LI;
1949 }
1950
1951 Builder.CreateRet(Val);
1952 }
1953}
1954
Richard Smith0f383742014-03-26 22:48:22 +00001955LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1956 const VarDecl *VD,
1957 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001958 QualType T = VD->getType();
1959 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1960 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1961 llvm::Function *Wrapper =
1962 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1963
1964 Val = CGF.Builder.CreateCall(Wrapper);
1965
1966 LValue LV;
1967 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00001968 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001969 else
Richard Smith0f383742014-03-26 22:48:22 +00001970 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001971 // FIXME: need setObjCGCLValueClass?
1972 return LV;
1973}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001974
1975/// Return whether the given global decl needs a VTT parameter, which it does
1976/// if it's a base constructor or destructor with virtual bases.
1977bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1978 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1979
1980 // We don't have any virtual bases, just return early.
1981 if (!MD->getParent()->getNumVBases())
1982 return false;
1983
1984 // Check if we have a base constructor.
1985 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1986 return true;
1987
1988 // Check if we have a base destructor.
1989 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1990 return true;
1991
1992 return false;
1993}
David Majnemere2cb8d12014-07-07 06:20:47 +00001994
1995namespace {
1996class ItaniumRTTIBuilder {
1997 CodeGenModule &CGM; // Per-module state.
1998 llvm::LLVMContext &VMContext;
1999 const ItaniumCXXABI &CXXABI; // Per-module state.
2000
2001 /// Fields - The fields of the RTTI descriptor currently being built.
2002 SmallVector<llvm::Constant *, 16> Fields;
2003
2004 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2005 llvm::GlobalVariable *
2006 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2007
2008 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2009 /// descriptor of the given type.
2010 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2011
2012 /// BuildVTablePointer - Build the vtable pointer for the given type.
2013 void BuildVTablePointer(const Type *Ty);
2014
2015 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2016 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2017 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2018
2019 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2020 /// classes with bases that do not satisfy the abi::__si_class_type_info
2021 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2022 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2023
2024 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2025 /// for pointer types.
2026 void BuildPointerTypeInfo(QualType PointeeTy);
2027
2028 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2029 /// type_info for an object type.
2030 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2031
2032 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2033 /// struct, used for member pointer types.
2034 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2035
2036public:
2037 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2038 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2039
2040 // Pointer type info flags.
2041 enum {
2042 /// PTI_Const - Type has const qualifier.
2043 PTI_Const = 0x1,
2044
2045 /// PTI_Volatile - Type has volatile qualifier.
2046 PTI_Volatile = 0x2,
2047
2048 /// PTI_Restrict - Type has restrict qualifier.
2049 PTI_Restrict = 0x4,
2050
2051 /// PTI_Incomplete - Type is incomplete.
2052 PTI_Incomplete = 0x8,
2053
2054 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2055 /// (in pointer to member).
2056 PTI_ContainingClassIncomplete = 0x10
2057 };
2058
2059 // VMI type info flags.
2060 enum {
2061 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2062 VMI_NonDiamondRepeat = 0x1,
2063
2064 /// VMI_DiamondShaped - Class is diamond shaped.
2065 VMI_DiamondShaped = 0x2
2066 };
2067
2068 // Base class type info flags.
2069 enum {
2070 /// BCTI_Virtual - Base class is virtual.
2071 BCTI_Virtual = 0x1,
2072
2073 /// BCTI_Public - Base class is public.
2074 BCTI_Public = 0x2
2075 };
2076
2077 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2078 ///
2079 /// \param Force - true to force the creation of this RTTI value
2080 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2081};
2082}
2083
2084llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2085 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2086 SmallString<256> OutName;
2087 llvm::raw_svector_ostream Out(OutName);
2088 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2089 Out.flush();
2090 StringRef Name = OutName.str();
2091
2092 // We know that the mangled name of the type starts at index 4 of the
2093 // mangled name of the typename, so we can just index into it in order to
2094 // get the mangled name of the type.
2095 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2096 Name.substr(4));
2097
2098 llvm::GlobalVariable *GV =
2099 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2100
2101 GV->setInitializer(Init);
2102
2103 return GV;
2104}
2105
2106llvm::Constant *
2107ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2108 // Mangle the RTTI name.
2109 SmallString<256> OutName;
2110 llvm::raw_svector_ostream Out(OutName);
2111 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2112 Out.flush();
2113 StringRef Name = OutName.str();
2114
2115 // Look for an existing global.
2116 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2117
2118 if (!GV) {
2119 // Create a new global variable.
2120 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2121 /*Constant=*/true,
2122 llvm::GlobalValue::ExternalLinkage, nullptr,
2123 Name);
2124 }
2125
2126 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2127}
2128
2129/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2130/// info for that type is defined in the standard library.
2131static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2132 // Itanium C++ ABI 2.9.2:
2133 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2134 // the run-time support library. Specifically, the run-time support
2135 // library should contain type_info objects for the types X, X* and
2136 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2137 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2138 // long, unsigned long, long long, unsigned long long, float, double,
2139 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2140 // half-precision floating point types.
2141 switch (Ty->getKind()) {
2142 case BuiltinType::Void:
2143 case BuiltinType::NullPtr:
2144 case BuiltinType::Bool:
2145 case BuiltinType::WChar_S:
2146 case BuiltinType::WChar_U:
2147 case BuiltinType::Char_U:
2148 case BuiltinType::Char_S:
2149 case BuiltinType::UChar:
2150 case BuiltinType::SChar:
2151 case BuiltinType::Short:
2152 case BuiltinType::UShort:
2153 case BuiltinType::Int:
2154 case BuiltinType::UInt:
2155 case BuiltinType::Long:
2156 case BuiltinType::ULong:
2157 case BuiltinType::LongLong:
2158 case BuiltinType::ULongLong:
2159 case BuiltinType::Half:
2160 case BuiltinType::Float:
2161 case BuiltinType::Double:
2162 case BuiltinType::LongDouble:
2163 case BuiltinType::Char16:
2164 case BuiltinType::Char32:
2165 case BuiltinType::Int128:
2166 case BuiltinType::UInt128:
2167 case BuiltinType::OCLImage1d:
2168 case BuiltinType::OCLImage1dArray:
2169 case BuiltinType::OCLImage1dBuffer:
2170 case BuiltinType::OCLImage2d:
2171 case BuiltinType::OCLImage2dArray:
2172 case BuiltinType::OCLImage3d:
2173 case BuiltinType::OCLSampler:
2174 case BuiltinType::OCLEvent:
2175 return true;
2176
2177 case BuiltinType::Dependent:
2178#define BUILTIN_TYPE(Id, SingletonId)
2179#define PLACEHOLDER_TYPE(Id, SingletonId) \
2180 case BuiltinType::Id:
2181#include "clang/AST/BuiltinTypes.def"
2182 llvm_unreachable("asking for RRTI for a placeholder type!");
2183
2184 case BuiltinType::ObjCId:
2185 case BuiltinType::ObjCClass:
2186 case BuiltinType::ObjCSel:
2187 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2188 }
2189
2190 llvm_unreachable("Invalid BuiltinType Kind!");
2191}
2192
2193static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2194 QualType PointeeTy = PointerTy->getPointeeType();
2195 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2196 if (!BuiltinTy)
2197 return false;
2198
2199 // Check the qualifiers.
2200 Qualifiers Quals = PointeeTy.getQualifiers();
2201 Quals.removeConst();
2202
2203 if (!Quals.empty())
2204 return false;
2205
2206 return TypeInfoIsInStandardLibrary(BuiltinTy);
2207}
2208
2209/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2210/// information for the given type exists in the standard library.
2211static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2212 // Type info for builtin types is defined in the standard library.
2213 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2214 return TypeInfoIsInStandardLibrary(BuiltinTy);
2215
2216 // Type info for some pointer types to builtin types is defined in the
2217 // standard library.
2218 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2219 return TypeInfoIsInStandardLibrary(PointerTy);
2220
2221 return false;
2222}
2223
2224/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2225/// the given type exists somewhere else, and that we should not emit the type
2226/// information in this translation unit. Assumes that it is not a
2227/// standard-library type.
2228static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2229 QualType Ty) {
2230 ASTContext &Context = CGM.getContext();
2231
2232 // If RTTI is disabled, assume it might be disabled in the
2233 // translation unit that defines any potential key function, too.
2234 if (!Context.getLangOpts().RTTI) return false;
2235
2236 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2237 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2238 if (!RD->hasDefinition())
2239 return false;
2240
2241 if (!RD->isDynamicClass())
2242 return false;
2243
2244 // FIXME: this may need to be reconsidered if the key function
2245 // changes.
2246 return CGM.getVTables().isVTableExternal(RD);
2247 }
2248
2249 return false;
2250}
2251
2252/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2253static bool IsIncompleteClassType(const RecordType *RecordTy) {
2254 return !RecordTy->getDecl()->isCompleteDefinition();
2255}
2256
2257/// ContainsIncompleteClassType - Returns whether the given type contains an
2258/// incomplete class type. This is true if
2259///
2260/// * The given type is an incomplete class type.
2261/// * The given type is a pointer type whose pointee type contains an
2262/// incomplete class type.
2263/// * The given type is a member pointer type whose class is an incomplete
2264/// class type.
2265/// * The given type is a member pointer type whoise pointee type contains an
2266/// incomplete class type.
2267/// is an indirect or direct pointer to an incomplete class type.
2268static bool ContainsIncompleteClassType(QualType Ty) {
2269 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2270 if (IsIncompleteClassType(RecordTy))
2271 return true;
2272 }
2273
2274 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2275 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2276
2277 if (const MemberPointerType *MemberPointerTy =
2278 dyn_cast<MemberPointerType>(Ty)) {
2279 // Check if the class type is incomplete.
2280 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2281 if (IsIncompleteClassType(ClassType))
2282 return true;
2283
2284 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2285 }
2286
2287 return false;
2288}
2289
2290// CanUseSingleInheritance - Return whether the given record decl has a "single,
2291// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2292// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2293static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2294 // Check the number of bases.
2295 if (RD->getNumBases() != 1)
2296 return false;
2297
2298 // Get the base.
2299 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2300
2301 // Check that the base is not virtual.
2302 if (Base->isVirtual())
2303 return false;
2304
2305 // Check that the base is public.
2306 if (Base->getAccessSpecifier() != AS_public)
2307 return false;
2308
2309 // Check that the class is dynamic iff the base is.
2310 const CXXRecordDecl *BaseDecl =
2311 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2312 if (!BaseDecl->isEmpty() &&
2313 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2314 return false;
2315
2316 return true;
2317}
2318
2319void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2320 // abi::__class_type_info.
2321 static const char * const ClassTypeInfo =
2322 "_ZTVN10__cxxabiv117__class_type_infoE";
2323 // abi::__si_class_type_info.
2324 static const char * const SIClassTypeInfo =
2325 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2326 // abi::__vmi_class_type_info.
2327 static const char * const VMIClassTypeInfo =
2328 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2329
2330 const char *VTableName = nullptr;
2331
2332 switch (Ty->getTypeClass()) {
2333#define TYPE(Class, Base)
2334#define ABSTRACT_TYPE(Class, Base)
2335#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2336#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2337#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2338#include "clang/AST/TypeNodes.def"
2339 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2340
2341 case Type::LValueReference:
2342 case Type::RValueReference:
2343 llvm_unreachable("References shouldn't get here");
2344
2345 case Type::Auto:
2346 llvm_unreachable("Undeduced auto type shouldn't get here");
2347
2348 case Type::Builtin:
2349 // GCC treats vector and complex types as fundamental types.
2350 case Type::Vector:
2351 case Type::ExtVector:
2352 case Type::Complex:
2353 case Type::Atomic:
2354 // FIXME: GCC treats block pointers as fundamental types?!
2355 case Type::BlockPointer:
2356 // abi::__fundamental_type_info.
2357 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2358 break;
2359
2360 case Type::ConstantArray:
2361 case Type::IncompleteArray:
2362 case Type::VariableArray:
2363 // abi::__array_type_info.
2364 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2365 break;
2366
2367 case Type::FunctionNoProto:
2368 case Type::FunctionProto:
2369 // abi::__function_type_info.
2370 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2371 break;
2372
2373 case Type::Enum:
2374 // abi::__enum_type_info.
2375 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2376 break;
2377
2378 case Type::Record: {
2379 const CXXRecordDecl *RD =
2380 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2381
2382 if (!RD->hasDefinition() || !RD->getNumBases()) {
2383 VTableName = ClassTypeInfo;
2384 } else if (CanUseSingleInheritance(RD)) {
2385 VTableName = SIClassTypeInfo;
2386 } else {
2387 VTableName = VMIClassTypeInfo;
2388 }
2389
2390 break;
2391 }
2392
2393 case Type::ObjCObject:
2394 // Ignore protocol qualifiers.
2395 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2396
2397 // Handle id and Class.
2398 if (isa<BuiltinType>(Ty)) {
2399 VTableName = ClassTypeInfo;
2400 break;
2401 }
2402
2403 assert(isa<ObjCInterfaceType>(Ty));
2404 // Fall through.
2405
2406 case Type::ObjCInterface:
2407 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2408 VTableName = SIClassTypeInfo;
2409 } else {
2410 VTableName = ClassTypeInfo;
2411 }
2412 break;
2413
2414 case Type::ObjCObjectPointer:
2415 case Type::Pointer:
2416 // abi::__pointer_type_info.
2417 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2418 break;
2419
2420 case Type::MemberPointer:
2421 // abi::__pointer_to_member_type_info.
2422 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2423 break;
2424 }
2425
2426 llvm::Constant *VTable =
2427 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2428
2429 llvm::Type *PtrDiffTy =
2430 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2431
2432 // The vtable address point is 2.
2433 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2434 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2435 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2436
2437 Fields.push_back(VTable);
2438}
2439
2440/// \brief Return the linkage that the type info and type info name constants
2441/// should have for the given type.
2442static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2443 QualType Ty) {
2444 // Itanium C++ ABI 2.9.5p7:
2445 // In addition, it and all of the intermediate abi::__pointer_type_info
2446 // structs in the chain down to the abi::__class_type_info for the
2447 // incomplete class type must be prevented from resolving to the
2448 // corresponding type_info structs for the complete class type, possibly
2449 // by making them local static objects. Finally, a dummy class RTTI is
2450 // generated for the incomplete type that will not resolve to the final
2451 // complete class RTTI (because the latter need not exist), possibly by
2452 // making it a local static object.
2453 if (ContainsIncompleteClassType(Ty))
2454 return llvm::GlobalValue::InternalLinkage;
2455
2456 switch (Ty->getLinkage()) {
2457 case NoLinkage:
2458 case InternalLinkage:
2459 case UniqueExternalLinkage:
2460 return llvm::GlobalValue::InternalLinkage;
2461
2462 case VisibleNoLinkage:
2463 case ExternalLinkage:
2464 if (!CGM.getLangOpts().RTTI) {
2465 // RTTI is not enabled, which means that this type info struct is going
2466 // to be used for exception handling. Give it linkonce_odr linkage.
2467 return llvm::GlobalValue::LinkOnceODRLinkage;
2468 }
2469
2470 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2471 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2472 if (RD->hasAttr<WeakAttr>())
2473 return llvm::GlobalValue::WeakODRLinkage;
2474 if (RD->isDynamicClass())
2475 return CGM.getVTableLinkage(RD);
2476 }
2477
2478 return llvm::GlobalValue::LinkOnceODRLinkage;
2479 }
2480
2481 llvm_unreachable("Invalid linkage!");
2482}
2483
2484llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2485 // We want to operate on the canonical type.
2486 Ty = CGM.getContext().getCanonicalType(Ty);
2487
2488 // Check if we've already emitted an RTTI descriptor for this type.
2489 SmallString<256> OutName;
2490 llvm::raw_svector_ostream Out(OutName);
2491 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2492 Out.flush();
2493 StringRef Name = OutName.str();
2494
2495 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2496 if (OldGV && !OldGV->isDeclaration()) {
2497 assert(!OldGV->hasAvailableExternallyLinkage() &&
2498 "available_externally typeinfos not yet implemented");
2499
2500 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2501 }
2502
2503 // Check if there is already an external RTTI descriptor for this type.
2504 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2505 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2506 return GetAddrOfExternalRTTIDescriptor(Ty);
2507
2508 // Emit the standard library with external linkage.
2509 llvm::GlobalVariable::LinkageTypes Linkage;
2510 if (IsStdLib)
2511 Linkage = llvm::GlobalValue::ExternalLinkage;
2512 else
2513 Linkage = getTypeInfoLinkage(CGM, Ty);
2514
2515 // Add the vtable pointer.
2516 BuildVTablePointer(cast<Type>(Ty));
2517
2518 // And the name.
2519 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2520 llvm::Constant *TypeNameField;
2521
2522 // If we're supposed to demote the visibility, be sure to set a flag
2523 // to use a string comparison for type_info comparisons.
2524 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2525 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2526 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2527 // The flag is the sign bit, which on ARM64 is defined to be clear
2528 // for global pointers. This is very ARM64-specific.
2529 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2530 llvm::Constant *flag =
2531 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2532 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2533 TypeNameField =
2534 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2535 } else {
2536 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2537 }
2538 Fields.push_back(TypeNameField);
2539
2540 switch (Ty->getTypeClass()) {
2541#define TYPE(Class, Base)
2542#define ABSTRACT_TYPE(Class, Base)
2543#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2544#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2545#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2546#include "clang/AST/TypeNodes.def"
2547 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2548
2549 // GCC treats vector types as fundamental types.
2550 case Type::Builtin:
2551 case Type::Vector:
2552 case Type::ExtVector:
2553 case Type::Complex:
2554 case Type::BlockPointer:
2555 // Itanium C++ ABI 2.9.5p4:
2556 // abi::__fundamental_type_info adds no data members to std::type_info.
2557 break;
2558
2559 case Type::LValueReference:
2560 case Type::RValueReference:
2561 llvm_unreachable("References shouldn't get here");
2562
2563 case Type::Auto:
2564 llvm_unreachable("Undeduced auto type shouldn't get here");
2565
2566 case Type::ConstantArray:
2567 case Type::IncompleteArray:
2568 case Type::VariableArray:
2569 // Itanium C++ ABI 2.9.5p5:
2570 // abi::__array_type_info adds no data members to std::type_info.
2571 break;
2572
2573 case Type::FunctionNoProto:
2574 case Type::FunctionProto:
2575 // Itanium C++ ABI 2.9.5p5:
2576 // abi::__function_type_info adds no data members to std::type_info.
2577 break;
2578
2579 case Type::Enum:
2580 // Itanium C++ ABI 2.9.5p5:
2581 // abi::__enum_type_info adds no data members to std::type_info.
2582 break;
2583
2584 case Type::Record: {
2585 const CXXRecordDecl *RD =
2586 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2587 if (!RD->hasDefinition() || !RD->getNumBases()) {
2588 // We don't need to emit any fields.
2589 break;
2590 }
2591
2592 if (CanUseSingleInheritance(RD))
2593 BuildSIClassTypeInfo(RD);
2594 else
2595 BuildVMIClassTypeInfo(RD);
2596
2597 break;
2598 }
2599
2600 case Type::ObjCObject:
2601 case Type::ObjCInterface:
2602 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2603 break;
2604
2605 case Type::ObjCObjectPointer:
2606 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2607 break;
2608
2609 case Type::Pointer:
2610 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2611 break;
2612
2613 case Type::MemberPointer:
2614 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2615 break;
2616
2617 case Type::Atomic:
2618 // No fields, at least for the moment.
2619 break;
2620 }
2621
2622 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2623
2624 llvm::GlobalVariable *GV =
2625 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2626 /*Constant=*/true, Linkage, Init, Name);
2627
2628 // If there's already an old global variable, replace it with the new one.
2629 if (OldGV) {
2630 GV->takeName(OldGV);
2631 llvm::Constant *NewPtr =
2632 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2633 OldGV->replaceAllUsesWith(NewPtr);
2634 OldGV->eraseFromParent();
2635 }
2636
2637 // The Itanium ABI specifies that type_info objects must be globally
2638 // unique, with one exception: if the type is an incomplete class
2639 // type or a (possibly indirect) pointer to one. That exception
2640 // affects the general case of comparing type_info objects produced
2641 // by the typeid operator, which is why the comparison operators on
2642 // std::type_info generally use the type_info name pointers instead
2643 // of the object addresses. However, the language's built-in uses
2644 // of RTTI generally require class types to be complete, even when
2645 // manipulating pointers to those class types. This allows the
2646 // implementation of dynamic_cast to rely on address equality tests,
2647 // which is much faster.
2648
2649 // All of this is to say that it's important that both the type_info
2650 // object and the type_info name be uniqued when weakly emitted.
2651
2652 // Give the type_info object and name the formal visibility of the
2653 // type itself.
2654 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2655 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2656 // If the linkage is local, only default visibility makes sense.
2657 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2658 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2659 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2660 else
2661 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2662 TypeName->setVisibility(llvmVisibility);
2663 GV->setVisibility(llvmVisibility);
2664
2665 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2666}
2667
2668/// ComputeQualifierFlags - Compute the pointer type info flags from the
2669/// given qualifier.
2670static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2671 unsigned Flags = 0;
2672
2673 if (Quals.hasConst())
2674 Flags |= ItaniumRTTIBuilder::PTI_Const;
2675 if (Quals.hasVolatile())
2676 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2677 if (Quals.hasRestrict())
2678 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2679
2680 return Flags;
2681}
2682
2683/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2684/// for the given Objective-C object type.
2685void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2686 // Drop qualifiers.
2687 const Type *T = OT->getBaseType().getTypePtr();
2688 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2689
2690 // The builtin types are abi::__class_type_infos and don't require
2691 // extra fields.
2692 if (isa<BuiltinType>(T)) return;
2693
2694 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2695 ObjCInterfaceDecl *Super = Class->getSuperClass();
2696
2697 // Root classes are also __class_type_info.
2698 if (!Super) return;
2699
2700 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2701
2702 // Everything else is single inheritance.
2703 llvm::Constant *BaseTypeInfo =
2704 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2705 Fields.push_back(BaseTypeInfo);
2706}
2707
2708/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2709/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2710void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2711 // Itanium C++ ABI 2.9.5p6b:
2712 // It adds to abi::__class_type_info a single member pointing to the
2713 // type_info structure for the base type,
2714 llvm::Constant *BaseTypeInfo =
2715 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2716 Fields.push_back(BaseTypeInfo);
2717}
2718
2719namespace {
2720 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2721 /// a class hierarchy.
2722 struct SeenBases {
2723 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2724 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2725 };
2726}
2727
2728/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2729/// abi::__vmi_class_type_info.
2730///
2731static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2732 SeenBases &Bases) {
2733
2734 unsigned Flags = 0;
2735
2736 const CXXRecordDecl *BaseDecl =
2737 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2738
2739 if (Base->isVirtual()) {
2740 // Mark the virtual base as seen.
2741 if (!Bases.VirtualBases.insert(BaseDecl)) {
2742 // If this virtual base has been seen before, then the class is diamond
2743 // shaped.
2744 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2745 } else {
2746 if (Bases.NonVirtualBases.count(BaseDecl))
2747 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2748 }
2749 } else {
2750 // Mark the non-virtual base as seen.
2751 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
2752 // If this non-virtual base has been seen before, then the class has non-
2753 // diamond shaped repeated inheritance.
2754 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2755 } else {
2756 if (Bases.VirtualBases.count(BaseDecl))
2757 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2758 }
2759 }
2760
2761 // Walk all bases.
2762 for (const auto &I : BaseDecl->bases())
2763 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2764
2765 return Flags;
2766}
2767
2768static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2769 unsigned Flags = 0;
2770 SeenBases Bases;
2771
2772 // Walk all bases.
2773 for (const auto &I : RD->bases())
2774 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2775
2776 return Flags;
2777}
2778
2779/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2780/// classes with bases that do not satisfy the abi::__si_class_type_info
2781/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2782void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2783 llvm::Type *UnsignedIntLTy =
2784 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2785
2786 // Itanium C++ ABI 2.9.5p6c:
2787 // __flags is a word with flags describing details about the class
2788 // structure, which may be referenced by using the __flags_masks
2789 // enumeration. These flags refer to both direct and indirect bases.
2790 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2791 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2792
2793 // Itanium C++ ABI 2.9.5p6c:
2794 // __base_count is a word with the number of direct proper base class
2795 // descriptions that follow.
2796 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2797
2798 if (!RD->getNumBases())
2799 return;
2800
2801 llvm::Type *LongLTy =
2802 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2803
2804 // Now add the base class descriptions.
2805
2806 // Itanium C++ ABI 2.9.5p6c:
2807 // __base_info[] is an array of base class descriptions -- one for every
2808 // direct proper base. Each description is of the type:
2809 //
2810 // struct abi::__base_class_type_info {
2811 // public:
2812 // const __class_type_info *__base_type;
2813 // long __offset_flags;
2814 //
2815 // enum __offset_flags_masks {
2816 // __virtual_mask = 0x1,
2817 // __public_mask = 0x2,
2818 // __offset_shift = 8
2819 // };
2820 // };
2821 for (const auto &Base : RD->bases()) {
2822 // The __base_type member points to the RTTI for the base type.
2823 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2824
2825 const CXXRecordDecl *BaseDecl =
2826 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2827
2828 int64_t OffsetFlags = 0;
2829
2830 // All but the lower 8 bits of __offset_flags are a signed offset.
2831 // For a non-virtual base, this is the offset in the object of the base
2832 // subobject. For a virtual base, this is the offset in the virtual table of
2833 // the virtual base offset for the virtual base referenced (negative).
2834 CharUnits Offset;
2835 if (Base.isVirtual())
2836 Offset =
2837 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2838 else {
2839 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2840 Offset = Layout.getBaseClassOffset(BaseDecl);
2841 };
2842
2843 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2844
2845 // The low-order byte of __offset_flags contains flags, as given by the
2846 // masks from the enumeration __offset_flags_masks.
2847 if (Base.isVirtual())
2848 OffsetFlags |= BCTI_Virtual;
2849 if (Base.getAccessSpecifier() == AS_public)
2850 OffsetFlags |= BCTI_Public;
2851
2852 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2853 }
2854}
2855
2856/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2857/// used for pointer types.
2858void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2859 Qualifiers Quals;
2860 QualType UnqualifiedPointeeTy =
2861 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2862
2863 // Itanium C++ ABI 2.9.5p7:
2864 // __flags is a flag word describing the cv-qualification and other
2865 // attributes of the type pointed to
2866 unsigned Flags = ComputeQualifierFlags(Quals);
2867
2868 // Itanium C++ ABI 2.9.5p7:
2869 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2870 // incomplete class type, the incomplete target type flag is set.
2871 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2872 Flags |= PTI_Incomplete;
2873
2874 llvm::Type *UnsignedIntLTy =
2875 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2876 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2877
2878 // Itanium C++ ABI 2.9.5p7:
2879 // __pointee is a pointer to the std::type_info derivation for the
2880 // unqualified type being pointed to.
2881 llvm::Constant *PointeeTypeInfo =
2882 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2883 Fields.push_back(PointeeTypeInfo);
2884}
2885
2886/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2887/// struct, used for member pointer types.
2888void
2889ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2890 QualType PointeeTy = Ty->getPointeeType();
2891
2892 Qualifiers Quals;
2893 QualType UnqualifiedPointeeTy =
2894 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2895
2896 // Itanium C++ ABI 2.9.5p7:
2897 // __flags is a flag word describing the cv-qualification and other
2898 // attributes of the type pointed to.
2899 unsigned Flags = ComputeQualifierFlags(Quals);
2900
2901 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
2902
2903 // Itanium C++ ABI 2.9.5p7:
2904 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2905 // incomplete class type, the incomplete target type flag is set.
2906 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2907 Flags |= PTI_Incomplete;
2908
2909 if (IsIncompleteClassType(ClassType))
2910 Flags |= PTI_ContainingClassIncomplete;
2911
2912 llvm::Type *UnsignedIntLTy =
2913 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2914 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2915
2916 // Itanium C++ ABI 2.9.5p7:
2917 // __pointee is a pointer to the std::type_info derivation for the
2918 // unqualified type being pointed to.
2919 llvm::Constant *PointeeTypeInfo =
2920 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2921 Fields.push_back(PointeeTypeInfo);
2922
2923 // Itanium C++ ABI 2.9.5p9:
2924 // __context is a pointer to an abi::__class_type_info corresponding to the
2925 // class type containing the member pointed to
2926 // (e.g., the "A" in "int A::*").
2927 Fields.push_back(
2928 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
2929}
2930
2931llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
2932 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
2933}
2934
2935void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
2936 QualType PointerType = getContext().getPointerType(Type);
2937 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
2938 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
2939 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
2940 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
2941}
2942
2943void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
2944 QualType FundamentalTypes[] = {
2945 getContext().VoidTy, getContext().NullPtrTy,
2946 getContext().BoolTy, getContext().WCharTy,
2947 getContext().CharTy, getContext().UnsignedCharTy,
2948 getContext().SignedCharTy, getContext().ShortTy,
2949 getContext().UnsignedShortTy, getContext().IntTy,
2950 getContext().UnsignedIntTy, getContext().LongTy,
2951 getContext().UnsignedLongTy, getContext().LongLongTy,
2952 getContext().UnsignedLongLongTy, getContext().HalfTy,
2953 getContext().FloatTy, getContext().DoubleTy,
2954 getContext().LongDoubleTy, getContext().Char16Ty,
2955 getContext().Char32Ty,
2956 };
2957 for (const QualType &FundamentalType : FundamentalTypes)
2958 EmitFundamentalRTTIDescriptor(FundamentalType);
2959}
2960
2961/// What sort of uniqueness rules should we use for the RTTI for the
2962/// given type?
2963ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
2964 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
2965 if (shouldRTTIBeUnique())
2966 return RUK_Unique;
2967
2968 // It's only necessary for linkonce_odr or weak_odr linkage.
2969 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
2970 Linkage != llvm::GlobalValue::WeakODRLinkage)
2971 return RUK_Unique;
2972
2973 // It's only necessary with default visibility.
2974 if (CanTy->getVisibility() != DefaultVisibility)
2975 return RUK_Unique;
2976
2977 // If we're not required to publish this symbol, hide it.
2978 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
2979 return RUK_NonUniqueHidden;
2980
2981 // If we're required to publish this symbol, as we might be under an
2982 // explicit instantiation, leave it with default visibility but
2983 // enable string-comparisons.
2984 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
2985 return RUK_NonUniqueVisible;
2986}