blob: 93d5ff13ecb2f6afca56bc809dbc94641872994a [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
David Majnemer0c0b6d92014-10-31 20:09:12 +0000109 void emitVirtualObjectDelete(CodeGenFunction &CGF,
110 const FunctionDecl *OperatorDelete,
111 llvm::Value *Ptr, QualType ElementType,
112 bool UseGlobalDelete,
113 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000114
David Majnemere2cb8d12014-07-07 06:20:47 +0000115 void EmitFundamentalRTTIDescriptor(QualType Type);
116 void EmitFundamentalRTTIDescriptors();
117 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
118
David Majnemer1162d252014-06-22 19:05:33 +0000119 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
120 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
121 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
122 llvm::Value *ThisPtr,
123 llvm::Type *StdTypeInfoPtrTy) override;
124
125 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
126 QualType SrcRecordTy) override;
127
128 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
129 QualType SrcRecordTy, QualType DestTy,
130 QualType DestRecordTy,
131 llvm::BasicBlock *CastEnd) override;
132
133 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
134 QualType SrcRecordTy,
135 QualType DestTy) override;
136
137 bool EmitBadCastCall(CodeGenFunction &CGF) override;
138
Craig Topper4f12f102014-03-12 06:41:41 +0000139 llvm::Value *
140 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
141 const CXXRecordDecl *ClassDecl,
142 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000143
Craig Topper4f12f102014-03-12 06:41:41 +0000144 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000145
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000146 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
147 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000148
Reid Klecknere7de47e2013-07-22 13:51:44 +0000149 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000151 // Itanium does not emit any destructor variant as an inline thunk.
152 // Delegating may occur as an optimization, but all variants are either
153 // emitted with external linkage or as linkonce if they are inline and used.
154 return false;
155 }
156
Craig Topper4f12f102014-03-12 06:41:41 +0000157 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000158
Reid Kleckner89077a12013-12-17 19:46:40 +0000159 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000160 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000161
Craig Topper4f12f102014-03-12 06:41:41 +0000162 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000163
Reid Kleckner89077a12013-12-17 19:46:40 +0000164 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
165 const CXXConstructorDecl *D,
166 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000167 bool Delegating,
168 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000169
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000170 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
171 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000172 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000173
Craig Topper4f12f102014-03-12 06:41:41 +0000174 void emitVTableDefinitions(CodeGenVTables &CGVT,
175 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000176
177 llvm::Value *getVTableAddressPointInStructor(
178 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
179 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000180 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000181
182 llvm::Constant *
183 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000184 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000185
186 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000187 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000188
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000189 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000190 llvm::Value *This,
191 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000192
David Majnemer0c0b6d92014-10-31 20:09:12 +0000193 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
194 const CXXDestructorDecl *Dtor,
195 CXXDtorType DtorType,
196 llvm::Value *This,
197 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000198
Craig Topper4f12f102014-03-12 06:41:41 +0000199 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000200
Hans Wennborgc94391d2014-06-06 20:04:01 +0000201 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
202 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000203 // Allow inlining of thunks by emitting them with available_externally
204 // linkage together with vtables when needed.
205 if (ForVTable)
206 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
207 }
208
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000209 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000210 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000211
212 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000213 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000214
David Majnemer196ac332014-09-11 23:05:02 +0000215 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
216 FunctionArgList &Args) const override {
217 assert(!Args.empty() && "expected the arglist to not be empty!");
218 return Args.size() - 1;
219 }
220
Craig Topper4f12f102014-03-12 06:41:41 +0000221 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
222 StringRef GetDeletedVirtualCallName() override
223 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000224
Craig Topper4f12f102014-03-12 06:41:41 +0000225 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000226 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
227 llvm::Value *NewPtr,
228 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000229 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000230 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000231 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
232 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000233 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000234
John McCallcdf7ef52010-11-06 09:44:32 +0000235 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000236 llvm::GlobalVariable *DeclPtr,
237 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000238 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000239 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000240
241 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000242 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000243 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000244 CodeGenModule &CGM,
245 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
246 CXXThreadLocals,
247 ArrayRef<llvm::Function *> CXXThreadLocalInits,
248 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
249
250 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000251 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
252 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000253
Craig Topper4f12f102014-03-12 06:41:41 +0000254 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000255
256 /**************************** RTTI Uniqueness ******************************/
257
258protected:
259 /// Returns true if the ABI requires RTTI type_info objects to be unique
260 /// across a program.
261 virtual bool shouldRTTIBeUnique() const { return true; }
262
263public:
264 /// What sort of unique-RTTI behavior should we use?
265 enum RTTIUniquenessKind {
266 /// We are guaranteeing, or need to guarantee, that the RTTI string
267 /// is unique.
268 RUK_Unique,
269
270 /// We are not guaranteeing uniqueness for the RTTI string, so we
271 /// can demote to hidden visibility but must use string comparisons.
272 RUK_NonUniqueHidden,
273
274 /// We are not guaranteeing uniqueness for the RTTI string, so we
275 /// have to use string comparisons, but we also have to emit it with
276 /// non-hidden visibility.
277 RUK_NonUniqueVisible
278 };
279
280 /// Return the required visibility status for the given type and linkage in
281 /// the current ABI.
282 RTTIUniquenessKind
283 classifyRTTIUniqueness(QualType CanTy,
284 llvm::GlobalValue::LinkageTypes Linkage) const;
285 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000286
287 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000288};
John McCall86353412010-08-21 22:46:04 +0000289
290class ARMCXXABI : public ItaniumCXXABI {
291public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000292 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
293 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
294 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000295
Craig Topper4f12f102014-03-12 06:41:41 +0000296 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000297 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
298 isa<CXXDestructorDecl>(GD.getDecl()) &&
299 GD.getDtorType() != Dtor_Deleting));
300 }
John McCall5d865c322010-08-31 07:33:07 +0000301
Craig Topper4f12f102014-03-12 06:41:41 +0000302 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
303 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000304
Craig Topper4f12f102014-03-12 06:41:41 +0000305 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000306 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
307 llvm::Value *NewPtr,
308 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000309 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000310 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000311 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000312 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000313};
Tim Northovera2ee4332014-03-29 15:09:45 +0000314
315class iOS64CXXABI : public ARMCXXABI {
316public:
317 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000318
319 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000320 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000321};
Charles Davis4e786dd2010-05-25 19:52:27 +0000322}
323
Charles Davis53c59df2010-08-16 03:33:14 +0000324CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000325 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000326 // For IR-generation purposes, there's no significant difference
327 // between the ARM and iOS ABIs.
328 case TargetCXXABI::GenericARM:
329 case TargetCXXABI::iOS:
330 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000331
Tim Northovera2ee4332014-03-29 15:09:45 +0000332 case TargetCXXABI::iOS64:
333 return new iOS64CXXABI(CGM);
334
Tim Northover9bb857a2013-01-31 12:13:10 +0000335 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
336 // include the other 32-bit ARM oddities: constructor/destructor return values
337 // and array cookies.
338 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000339 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
340 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000341
John McCall57625922013-01-25 23:36:14 +0000342 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000343 if (CGM.getContext().getTargetInfo().getTriple().getArch()
344 == llvm::Triple::le32) {
345 // For PNaCl, use ARM-style method pointers so that PNaCl code
346 // does not assume anything about the alignment of function
347 // pointers.
348 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
349 /* UseARMGuardVarABI = */ false);
350 }
John McCall57625922013-01-25 23:36:14 +0000351 return new ItaniumCXXABI(CGM);
352
353 case TargetCXXABI::Microsoft:
354 llvm_unreachable("Microsoft ABI is not Itanium-based");
355 }
356 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000357}
358
Chris Lattnera5f58b02011-07-09 17:41:47 +0000359llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000360ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
361 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000362 return CGM.PtrDiffTy;
363 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
John McCall1c456c82010-08-22 06:43:33 +0000364}
365
John McCalld9c6c0b2010-08-22 00:59:17 +0000366/// In the Itanium and ARM ABIs, method pointers have the form:
367/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
368///
369/// In the Itanium ABI:
370/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
371/// - the this-adjustment is (memptr.adj)
372/// - the virtual offset is (memptr.ptr - 1)
373///
374/// In the ARM ABI:
375/// - method pointers are virtual if (memptr.adj & 1) is nonzero
376/// - the this-adjustment is (memptr.adj >> 1)
377/// - the virtual offset is (memptr.ptr)
378/// ARM uses 'adj' for the virtual flag because Thumb functions
379/// may be only single-byte aligned.
380///
381/// If the member is virtual, the adjusted 'this' pointer points
382/// to a vtable pointer from which the virtual offset is applied.
383///
384/// If the member is non-virtual, memptr.ptr is the address of
385/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000386llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
387 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
388 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000389 CGBuilderTy &Builder = CGF.Builder;
390
391 const FunctionProtoType *FPT =
392 MPT->getPointeeType()->getAs<FunctionProtoType>();
393 const CXXRecordDecl *RD =
394 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
395
Chris Lattner2192fe52011-07-18 04:24:23 +0000396 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000397 CGM.getTypes().GetFunctionType(
398 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000399
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000400 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000401
John McCalld9c6c0b2010-08-22 00:59:17 +0000402 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
403 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
404 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
405
John McCalla1dee5302010-08-22 10:59:02 +0000406 // Extract memptr.adj, which is in the second field.
407 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000408
409 // Compute the true adjustment.
410 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000411 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000412 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000413
414 // Apply the adjustment and cast back to the original struct type
415 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000416 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
417 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
418 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000419
420 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000421 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000422
423 // If the LSB in the function pointer is 1, the function pointer points to
424 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000425 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000426 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000427 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
428 else
429 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
430 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000431 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
432
433 // In the virtual path, the adjustment left 'This' pointing to the
434 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000435 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000436 CGF.EmitBlock(FnVirtual);
437
438 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000439 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000440 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000441
442 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000443 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000444 if (!UseARMMethodPtrABI)
445 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000446 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000447
448 // Load the virtual function to call.
449 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000450 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000451 CGF.EmitBranch(FnEnd);
452
453 // In the non-virtual path, the function pointer is actually a
454 // function pointer.
455 CGF.EmitBlock(FnNonVirtual);
456 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000457 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000458
459 // We're done.
460 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000461 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000462 Callee->addIncoming(VirtualFn, FnVirtual);
463 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
464 return Callee;
465}
John McCalla8bbb822010-08-22 03:04:22 +0000466
John McCallc134eb52010-08-31 21:07:20 +0000467/// Compute an l-value by applying the given pointer-to-member to a
468/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000469llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
470 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
471 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000472 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000473
474 CGBuilderTy &Builder = CGF.Builder;
475
Micah Villmowea2fea22012-10-25 15:39:14 +0000476 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000477
478 // Cast to char*.
479 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
480
481 // Apply the offset, which we assume is non-null.
482 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
483
484 // Cast the address to the appropriate pointer type, adopting the
485 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000486 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000487 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000488 return Builder.CreateBitCast(Addr, PType);
489}
490
John McCallc62bb392012-02-15 01:22:51 +0000491/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
492/// conversion.
493///
494/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000495///
496/// Obligatory offset/adjustment diagram:
497/// <-- offset --> <-- adjustment -->
498/// |--------------------------|----------------------|--------------------|
499/// ^Derived address point ^Base address point ^Member address point
500///
501/// So when converting a base member pointer to a derived member pointer,
502/// we add the offset to the adjustment because the address point has
503/// decreased; and conversely, when converting a derived MP to a base MP
504/// we subtract the offset from the adjustment because the address point
505/// has increased.
506///
507/// The standard forbids (at compile time) conversion to and from
508/// virtual bases, which is why we don't have to consider them here.
509///
510/// The standard forbids (at run time) casting a derived MP to a base
511/// MP when the derived MP does not point to a member of the base.
512/// This is why -1 is a reasonable choice for null data member
513/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000514llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000515ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
516 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000517 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000518 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000519 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
520 E->getCastKind() == CK_ReinterpretMemberPointer);
521
522 // Under Itanium, reinterprets don't require any additional processing.
523 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
524
525 // Use constant emission if we can.
526 if (isa<llvm::Constant>(src))
527 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
528
529 llvm::Constant *adj = getMemberPointerAdjustment(E);
530 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000531
532 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000533 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000534
John McCallc62bb392012-02-15 01:22:51 +0000535 const MemberPointerType *destTy =
536 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000537
John McCall7a9aac22010-08-23 01:21:21 +0000538 // For member data pointers, this is just a matter of adding the
539 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000540 if (destTy->isMemberDataPointer()) {
541 llvm::Value *dst;
542 if (isDerivedToBase)
543 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000544 else
John McCallc62bb392012-02-15 01:22:51 +0000545 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000546
547 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000548 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
549 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
550 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000551 }
552
John McCalla1dee5302010-08-22 10:59:02 +0000553 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000554 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000555 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
556 offset <<= 1;
557 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000558 }
559
John McCallc62bb392012-02-15 01:22:51 +0000560 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
561 llvm::Value *dstAdj;
562 if (isDerivedToBase)
563 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000564 else
John McCallc62bb392012-02-15 01:22:51 +0000565 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000566
John McCallc62bb392012-02-15 01:22:51 +0000567 return Builder.CreateInsertValue(src, dstAdj, 1);
568}
569
570llvm::Constant *
571ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
572 llvm::Constant *src) {
573 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
574 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
575 E->getCastKind() == CK_ReinterpretMemberPointer);
576
577 // Under Itanium, reinterprets don't require any additional processing.
578 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
579
580 // If the adjustment is trivial, we don't need to do anything.
581 llvm::Constant *adj = getMemberPointerAdjustment(E);
582 if (!adj) return src;
583
584 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
585
586 const MemberPointerType *destTy =
587 E->getType()->castAs<MemberPointerType>();
588
589 // For member data pointers, this is just a matter of adding the
590 // offset if the source is non-null.
591 if (destTy->isMemberDataPointer()) {
592 // null maps to null.
593 if (src->isAllOnesValue()) return src;
594
595 if (isDerivedToBase)
596 return llvm::ConstantExpr::getNSWSub(src, adj);
597 else
598 return llvm::ConstantExpr::getNSWAdd(src, adj);
599 }
600
601 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000602 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000603 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
604 offset <<= 1;
605 adj = llvm::ConstantInt::get(adj->getType(), offset);
606 }
607
608 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
609 llvm::Constant *dstAdj;
610 if (isDerivedToBase)
611 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
612 else
613 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
614
615 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000616}
John McCall84fa5102010-08-22 04:16:24 +0000617
618llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000619ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000620 // Itanium C++ ABI 2.3:
621 // A NULL pointer is represented as -1.
622 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000623 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000624
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000625 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000626 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000627 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000628}
629
John McCallf3a88602011-02-03 08:15:49 +0000630llvm::Constant *
631ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
632 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000633 // Itanium C++ ABI 2.3:
634 // A pointer to data member is an offset from the base address of
635 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000636 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000637}
638
John McCall2979fe02011-04-12 00:42:48 +0000639llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000640 return BuildMemberPointer(MD, CharUnits::Zero());
641}
642
643llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
644 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000645 assert(MD->isInstance() && "Member function must not be static!");
646 MD = MD->getCanonicalDecl();
647
648 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000649
650 // Get the function pointer (or index if this is a virtual function).
651 llvm::Constant *MemPtr[2];
652 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000653 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000654
Ken Dyckdf016282011-04-09 01:30:02 +0000655 const ASTContext &Context = getContext();
656 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000657 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000658 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000659
Mark Seabornedf0d382013-07-24 16:25:13 +0000660 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000661 // ARM C++ ABI 3.2.1:
662 // This ABI specifies that adj contains twice the this
663 // adjustment, plus 1 if the member function is virtual. The
664 // least significant bit of adj then makes exactly the same
665 // discrimination as the least significant bit of ptr does for
666 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000667 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
668 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000669 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000670 } else {
671 // Itanium C++ ABI 2.3:
672 // For a virtual function, [the pointer field] is 1 plus the
673 // virtual table offset (in bytes) of the function,
674 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000675 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
676 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000677 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000678 }
679 } else {
John McCall2979fe02011-04-12 00:42:48 +0000680 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000681 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000682 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000683 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000684 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000685 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000686 } else {
John McCall2979fe02011-04-12 00:42:48 +0000687 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
688 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000689 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000690 }
John McCall2979fe02011-04-12 00:42:48 +0000691 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000692
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000693 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000694 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
695 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000696 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000697 }
John McCall1c456c82010-08-22 06:43:33 +0000698
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000699 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000700}
701
Richard Smithdafff942012-01-14 04:30:29 +0000702llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
703 QualType MPType) {
704 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
705 const ValueDecl *MPD = MP.getMemberPointerDecl();
706 if (!MPD)
707 return EmitNullMemberPointer(MPT);
708
Reid Kleckner452abac2013-05-09 21:01:17 +0000709 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000710
711 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
712 return BuildMemberPointer(MD, ThisAdjustment);
713
714 CharUnits FieldOffset =
715 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
716 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
717}
718
John McCall131d97d2010-08-22 08:30:07 +0000719/// The comparison algorithm is pretty easy: the member pointers are
720/// the same if they're either bitwise identical *or* both null.
721///
722/// ARM is different here only because null-ness is more complicated.
723llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000724ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
725 llvm::Value *L,
726 llvm::Value *R,
727 const MemberPointerType *MPT,
728 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000729 CGBuilderTy &Builder = CGF.Builder;
730
John McCall131d97d2010-08-22 08:30:07 +0000731 llvm::ICmpInst::Predicate Eq;
732 llvm::Instruction::BinaryOps And, Or;
733 if (Inequality) {
734 Eq = llvm::ICmpInst::ICMP_NE;
735 And = llvm::Instruction::Or;
736 Or = llvm::Instruction::And;
737 } else {
738 Eq = llvm::ICmpInst::ICMP_EQ;
739 And = llvm::Instruction::And;
740 Or = llvm::Instruction::Or;
741 }
742
John McCall7a9aac22010-08-23 01:21:21 +0000743 // Member data pointers are easy because there's a unique null
744 // value, so it just comes down to bitwise equality.
745 if (MPT->isMemberDataPointer())
746 return Builder.CreateICmp(Eq, L, R);
747
748 // For member function pointers, the tautologies are more complex.
749 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000750 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000751 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000752 // (L == R) <==> (L.ptr == R.ptr &&
753 // (L.adj == R.adj ||
754 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000755 // The inequality tautologies have exactly the same structure, except
756 // applying De Morgan's laws.
757
758 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
759 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
760
John McCall131d97d2010-08-22 08:30:07 +0000761 // This condition tests whether L.ptr == R.ptr. This must always be
762 // true for equality to hold.
763 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
764
765 // This condition, together with the assumption that L.ptr == R.ptr,
766 // tests whether the pointers are both null. ARM imposes an extra
767 // condition.
768 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
769 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
770
771 // This condition tests whether L.adj == R.adj. If this isn't
772 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000773 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
774 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000775 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
776
777 // Null member function pointers on ARM clear the low bit of Adj,
778 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000779 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000780 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
781
782 // Compute (l.adj | r.adj) & 1 and test it against zero.
783 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
784 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
785 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
786 "cmp.or.adj");
787 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
788 }
789
790 // Tie together all our conditions.
791 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
792 Result = Builder.CreateBinOp(And, PtrEq, Result,
793 Inequality ? "memptr.ne" : "memptr.eq");
794 return Result;
795}
796
797llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000798ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
799 llvm::Value *MemPtr,
800 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000801 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000802
803 /// For member data pointers, this is just a check against -1.
804 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000805 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000806 llvm::Value *NegativeOne =
807 llvm::Constant::getAllOnesValue(MemPtr->getType());
808 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
809 }
John McCall131d97d2010-08-22 08:30:07 +0000810
Daniel Dunbar914bc412011-04-19 23:10:47 +0000811 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000812 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000813
814 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
815 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
816
Daniel Dunbar914bc412011-04-19 23:10:47 +0000817 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
818 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000819 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000820 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000821 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000822 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000823 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
824 "memptr.isvirtual");
825 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000826 }
827
828 return Result;
829}
John McCall1c456c82010-08-22 06:43:33 +0000830
Reid Kleckner40ca9132014-05-13 22:05:45 +0000831bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
832 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
833 if (!RD)
834 return false;
835
Reid Klecknerd355ca72014-05-15 01:26:32 +0000836 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
837 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
838 // special members.
839 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000840 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
841 return true;
842 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000843 return false;
844}
845
John McCall614dbdc2010-08-22 21:01:12 +0000846/// The Itanium ABI requires non-zero initialization only for data
847/// member pointers, for which '0' is a valid offset.
848bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
849 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000850}
John McCall5d865c322010-08-31 07:33:07 +0000851
John McCall82fb8922012-09-25 10:10:39 +0000852/// The Itanium ABI always places an offset to the complete object
853/// at entry -2 in the vtable.
David Majnemer0c0b6d92014-10-31 20:09:12 +0000854void ItaniumCXXABI::emitVirtualObjectDelete(
855 CodeGenFunction &CGF, const FunctionDecl *OperatorDelete, llvm::Value *Ptr,
856 QualType ElementType, bool UseGlobalDelete, const CXXDestructorDecl *Dtor) {
857 if (UseGlobalDelete) {
858 // Derive the complete-object pointer, which is what we need
859 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000860
David Majnemer0c0b6d92014-10-31 20:09:12 +0000861 // Grab the vtable pointer as an intptr_t*.
862 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000863
David Majnemer0c0b6d92014-10-31 20:09:12 +0000864 // Track back to entry -2 and pull out the offset there.
865 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
866 VTable, -2, "complete-offset.ptr");
867 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
868 Offset->setAlignment(CGF.PointerAlignInBytes);
869
870 // Apply the offset.
871 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
872 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
873
874 // If we're supposed to call the global delete, make sure we do so
875 // even if the destructor throws.
876 CGF.pushCallObjectDeleteCleanup(OperatorDelete, CompletePtr, ElementType);
877 }
878
879 // FIXME: Provide a source location here even though there's no
880 // CXXMemberCallExpr for dtor call.
881 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
882 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
883
884 if (UseGlobalDelete)
885 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000886}
887
David Majnemer1162d252014-06-22 19:05:33 +0000888static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
889 // void *__dynamic_cast(const void *sub,
890 // const abi::__class_type_info *src,
891 // const abi::__class_type_info *dst,
892 // std::ptrdiff_t src2dst_offset);
893
894 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
895 llvm::Type *PtrDiffTy =
896 CGF.ConvertType(CGF.getContext().getPointerDiffType());
897
898 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
899
900 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
901
902 // Mark the function as nounwind readonly.
903 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
904 llvm::Attribute::ReadOnly };
905 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
906 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
907
908 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
909}
910
911static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
912 // void __cxa_bad_cast();
913 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
914 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
915}
916
917/// \brief Compute the src2dst_offset hint as described in the
918/// Itanium C++ ABI [2.9.7]
919static CharUnits computeOffsetHint(ASTContext &Context,
920 const CXXRecordDecl *Src,
921 const CXXRecordDecl *Dst) {
922 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
923 /*DetectVirtual=*/false);
924
925 // If Dst is not derived from Src we can skip the whole computation below and
926 // return that Src is not a public base of Dst. Record all inheritance paths.
927 if (!Dst->isDerivedFrom(Src, Paths))
928 return CharUnits::fromQuantity(-2ULL);
929
930 unsigned NumPublicPaths = 0;
931 CharUnits Offset;
932
933 // Now walk all possible inheritance paths.
934 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
935 ++I) {
936 if (I->Access != AS_public) // Ignore non-public inheritance.
937 continue;
938
939 ++NumPublicPaths;
940
941 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
942 // If the path contains a virtual base class we can't give any hint.
943 // -1: no hint.
944 if (J->Base->isVirtual())
945 return CharUnits::fromQuantity(-1ULL);
946
947 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
948 continue;
949
950 // Accumulate the base class offsets.
951 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
952 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
953 }
954 }
955
956 // -2: Src is not a public base of Dst.
957 if (NumPublicPaths == 0)
958 return CharUnits::fromQuantity(-2ULL);
959
960 // -3: Src is a multiple public base type but never a virtual base type.
961 if (NumPublicPaths > 1)
962 return CharUnits::fromQuantity(-3ULL);
963
964 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
965 // Return the offset of Src from the origin of Dst.
966 return Offset;
967}
968
969static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
970 // void __cxa_bad_typeid();
971 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
972
973 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
974}
975
976bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
977 QualType SrcRecordTy) {
978 return IsDeref;
979}
980
981void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
982 llvm::Value *Fn = getBadTypeidFn(CGF);
983 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
984 CGF.Builder.CreateUnreachable();
985}
986
987llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
988 QualType SrcRecordTy,
989 llvm::Value *ThisPtr,
990 llvm::Type *StdTypeInfoPtrTy) {
991 llvm::Value *Value =
992 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
993
994 // Load the type info.
995 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
996 return CGF.Builder.CreateLoad(Value);
997}
998
999bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1000 QualType SrcRecordTy) {
1001 return SrcIsPtr;
1002}
1003
1004llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1005 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1006 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1007 llvm::Type *PtrDiffLTy =
1008 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1009 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1010
1011 llvm::Value *SrcRTTI =
1012 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1013 llvm::Value *DestRTTI =
1014 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1015
1016 // Compute the offset hint.
1017 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1018 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1019 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1020 PtrDiffLTy,
1021 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1022
1023 // Emit the call to __dynamic_cast.
1024 Value = CGF.EmitCastToVoidPtr(Value);
1025
1026 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1027 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1028 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1029
1030 /// C++ [expr.dynamic.cast]p9:
1031 /// A failed cast to reference type throws std::bad_cast
1032 if (DestTy->isReferenceType()) {
1033 llvm::BasicBlock *BadCastBlock =
1034 CGF.createBasicBlock("dynamic_cast.bad_cast");
1035
1036 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1037 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1038
1039 CGF.EmitBlock(BadCastBlock);
1040 EmitBadCastCall(CGF);
1041 }
1042
1043 return Value;
1044}
1045
1046llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1047 llvm::Value *Value,
1048 QualType SrcRecordTy,
1049 QualType DestTy) {
1050 llvm::Type *PtrDiffLTy =
1051 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1052 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1053
1054 // Get the vtable pointer.
1055 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1056
1057 // Get the offset-to-top from the vtable.
1058 llvm::Value *OffsetToTop =
1059 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1060 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1061
1062 // Finally, add the offset to the pointer.
1063 Value = CGF.EmitCastToVoidPtr(Value);
1064 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1065
1066 return CGF.Builder.CreateBitCast(Value, DestLTy);
1067}
1068
1069bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1070 llvm::Value *Fn = getBadCastFn(CGF);
1071 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1072 CGF.Builder.CreateUnreachable();
1073 return true;
1074}
1075
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001076llvm::Value *
1077ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1078 llvm::Value *This,
1079 const CXXRecordDecl *ClassDecl,
1080 const CXXRecordDecl *BaseClassDecl) {
1081 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1082 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001083 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1084 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001085
1086 llvm::Value *VBaseOffsetPtr =
1087 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1088 "vbase.offset.ptr");
1089 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1090 CGM.PtrDiffTy->getPointerTo());
1091
1092 llvm::Value *VBaseOffset =
1093 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1094
1095 return VBaseOffset;
1096}
1097
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001098void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1099 // Just make sure we're in sync with TargetCXXABI.
1100 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1101
Rafael Espindolac3cde362013-12-09 14:51:17 +00001102 // The constructor used for constructing this as a base class;
1103 // ignores virtual bases.
1104 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1105
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001106 // The constructor used for constructing this as a complete class;
1107 // constucts the virtual bases, then calls the base constructor.
1108 if (!D->getParent()->isAbstract()) {
1109 // We don't need to emit the complete ctor if the class is abstract.
1110 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1111 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001112}
1113
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001114void
1115ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1116 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001117 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001118
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001119 // All parameters are already in place except VTT, which goes after 'this'.
1120 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001121
1122 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001123 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1124 ArgTys.insert(ArgTys.begin() + 1,
1125 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001126}
1127
Reid Klecknere7de47e2013-07-22 13:51:44 +00001128void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001129 // The destructor used for destructing this as a base class; ignores
1130 // virtual bases.
1131 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001132
1133 // The destructor used for destructing this as a most-derived class;
1134 // call the base destructor and then destructs any virtual bases.
1135 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1136
Rafael Espindolac3cde362013-12-09 14:51:17 +00001137 // The destructor in a virtual table is always a 'deleting'
1138 // destructor, which calls the complete destructor and then uses the
1139 // appropriate operator delete.
1140 if (D->isVirtual())
1141 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001142}
1143
Reid Kleckner89077a12013-12-17 19:46:40 +00001144void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1145 QualType &ResTy,
1146 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001147 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001148 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001149
1150 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001151 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001152 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001153
1154 // FIXME: avoid the fake decl
1155 QualType T = Context.getPointerType(Context.VoidPtrTy);
1156 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001157 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001158 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001159 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001160 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001161 }
1162}
1163
John McCall5d865c322010-08-31 07:33:07 +00001164void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1165 /// Initialize the 'this' slot.
1166 EmitThisParam(CGF);
1167
1168 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001169 if (getStructorImplicitParamDecl(CGF)) {
1170 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1171 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001172 }
John McCall5d865c322010-08-31 07:33:07 +00001173
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001174 /// If this is a function that the ABI specifies returns 'this', initialize
1175 /// the return slot to 'this' at the start of the function.
1176 ///
1177 /// Unlike the setting of return types, this is done within the ABI
1178 /// implementation instead of by clients of CGCXXABI because:
1179 /// 1) getThisValue is currently protected
1180 /// 2) in theory, an ABI could implement 'this' returns some other way;
1181 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001182 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001183 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001184}
1185
Reid Kleckner89077a12013-12-17 19:46:40 +00001186unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1187 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1188 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1189 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1190 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001191
Reid Kleckner89077a12013-12-17 19:46:40 +00001192 // Insert the implicit 'vtt' argument as the second argument.
1193 llvm::Value *VTT =
1194 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1195 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1196 Args.insert(Args.begin() + 1,
1197 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1198 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001199}
1200
1201void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1202 const CXXDestructorDecl *DD,
1203 CXXDtorType Type, bool ForVirtualBase,
1204 bool Delegating, llvm::Value *This) {
1205 GlobalDecl GD(DD, Type);
1206 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1207 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1208
Craig Topper8a13c412014-05-21 05:09:00 +00001209 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001210 if (getContext().getLangOpts().AppleKext)
1211 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1212
1213 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001214 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001215
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001216 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1217 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001218}
1219
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001220void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1221 const CXXRecordDecl *RD) {
1222 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1223 if (VTable->hasInitializer())
1224 return;
1225
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001226 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001227 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1228 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001229 llvm::Constant *RTTI =
1230 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001231
1232 // Create and set the initializer.
1233 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1234 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001235 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001236 VTable->setInitializer(Init);
1237
1238 // Set the correct linkage.
1239 VTable->setLinkage(Linkage);
1240
1241 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001242 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001243
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001244 // Use pointer alignment for the vtable. Otherwise we would align them based
1245 // on the size of the initializer which doesn't make sense as only single
1246 // values are read.
1247 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1248 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1249
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001250 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1251 // we will emit the typeinfo for the fundamental types. This is the
1252 // same behaviour as GCC.
1253 const DeclContext *DC = RD->getDeclContext();
1254 if (RD->getIdentifier() &&
1255 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1256 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1257 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1258 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001259 EmitFundamentalRTTIDescriptors();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001260}
1261
1262llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1263 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1264 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1265 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1266 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1267
1268 llvm::Value *VTableAddressPoint;
1269 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1270 // Get the secondary vpointer index.
1271 uint64_t VirtualPointerIndex =
1272 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1273
1274 /// Load the VTT.
1275 llvm::Value *VTT = CGF.LoadCXXVTT();
1276 if (VirtualPointerIndex)
1277 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1278
1279 // And load the address point from the VTT.
1280 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1281 } else {
1282 llvm::Constant *VTable =
1283 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001284 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1285 .getVTableLayout(VTableClass)
1286 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001287 VTableAddressPoint =
1288 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1289 }
1290
1291 return VTableAddressPoint;
1292}
1293
1294llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1295 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1296 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1297
1298 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001299 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1300 .getVTableLayout(VTableClass)
1301 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001302 llvm::Value *Indices[] = {
1303 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1304 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1305 };
1306
1307 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1308}
1309
1310llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1311 CharUnits VPtrOffset) {
1312 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1313
1314 llvm::GlobalVariable *&VTable = VTables[RD];
1315 if (VTable)
1316 return VTable;
1317
1318 // Queue up this v-table for possible deferred emission.
1319 CGM.addDeferredVTable(RD);
1320
1321 SmallString<256> OutName;
1322 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001323 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001324 Out.flush();
1325 StringRef Name = OutName.str();
1326
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001327 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001328 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1329 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1330
1331 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1332 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1333 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001334
1335 if (RD->hasAttr<DLLImportAttr>())
1336 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1337 else if (RD->hasAttr<DLLExportAttr>())
1338 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1339
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001340 return VTable;
1341}
1342
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001343llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1344 GlobalDecl GD,
1345 llvm::Value *This,
1346 llvm::Type *Ty) {
1347 GD = GD.getCanonicalDecl();
1348 Ty = Ty->getPointerTo()->getPointerTo();
1349 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1350
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001351 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001352 llvm::Value *VFuncPtr =
1353 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1354 return CGF.Builder.CreateLoad(VFuncPtr);
1355}
1356
David Majnemer0c0b6d92014-10-31 20:09:12 +00001357llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1358 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1359 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001360 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001361 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1362
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001363 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1364 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001365 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001366 llvm::Value *Callee =
1367 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001368
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001369 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1370 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001371 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001372}
1373
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001374void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001375 CodeGenVTables &VTables = CGM.getVTables();
1376 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001377 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001378}
1379
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001380static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1381 llvm::Value *Ptr,
1382 int64_t NonVirtualAdjustment,
1383 int64_t VirtualAdjustment,
1384 bool IsReturnAdjustment) {
1385 if (!NonVirtualAdjustment && !VirtualAdjustment)
1386 return Ptr;
1387
1388 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1389 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1390
1391 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1392 // Perform the non-virtual adjustment for a base-to-derived cast.
1393 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1394 }
1395
1396 if (VirtualAdjustment) {
1397 llvm::Type *PtrDiffTy =
1398 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1399
1400 // Perform the virtual adjustment.
1401 llvm::Value *VTablePtrPtr =
1402 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1403
1404 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1405
1406 llvm::Value *OffsetPtr =
1407 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1408
1409 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1410
1411 // Load the adjustment offset from the vtable.
1412 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1413
1414 // Adjust our pointer.
1415 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1416 }
1417
1418 if (NonVirtualAdjustment && IsReturnAdjustment) {
1419 // Perform the non-virtual adjustment for a derived-to-base cast.
1420 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1421 }
1422
1423 // Cast back to the original type.
1424 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1425}
1426
1427llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1428 llvm::Value *This,
1429 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001430 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1431 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001432 /*IsReturnAdjustment=*/false);
1433}
1434
1435llvm::Value *
1436ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1437 const ReturnAdjustment &RA) {
1438 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1439 RA.Virtual.Itanium.VBaseOffsetOffset,
1440 /*IsReturnAdjustment=*/true);
1441}
1442
John McCall5d865c322010-08-31 07:33:07 +00001443void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1444 RValue RV, QualType ResultType) {
1445 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1446 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1447
1448 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001449 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001450 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1451 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1452 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1453}
John McCall8ed55a52010-09-02 09:58:18 +00001454
1455/************************** Array allocation cookies **************************/
1456
John McCallb91cd662012-05-01 05:23:51 +00001457CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1458 // The array cookie is a size_t; pad that up to the element alignment.
1459 // The cookie is actually right-justified in that space.
1460 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1461 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001462}
1463
1464llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1465 llvm::Value *NewPtr,
1466 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001467 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001468 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001469 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001470
Micah Villmowea2fea22012-10-25 15:39:14 +00001471 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001472
John McCall9bca9232010-09-02 10:25:57 +00001473 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001474 QualType SizeTy = Ctx.getSizeType();
1475 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1476
1477 // The size of the cookie.
1478 CharUnits CookieSize =
1479 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001480 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001481
1482 // Compute an offset to the cookie.
1483 llvm::Value *CookiePtr = NewPtr;
1484 CharUnits CookieOffset = CookieSize - SizeSize;
1485 if (!CookieOffset.isZero())
1486 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1487 CookieOffset.getQuantity());
1488
1489 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001490 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1491 llvm::Value *NumElementsPtr =
1492 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1493 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001494 if (CGM.getLangOpts().Sanitize.Address && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001495 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001496 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001497 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1498 llvm::FunctionType *FTy =
1499 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1500 llvm::Constant *F =
1501 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1502 CGF.Builder.CreateCall(F, NumElementsPtr);
1503 }
John McCall8ed55a52010-09-02 09:58:18 +00001504
1505 // Finally, compute a pointer to the actual data buffer by skipping
1506 // over the cookie completely.
1507 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1508 CookieSize.getQuantity());
1509}
1510
John McCallb91cd662012-05-01 05:23:51 +00001511llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1512 llvm::Value *allocPtr,
1513 CharUnits cookieSize) {
1514 // The element size is right-justified in the cookie.
1515 llvm::Value *numElementsPtr = allocPtr;
1516 CharUnits numElementsOffset =
1517 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1518 if (!numElementsOffset.isZero())
1519 numElementsPtr =
1520 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1521 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001522
Micah Villmowea2fea22012-10-25 15:39:14 +00001523 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001524 numElementsPtr =
1525 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001526 if (!CGM.getLangOpts().Sanitize.Address || AS != 0)
1527 return CGF.Builder.CreateLoad(numElementsPtr);
1528 // In asan mode emit a function call instead of a regular load and let the
1529 // run-time deal with it: if the shadow is properly poisoned return the
1530 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1531 // We can't simply ignore this load using nosanitize metadata because
1532 // the metadata may be lost.
1533 llvm::FunctionType *FTy =
1534 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1535 llvm::Constant *F =
1536 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1537 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001538}
1539
John McCallb91cd662012-05-01 05:23:51 +00001540CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001541 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001542 // struct array_cookie {
1543 // std::size_t element_size; // element_size != 0
1544 // std::size_t element_count;
1545 // };
John McCallc19c7062013-01-25 23:36:19 +00001546 // But the base ABI doesn't give anything an alignment greater than
1547 // 8, so we can dismiss this as typical ABI-author blindness to
1548 // actual language complexity and round up to the element alignment.
1549 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1550 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001551}
1552
1553llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001554 llvm::Value *newPtr,
1555 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001556 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001557 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001558 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001559
John McCallc19c7062013-01-25 23:36:19 +00001560 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1561 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001562
1563 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001564 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001565
1566 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001567 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1568 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1569 getContext().getTypeSizeInChars(elementType).getQuantity());
1570 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001571
1572 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001573 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1574 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001575
1576 // Finally, compute a pointer to the actual data buffer by skipping
1577 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001578 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1579 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1580 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001581}
1582
John McCallb91cd662012-05-01 05:23:51 +00001583llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1584 llvm::Value *allocPtr,
1585 CharUnits cookieSize) {
1586 // The number of elements is at offset sizeof(size_t) relative to
1587 // the allocated pointer.
1588 llvm::Value *numElementsPtr
1589 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001590
Micah Villmowea2fea22012-10-25 15:39:14 +00001591 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001592 numElementsPtr =
1593 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1594 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001595}
1596
John McCall68ff0372010-09-08 01:44:27 +00001597/*********************** Static local initialization **************************/
1598
1599static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001600 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001601 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001602 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001603 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001604 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001605 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001606 llvm::AttributeSet::get(CGM.getLLVMContext(),
1607 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001608 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001609}
1610
1611static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001612 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001613 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001614 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001615 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001616 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001617 llvm::AttributeSet::get(CGM.getLLVMContext(),
1618 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001619 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001620}
1621
1622static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001623 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001624 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001625 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001626 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001627 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001628 llvm::AttributeSet::get(CGM.getLLVMContext(),
1629 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001630 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001631}
1632
1633namespace {
1634 struct CallGuardAbort : EHScopeStack::Cleanup {
1635 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001636 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001637
Craig Topper4f12f102014-03-12 06:41:41 +00001638 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001639 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1640 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001641 }
1642 };
1643}
1644
1645/// The ARM code here follows the Itanium code closely enough that we
1646/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001647void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1648 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001649 llvm::GlobalVariable *var,
1650 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001651 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001652
Richard Smithdbf74ba2013-04-14 23:01:42 +00001653 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001654 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001655 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1656 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001657
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001658 // If we have a global variable with internal linkage and thread-safe statics
1659 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001660 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1661
1662 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001663 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001664 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001665 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001666 // Guard variables are 64 bits in the generic ABI and size width on ARM
1667 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001668 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001669 }
John McCallb88a5662012-03-30 21:00:39 +00001670 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001671
John McCallb88a5662012-03-30 21:00:39 +00001672 // Create the guard variable if we don't already have it (as we
1673 // might if we're double-emitting this function body).
1674 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1675 if (!guard) {
1676 // Mangle the name for the guard.
1677 SmallString<256> guardName;
1678 {
1679 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001680 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001681 out.flush();
1682 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001683
John McCallb88a5662012-03-30 21:00:39 +00001684 // Create the guard variable with a zero-initializer.
1685 // Just absorb linkage and visibility from the guarded variable.
1686 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1687 false, var->getLinkage(),
1688 llvm::ConstantInt::get(guardTy, 0),
1689 guardName.str());
1690 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001691 // If the variable is thread-local, so is its guard variable.
1692 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001693
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001694 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1695 // as the associated data object
Reid Kleckner739aa122014-09-23 16:20:01 +00001696 if (!D.isLocalVarDecl() && var->isWeakForLinker() && CGM.supportsCOMDAT()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001697 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(var->getName());
1698 guard->setComdat(C);
1699 var->setComdat(C);
1700 CGF.CurFn->setComdat(C);
1701 }
1702
John McCallb88a5662012-03-30 21:00:39 +00001703 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1704 }
John McCall87590e62012-03-30 07:09:50 +00001705
John McCall68ff0372010-09-08 01:44:27 +00001706 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001707 //
John McCall68ff0372010-09-08 01:44:27 +00001708 // Itanium C++ ABI 3.3.2:
1709 // The following is pseudo-code showing how these functions can be used:
1710 // if (obj_guard.first_byte == 0) {
1711 // if ( __cxa_guard_acquire (&obj_guard) ) {
1712 // try {
1713 // ... initialize the object ...;
1714 // } catch (...) {
1715 // __cxa_guard_abort (&obj_guard);
1716 // throw;
1717 // }
1718 // ... queue object destructor with __cxa_atexit() ...;
1719 // __cxa_guard_release (&obj_guard);
1720 // }
1721 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001722
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001723 // Load the first byte of the guard variable.
1724 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001725 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001726 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001727
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001728 // Itanium ABI:
1729 // An implementation supporting thread-safety on multiprocessor
1730 // systems must also guarantee that references to the initialized
1731 // object do not occur before the load of the initialization flag.
1732 //
1733 // In LLVM, we do this by marking the load Acquire.
1734 if (threadsafe)
1735 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001736
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001737 // For ARM, we should only check the first bit, rather than the entire byte:
1738 //
1739 // ARM C++ ABI 3.2.3.1:
1740 // To support the potential use of initialization guard variables
1741 // as semaphores that are the target of ARM SWP and LDREX/STREX
1742 // synchronizing instructions we define a static initialization
1743 // guard variable to be a 4-byte aligned, 4-byte word with the
1744 // following inline access protocol.
1745 // #define INITIALIZED 1
1746 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1747 // if (__cxa_guard_acquire(&obj_guard))
1748 // ...
1749 // }
1750 //
1751 // and similarly for ARM64:
1752 //
1753 // ARM64 C++ ABI 3.2.2:
1754 // This ABI instead only specifies the value bit 0 of the static guard
1755 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1756 // variable is not initialized and 1 when it is.
1757 llvm::Value *V =
1758 (UseARMGuardVarABI && !useInt8GuardVariable)
1759 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1760 : LI;
1761 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001762
1763 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1764 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1765
1766 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001767 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001768
1769 CGF.EmitBlock(InitCheckBlock);
1770
1771 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001772 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001773 // Call __cxa_guard_acquire.
1774 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001775 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001776
1777 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1778
1779 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1780 InitBlock, EndBlock);
1781
1782 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001783 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001784
1785 CGF.EmitBlock(InitBlock);
1786 }
1787
1788 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001789 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001790
John McCall5aa52592011-06-17 07:33:57 +00001791 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001792 // Pop the guard-abort cleanup if we pushed one.
1793 CGF.PopCleanupBlock();
1794
1795 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001796 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001797 } else {
John McCallb88a5662012-03-30 21:00:39 +00001798 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001799 }
1800
1801 CGF.EmitBlock(EndBlock);
1802}
John McCallc84ed6a2012-05-01 06:13:13 +00001803
1804/// Register a global destructor using __cxa_atexit.
1805static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1806 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001807 llvm::Constant *addr,
1808 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001809 const char *Name = "__cxa_atexit";
1810 if (TLS) {
1811 const llvm::Triple &T = CGF.getTarget().getTriple();
1812 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1813 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001814
John McCallc84ed6a2012-05-01 06:13:13 +00001815 // We're assuming that the destructor function is something we can
1816 // reasonably call with the default CC. Go ahead and cast it to the
1817 // right prototype.
1818 llvm::Type *dtorTy =
1819 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1820
1821 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1822 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1823 llvm::FunctionType *atexitTy =
1824 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1825
1826 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001827 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001828 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1829 fn->setDoesNotThrow();
1830
1831 // Create a variable that binds the atexit to this shared object.
1832 llvm::Constant *handle =
1833 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1834
1835 llvm::Value *args[] = {
1836 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1837 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1838 handle
1839 };
John McCall882987f2013-02-28 19:01:20 +00001840 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001841}
1842
1843/// Register a global destructor as best as we know how.
1844void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001845 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001846 llvm::Constant *dtor,
1847 llvm::Constant *addr) {
1848 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001849 if (CGM.getCodeGenOpts().CXAAtExit)
1850 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1851
1852 if (D.getTLSKind())
1853 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001854
1855 // In Apple kexts, we want to add a global destructor entry.
1856 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001857 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001858 // Generate a global destructor entry.
1859 return CGM.AddCXXDtorEntry(dtor, addr);
1860 }
1861
David Blaikieebe87e12013-08-27 23:57:18 +00001862 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001863}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001864
David Majnemer9b21c332014-07-11 20:28:10 +00001865static bool isThreadWrapperReplaceable(const VarDecl *VD,
1866 CodeGen::CodeGenModule &CGM) {
1867 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1868 // OS X prefers to have references to thread local variables to go through
1869 // the thread wrapper instead of directly referencing the backing variable.
1870 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1871 CGM.getTarget().getTriple().isMacOSX();
1872}
1873
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001874/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001875/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001876/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001877static llvm::GlobalValue::LinkageTypes
1878getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1879 llvm::GlobalValue::LinkageTypes VarLinkage =
1880 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1881
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001882 // For internal linkage variables, we don't need an external or weak wrapper.
1883 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1884 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001885
David Majnemer9b21c332014-07-11 20:28:10 +00001886 // If the thread wrapper is replaceable, give it appropriate linkage.
1887 if (isThreadWrapperReplaceable(VD, CGM)) {
1888 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1889 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1890 return llvm::GlobalVariable::WeakAnyLinkage;
1891 return VarLinkage;
1892 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001893 return llvm::GlobalValue::WeakODRLinkage;
1894}
1895
1896llvm::Function *
1897ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00001898 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001899 // Mangle the name for the thread_local wrapper function.
1900 SmallString<256> WrapperName;
1901 {
1902 llvm::raw_svector_ostream Out(WrapperName);
1903 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1904 Out.flush();
1905 }
1906
Alexander Musmanf94c3182014-09-26 06:28:25 +00001907 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001908 return cast<llvm::Function>(V);
1909
Alexander Musmanf94c3182014-09-26 06:28:25 +00001910 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001911 if (VD->getType()->isReferenceType())
1912 RetTy = RetTy->getPointerElementType();
1913
1914 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00001915 llvm::Function *Wrapper =
1916 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1917 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001918 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00001919 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00001920 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001921 return Wrapper;
1922}
1923
1924void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00001925 CodeGenModule &CGM,
1926 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
1927 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
1928 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
1929 llvm::Function *InitFunc = nullptr;
1930 if (!CXXThreadLocalInits.empty()) {
1931 // Generate a guarded initialization function.
1932 llvm::FunctionType *FTy =
1933 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1934 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001935 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00001936 /*TLS=*/true);
1937 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
1938 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
1939 llvm::GlobalVariable::InternalLinkage,
1940 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
1941 Guard->setThreadLocal(true);
1942 CodeGenFunction(CGM)
1943 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
1944 }
1945 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
1946 const VarDecl *VD = CXXThreadLocals[I].first;
1947 llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001948
David Majnemer9b21c332014-07-11 20:28:10 +00001949 // Some targets require that all access to thread local variables go through
1950 // the thread wrapper. This means that we cannot attempt to create a thread
1951 // wrapper or a thread helper.
1952 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1953 continue;
1954
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001955 // Mangle the name for the thread_local initialization function.
1956 SmallString<256> InitFnName;
1957 {
1958 llvm::raw_svector_ostream Out(InitFnName);
1959 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1960 Out.flush();
1961 }
1962
1963 // If we have a definition for the variable, emit the initialization
1964 // function as an alias to the global Init function (if any). Otherwise,
1965 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00001966 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001967 bool InitIsInitFunc = false;
1968 if (VD->hasDefinition()) {
1969 InitIsInitFunc = true;
1970 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00001971 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1972 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001973 } else {
1974 // Emit a weak global function referring to the initialization function.
1975 // This function will not exist if the TU defining the thread_local
1976 // variable in question does not need any dynamic initialization for
1977 // its thread_local variables.
1978 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1979 Init = llvm::Function::Create(
1980 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1981 &CGM.getModule());
1982 }
1983
1984 if (Init)
1985 Init->setVisibility(Var->getVisibility());
1986
1987 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1988 llvm::LLVMContext &Context = CGM.getModule().getContext();
1989 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1990 CGBuilderTy Builder(Entry);
1991 if (InitIsInitFunc) {
1992 if (Init)
1993 Builder.CreateCall(Init);
1994 } else {
1995 // Don't know whether we have an init function. Call it if it exists.
1996 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1997 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1998 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1999 Builder.CreateCondBr(Have, InitBB, ExitBB);
2000
2001 Builder.SetInsertPoint(InitBB);
2002 Builder.CreateCall(Init);
2003 Builder.CreateBr(ExitBB);
2004
2005 Builder.SetInsertPoint(ExitBB);
2006 }
2007
2008 // For a reference, the result of the wrapper function is a pointer to
2009 // the referenced object.
2010 llvm::Value *Val = Var;
2011 if (VD->getType()->isReferenceType()) {
2012 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2013 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2014 Val = LI;
2015 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002016 if (Val->getType() != Wrapper->getReturnType())
2017 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2018 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002019 Builder.CreateRet(Val);
2020 }
2021}
2022
Richard Smith0f383742014-03-26 22:48:22 +00002023LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2024 const VarDecl *VD,
2025 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002026 QualType T = VD->getType();
2027 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2028 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002029 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002030
2031 Val = CGF.Builder.CreateCall(Wrapper);
2032
2033 LValue LV;
2034 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002035 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002036 else
Richard Smith0f383742014-03-26 22:48:22 +00002037 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002038 // FIXME: need setObjCGCLValueClass?
2039 return LV;
2040}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002041
2042/// Return whether the given global decl needs a VTT parameter, which it does
2043/// if it's a base constructor or destructor with virtual bases.
2044bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2045 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2046
2047 // We don't have any virtual bases, just return early.
2048 if (!MD->getParent()->getNumVBases())
2049 return false;
2050
2051 // Check if we have a base constructor.
2052 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2053 return true;
2054
2055 // Check if we have a base destructor.
2056 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2057 return true;
2058
2059 return false;
2060}
David Majnemere2cb8d12014-07-07 06:20:47 +00002061
2062namespace {
2063class ItaniumRTTIBuilder {
2064 CodeGenModule &CGM; // Per-module state.
2065 llvm::LLVMContext &VMContext;
2066 const ItaniumCXXABI &CXXABI; // Per-module state.
2067
2068 /// Fields - The fields of the RTTI descriptor currently being built.
2069 SmallVector<llvm::Constant *, 16> Fields;
2070
2071 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2072 llvm::GlobalVariable *
2073 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2074
2075 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2076 /// descriptor of the given type.
2077 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2078
2079 /// BuildVTablePointer - Build the vtable pointer for the given type.
2080 void BuildVTablePointer(const Type *Ty);
2081
2082 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2083 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2084 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2085
2086 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2087 /// classes with bases that do not satisfy the abi::__si_class_type_info
2088 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2089 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2090
2091 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2092 /// for pointer types.
2093 void BuildPointerTypeInfo(QualType PointeeTy);
2094
2095 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2096 /// type_info for an object type.
2097 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2098
2099 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2100 /// struct, used for member pointer types.
2101 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2102
2103public:
2104 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2105 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2106
2107 // Pointer type info flags.
2108 enum {
2109 /// PTI_Const - Type has const qualifier.
2110 PTI_Const = 0x1,
2111
2112 /// PTI_Volatile - Type has volatile qualifier.
2113 PTI_Volatile = 0x2,
2114
2115 /// PTI_Restrict - Type has restrict qualifier.
2116 PTI_Restrict = 0x4,
2117
2118 /// PTI_Incomplete - Type is incomplete.
2119 PTI_Incomplete = 0x8,
2120
2121 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2122 /// (in pointer to member).
2123 PTI_ContainingClassIncomplete = 0x10
2124 };
2125
2126 // VMI type info flags.
2127 enum {
2128 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2129 VMI_NonDiamondRepeat = 0x1,
2130
2131 /// VMI_DiamondShaped - Class is diamond shaped.
2132 VMI_DiamondShaped = 0x2
2133 };
2134
2135 // Base class type info flags.
2136 enum {
2137 /// BCTI_Virtual - Base class is virtual.
2138 BCTI_Virtual = 0x1,
2139
2140 /// BCTI_Public - Base class is public.
2141 BCTI_Public = 0x2
2142 };
2143
2144 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2145 ///
2146 /// \param Force - true to force the creation of this RTTI value
2147 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2148};
2149}
2150
2151llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2152 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2153 SmallString<256> OutName;
2154 llvm::raw_svector_ostream Out(OutName);
2155 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2156 Out.flush();
2157 StringRef Name = OutName.str();
2158
2159 // We know that the mangled name of the type starts at index 4 of the
2160 // mangled name of the typename, so we can just index into it in order to
2161 // get the mangled name of the type.
2162 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2163 Name.substr(4));
2164
2165 llvm::GlobalVariable *GV =
2166 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2167
2168 GV->setInitializer(Init);
2169
2170 return GV;
2171}
2172
2173llvm::Constant *
2174ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2175 // Mangle the RTTI name.
2176 SmallString<256> OutName;
2177 llvm::raw_svector_ostream Out(OutName);
2178 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2179 Out.flush();
2180 StringRef Name = OutName.str();
2181
2182 // Look for an existing global.
2183 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2184
2185 if (!GV) {
2186 // Create a new global variable.
2187 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2188 /*Constant=*/true,
2189 llvm::GlobalValue::ExternalLinkage, nullptr,
2190 Name);
2191 }
2192
2193 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2194}
2195
2196/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2197/// info for that type is defined in the standard library.
2198static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2199 // Itanium C++ ABI 2.9.2:
2200 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2201 // the run-time support library. Specifically, the run-time support
2202 // library should contain type_info objects for the types X, X* and
2203 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2204 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2205 // long, unsigned long, long long, unsigned long long, float, double,
2206 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2207 // half-precision floating point types.
2208 switch (Ty->getKind()) {
2209 case BuiltinType::Void:
2210 case BuiltinType::NullPtr:
2211 case BuiltinType::Bool:
2212 case BuiltinType::WChar_S:
2213 case BuiltinType::WChar_U:
2214 case BuiltinType::Char_U:
2215 case BuiltinType::Char_S:
2216 case BuiltinType::UChar:
2217 case BuiltinType::SChar:
2218 case BuiltinType::Short:
2219 case BuiltinType::UShort:
2220 case BuiltinType::Int:
2221 case BuiltinType::UInt:
2222 case BuiltinType::Long:
2223 case BuiltinType::ULong:
2224 case BuiltinType::LongLong:
2225 case BuiltinType::ULongLong:
2226 case BuiltinType::Half:
2227 case BuiltinType::Float:
2228 case BuiltinType::Double:
2229 case BuiltinType::LongDouble:
2230 case BuiltinType::Char16:
2231 case BuiltinType::Char32:
2232 case BuiltinType::Int128:
2233 case BuiltinType::UInt128:
2234 case BuiltinType::OCLImage1d:
2235 case BuiltinType::OCLImage1dArray:
2236 case BuiltinType::OCLImage1dBuffer:
2237 case BuiltinType::OCLImage2d:
2238 case BuiltinType::OCLImage2dArray:
2239 case BuiltinType::OCLImage3d:
2240 case BuiltinType::OCLSampler:
2241 case BuiltinType::OCLEvent:
2242 return true;
2243
2244 case BuiltinType::Dependent:
2245#define BUILTIN_TYPE(Id, SingletonId)
2246#define PLACEHOLDER_TYPE(Id, SingletonId) \
2247 case BuiltinType::Id:
2248#include "clang/AST/BuiltinTypes.def"
2249 llvm_unreachable("asking for RRTI for a placeholder type!");
2250
2251 case BuiltinType::ObjCId:
2252 case BuiltinType::ObjCClass:
2253 case BuiltinType::ObjCSel:
2254 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2255 }
2256
2257 llvm_unreachable("Invalid BuiltinType Kind!");
2258}
2259
2260static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2261 QualType PointeeTy = PointerTy->getPointeeType();
2262 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2263 if (!BuiltinTy)
2264 return false;
2265
2266 // Check the qualifiers.
2267 Qualifiers Quals = PointeeTy.getQualifiers();
2268 Quals.removeConst();
2269
2270 if (!Quals.empty())
2271 return false;
2272
2273 return TypeInfoIsInStandardLibrary(BuiltinTy);
2274}
2275
2276/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2277/// information for the given type exists in the standard library.
2278static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2279 // Type info for builtin types is defined in the standard library.
2280 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2281 return TypeInfoIsInStandardLibrary(BuiltinTy);
2282
2283 // Type info for some pointer types to builtin types is defined in the
2284 // standard library.
2285 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2286 return TypeInfoIsInStandardLibrary(PointerTy);
2287
2288 return false;
2289}
2290
2291/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2292/// the given type exists somewhere else, and that we should not emit the type
2293/// information in this translation unit. Assumes that it is not a
2294/// standard-library type.
2295static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2296 QualType Ty) {
2297 ASTContext &Context = CGM.getContext();
2298
2299 // If RTTI is disabled, assume it might be disabled in the
2300 // translation unit that defines any potential key function, too.
2301 if (!Context.getLangOpts().RTTI) return false;
2302
2303 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2304 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2305 if (!RD->hasDefinition())
2306 return false;
2307
2308 if (!RD->isDynamicClass())
2309 return false;
2310
2311 // FIXME: this may need to be reconsidered if the key function
2312 // changes.
2313 return CGM.getVTables().isVTableExternal(RD);
2314 }
2315
2316 return false;
2317}
2318
2319/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2320static bool IsIncompleteClassType(const RecordType *RecordTy) {
2321 return !RecordTy->getDecl()->isCompleteDefinition();
2322}
2323
2324/// ContainsIncompleteClassType - Returns whether the given type contains an
2325/// incomplete class type. This is true if
2326///
2327/// * The given type is an incomplete class type.
2328/// * The given type is a pointer type whose pointee type contains an
2329/// incomplete class type.
2330/// * The given type is a member pointer type whose class is an incomplete
2331/// class type.
2332/// * The given type is a member pointer type whoise pointee type contains an
2333/// incomplete class type.
2334/// is an indirect or direct pointer to an incomplete class type.
2335static bool ContainsIncompleteClassType(QualType Ty) {
2336 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2337 if (IsIncompleteClassType(RecordTy))
2338 return true;
2339 }
2340
2341 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2342 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2343
2344 if (const MemberPointerType *MemberPointerTy =
2345 dyn_cast<MemberPointerType>(Ty)) {
2346 // Check if the class type is incomplete.
2347 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2348 if (IsIncompleteClassType(ClassType))
2349 return true;
2350
2351 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2352 }
2353
2354 return false;
2355}
2356
2357// CanUseSingleInheritance - Return whether the given record decl has a "single,
2358// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2359// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2360static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2361 // Check the number of bases.
2362 if (RD->getNumBases() != 1)
2363 return false;
2364
2365 // Get the base.
2366 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2367
2368 // Check that the base is not virtual.
2369 if (Base->isVirtual())
2370 return false;
2371
2372 // Check that the base is public.
2373 if (Base->getAccessSpecifier() != AS_public)
2374 return false;
2375
2376 // Check that the class is dynamic iff the base is.
2377 const CXXRecordDecl *BaseDecl =
2378 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2379 if (!BaseDecl->isEmpty() &&
2380 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2381 return false;
2382
2383 return true;
2384}
2385
2386void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2387 // abi::__class_type_info.
2388 static const char * const ClassTypeInfo =
2389 "_ZTVN10__cxxabiv117__class_type_infoE";
2390 // abi::__si_class_type_info.
2391 static const char * const SIClassTypeInfo =
2392 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2393 // abi::__vmi_class_type_info.
2394 static const char * const VMIClassTypeInfo =
2395 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2396
2397 const char *VTableName = nullptr;
2398
2399 switch (Ty->getTypeClass()) {
2400#define TYPE(Class, Base)
2401#define ABSTRACT_TYPE(Class, Base)
2402#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2403#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2404#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2405#include "clang/AST/TypeNodes.def"
2406 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2407
2408 case Type::LValueReference:
2409 case Type::RValueReference:
2410 llvm_unreachable("References shouldn't get here");
2411
2412 case Type::Auto:
2413 llvm_unreachable("Undeduced auto type shouldn't get here");
2414
2415 case Type::Builtin:
2416 // GCC treats vector and complex types as fundamental types.
2417 case Type::Vector:
2418 case Type::ExtVector:
2419 case Type::Complex:
2420 case Type::Atomic:
2421 // FIXME: GCC treats block pointers as fundamental types?!
2422 case Type::BlockPointer:
2423 // abi::__fundamental_type_info.
2424 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2425 break;
2426
2427 case Type::ConstantArray:
2428 case Type::IncompleteArray:
2429 case Type::VariableArray:
2430 // abi::__array_type_info.
2431 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2432 break;
2433
2434 case Type::FunctionNoProto:
2435 case Type::FunctionProto:
2436 // abi::__function_type_info.
2437 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2438 break;
2439
2440 case Type::Enum:
2441 // abi::__enum_type_info.
2442 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2443 break;
2444
2445 case Type::Record: {
2446 const CXXRecordDecl *RD =
2447 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2448
2449 if (!RD->hasDefinition() || !RD->getNumBases()) {
2450 VTableName = ClassTypeInfo;
2451 } else if (CanUseSingleInheritance(RD)) {
2452 VTableName = SIClassTypeInfo;
2453 } else {
2454 VTableName = VMIClassTypeInfo;
2455 }
2456
2457 break;
2458 }
2459
2460 case Type::ObjCObject:
2461 // Ignore protocol qualifiers.
2462 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2463
2464 // Handle id and Class.
2465 if (isa<BuiltinType>(Ty)) {
2466 VTableName = ClassTypeInfo;
2467 break;
2468 }
2469
2470 assert(isa<ObjCInterfaceType>(Ty));
2471 // Fall through.
2472
2473 case Type::ObjCInterface:
2474 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2475 VTableName = SIClassTypeInfo;
2476 } else {
2477 VTableName = ClassTypeInfo;
2478 }
2479 break;
2480
2481 case Type::ObjCObjectPointer:
2482 case Type::Pointer:
2483 // abi::__pointer_type_info.
2484 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2485 break;
2486
2487 case Type::MemberPointer:
2488 // abi::__pointer_to_member_type_info.
2489 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2490 break;
2491 }
2492
2493 llvm::Constant *VTable =
2494 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2495
2496 llvm::Type *PtrDiffTy =
2497 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2498
2499 // The vtable address point is 2.
2500 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2501 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2502 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2503
2504 Fields.push_back(VTable);
2505}
2506
2507/// \brief Return the linkage that the type info and type info name constants
2508/// should have for the given type.
2509static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2510 QualType Ty) {
2511 // Itanium C++ ABI 2.9.5p7:
2512 // In addition, it and all of the intermediate abi::__pointer_type_info
2513 // structs in the chain down to the abi::__class_type_info for the
2514 // incomplete class type must be prevented from resolving to the
2515 // corresponding type_info structs for the complete class type, possibly
2516 // by making them local static objects. Finally, a dummy class RTTI is
2517 // generated for the incomplete type that will not resolve to the final
2518 // complete class RTTI (because the latter need not exist), possibly by
2519 // making it a local static object.
2520 if (ContainsIncompleteClassType(Ty))
2521 return llvm::GlobalValue::InternalLinkage;
2522
2523 switch (Ty->getLinkage()) {
2524 case NoLinkage:
2525 case InternalLinkage:
2526 case UniqueExternalLinkage:
2527 return llvm::GlobalValue::InternalLinkage;
2528
2529 case VisibleNoLinkage:
2530 case ExternalLinkage:
2531 if (!CGM.getLangOpts().RTTI) {
2532 // RTTI is not enabled, which means that this type info struct is going
2533 // to be used for exception handling. Give it linkonce_odr linkage.
2534 return llvm::GlobalValue::LinkOnceODRLinkage;
2535 }
2536
2537 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2538 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2539 if (RD->hasAttr<WeakAttr>())
2540 return llvm::GlobalValue::WeakODRLinkage;
2541 if (RD->isDynamicClass())
2542 return CGM.getVTableLinkage(RD);
2543 }
2544
2545 return llvm::GlobalValue::LinkOnceODRLinkage;
2546 }
2547
2548 llvm_unreachable("Invalid linkage!");
2549}
2550
2551llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2552 // We want to operate on the canonical type.
2553 Ty = CGM.getContext().getCanonicalType(Ty);
2554
2555 // Check if we've already emitted an RTTI descriptor for this type.
2556 SmallString<256> OutName;
2557 llvm::raw_svector_ostream Out(OutName);
2558 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2559 Out.flush();
2560 StringRef Name = OutName.str();
2561
2562 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2563 if (OldGV && !OldGV->isDeclaration()) {
2564 assert(!OldGV->hasAvailableExternallyLinkage() &&
2565 "available_externally typeinfos not yet implemented");
2566
2567 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2568 }
2569
2570 // Check if there is already an external RTTI descriptor for this type.
2571 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2572 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2573 return GetAddrOfExternalRTTIDescriptor(Ty);
2574
2575 // Emit the standard library with external linkage.
2576 llvm::GlobalVariable::LinkageTypes Linkage;
2577 if (IsStdLib)
2578 Linkage = llvm::GlobalValue::ExternalLinkage;
2579 else
2580 Linkage = getTypeInfoLinkage(CGM, Ty);
2581
2582 // Add the vtable pointer.
2583 BuildVTablePointer(cast<Type>(Ty));
2584
2585 // And the name.
2586 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2587 llvm::Constant *TypeNameField;
2588
2589 // If we're supposed to demote the visibility, be sure to set a flag
2590 // to use a string comparison for type_info comparisons.
2591 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2592 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2593 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2594 // The flag is the sign bit, which on ARM64 is defined to be clear
2595 // for global pointers. This is very ARM64-specific.
2596 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2597 llvm::Constant *flag =
2598 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2599 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2600 TypeNameField =
2601 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2602 } else {
2603 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2604 }
2605 Fields.push_back(TypeNameField);
2606
2607 switch (Ty->getTypeClass()) {
2608#define TYPE(Class, Base)
2609#define ABSTRACT_TYPE(Class, Base)
2610#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2611#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2612#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2613#include "clang/AST/TypeNodes.def"
2614 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2615
2616 // GCC treats vector types as fundamental types.
2617 case Type::Builtin:
2618 case Type::Vector:
2619 case Type::ExtVector:
2620 case Type::Complex:
2621 case Type::BlockPointer:
2622 // Itanium C++ ABI 2.9.5p4:
2623 // abi::__fundamental_type_info adds no data members to std::type_info.
2624 break;
2625
2626 case Type::LValueReference:
2627 case Type::RValueReference:
2628 llvm_unreachable("References shouldn't get here");
2629
2630 case Type::Auto:
2631 llvm_unreachable("Undeduced auto type shouldn't get here");
2632
2633 case Type::ConstantArray:
2634 case Type::IncompleteArray:
2635 case Type::VariableArray:
2636 // Itanium C++ ABI 2.9.5p5:
2637 // abi::__array_type_info adds no data members to std::type_info.
2638 break;
2639
2640 case Type::FunctionNoProto:
2641 case Type::FunctionProto:
2642 // Itanium C++ ABI 2.9.5p5:
2643 // abi::__function_type_info adds no data members to std::type_info.
2644 break;
2645
2646 case Type::Enum:
2647 // Itanium C++ ABI 2.9.5p5:
2648 // abi::__enum_type_info adds no data members to std::type_info.
2649 break;
2650
2651 case Type::Record: {
2652 const CXXRecordDecl *RD =
2653 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2654 if (!RD->hasDefinition() || !RD->getNumBases()) {
2655 // We don't need to emit any fields.
2656 break;
2657 }
2658
2659 if (CanUseSingleInheritance(RD))
2660 BuildSIClassTypeInfo(RD);
2661 else
2662 BuildVMIClassTypeInfo(RD);
2663
2664 break;
2665 }
2666
2667 case Type::ObjCObject:
2668 case Type::ObjCInterface:
2669 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2670 break;
2671
2672 case Type::ObjCObjectPointer:
2673 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2674 break;
2675
2676 case Type::Pointer:
2677 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2678 break;
2679
2680 case Type::MemberPointer:
2681 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2682 break;
2683
2684 case Type::Atomic:
2685 // No fields, at least for the moment.
2686 break;
2687 }
2688
2689 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2690
2691 llvm::GlobalVariable *GV =
2692 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2693 /*Constant=*/true, Linkage, Init, Name);
2694
2695 // If there's already an old global variable, replace it with the new one.
2696 if (OldGV) {
2697 GV->takeName(OldGV);
2698 llvm::Constant *NewPtr =
2699 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2700 OldGV->replaceAllUsesWith(NewPtr);
2701 OldGV->eraseFromParent();
2702 }
2703
2704 // The Itanium ABI specifies that type_info objects must be globally
2705 // unique, with one exception: if the type is an incomplete class
2706 // type or a (possibly indirect) pointer to one. That exception
2707 // affects the general case of comparing type_info objects produced
2708 // by the typeid operator, which is why the comparison operators on
2709 // std::type_info generally use the type_info name pointers instead
2710 // of the object addresses. However, the language's built-in uses
2711 // of RTTI generally require class types to be complete, even when
2712 // manipulating pointers to those class types. This allows the
2713 // implementation of dynamic_cast to rely on address equality tests,
2714 // which is much faster.
2715
2716 // All of this is to say that it's important that both the type_info
2717 // object and the type_info name be uniqued when weakly emitted.
2718
2719 // Give the type_info object and name the formal visibility of the
2720 // type itself.
2721 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2722 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2723 // If the linkage is local, only default visibility makes sense.
2724 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2725 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2726 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2727 else
2728 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2729 TypeName->setVisibility(llvmVisibility);
2730 GV->setVisibility(llvmVisibility);
2731
2732 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2733}
2734
2735/// ComputeQualifierFlags - Compute the pointer type info flags from the
2736/// given qualifier.
2737static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2738 unsigned Flags = 0;
2739
2740 if (Quals.hasConst())
2741 Flags |= ItaniumRTTIBuilder::PTI_Const;
2742 if (Quals.hasVolatile())
2743 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2744 if (Quals.hasRestrict())
2745 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2746
2747 return Flags;
2748}
2749
2750/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2751/// for the given Objective-C object type.
2752void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2753 // Drop qualifiers.
2754 const Type *T = OT->getBaseType().getTypePtr();
2755 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2756
2757 // The builtin types are abi::__class_type_infos and don't require
2758 // extra fields.
2759 if (isa<BuiltinType>(T)) return;
2760
2761 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2762 ObjCInterfaceDecl *Super = Class->getSuperClass();
2763
2764 // Root classes are also __class_type_info.
2765 if (!Super) return;
2766
2767 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2768
2769 // Everything else is single inheritance.
2770 llvm::Constant *BaseTypeInfo =
2771 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2772 Fields.push_back(BaseTypeInfo);
2773}
2774
2775/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2776/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2777void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2778 // Itanium C++ ABI 2.9.5p6b:
2779 // It adds to abi::__class_type_info a single member pointing to the
2780 // type_info structure for the base type,
2781 llvm::Constant *BaseTypeInfo =
2782 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2783 Fields.push_back(BaseTypeInfo);
2784}
2785
2786namespace {
2787 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2788 /// a class hierarchy.
2789 struct SeenBases {
2790 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2791 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2792 };
2793}
2794
2795/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2796/// abi::__vmi_class_type_info.
2797///
2798static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2799 SeenBases &Bases) {
2800
2801 unsigned Flags = 0;
2802
2803 const CXXRecordDecl *BaseDecl =
2804 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2805
2806 if (Base->isVirtual()) {
2807 // Mark the virtual base as seen.
2808 if (!Bases.VirtualBases.insert(BaseDecl)) {
2809 // If this virtual base has been seen before, then the class is diamond
2810 // shaped.
2811 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2812 } else {
2813 if (Bases.NonVirtualBases.count(BaseDecl))
2814 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2815 }
2816 } else {
2817 // Mark the non-virtual base as seen.
2818 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
2819 // If this non-virtual base has been seen before, then the class has non-
2820 // diamond shaped repeated inheritance.
2821 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2822 } else {
2823 if (Bases.VirtualBases.count(BaseDecl))
2824 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2825 }
2826 }
2827
2828 // Walk all bases.
2829 for (const auto &I : BaseDecl->bases())
2830 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2831
2832 return Flags;
2833}
2834
2835static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2836 unsigned Flags = 0;
2837 SeenBases Bases;
2838
2839 // Walk all bases.
2840 for (const auto &I : RD->bases())
2841 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2842
2843 return Flags;
2844}
2845
2846/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2847/// classes with bases that do not satisfy the abi::__si_class_type_info
2848/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2849void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2850 llvm::Type *UnsignedIntLTy =
2851 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2852
2853 // Itanium C++ ABI 2.9.5p6c:
2854 // __flags is a word with flags describing details about the class
2855 // structure, which may be referenced by using the __flags_masks
2856 // enumeration. These flags refer to both direct and indirect bases.
2857 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2858 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2859
2860 // Itanium C++ ABI 2.9.5p6c:
2861 // __base_count is a word with the number of direct proper base class
2862 // descriptions that follow.
2863 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2864
2865 if (!RD->getNumBases())
2866 return;
2867
2868 llvm::Type *LongLTy =
2869 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2870
2871 // Now add the base class descriptions.
2872
2873 // Itanium C++ ABI 2.9.5p6c:
2874 // __base_info[] is an array of base class descriptions -- one for every
2875 // direct proper base. Each description is of the type:
2876 //
2877 // struct abi::__base_class_type_info {
2878 // public:
2879 // const __class_type_info *__base_type;
2880 // long __offset_flags;
2881 //
2882 // enum __offset_flags_masks {
2883 // __virtual_mask = 0x1,
2884 // __public_mask = 0x2,
2885 // __offset_shift = 8
2886 // };
2887 // };
2888 for (const auto &Base : RD->bases()) {
2889 // The __base_type member points to the RTTI for the base type.
2890 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2891
2892 const CXXRecordDecl *BaseDecl =
2893 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2894
2895 int64_t OffsetFlags = 0;
2896
2897 // All but the lower 8 bits of __offset_flags are a signed offset.
2898 // For a non-virtual base, this is the offset in the object of the base
2899 // subobject. For a virtual base, this is the offset in the virtual table of
2900 // the virtual base offset for the virtual base referenced (negative).
2901 CharUnits Offset;
2902 if (Base.isVirtual())
2903 Offset =
2904 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2905 else {
2906 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2907 Offset = Layout.getBaseClassOffset(BaseDecl);
2908 };
2909
2910 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2911
2912 // The low-order byte of __offset_flags contains flags, as given by the
2913 // masks from the enumeration __offset_flags_masks.
2914 if (Base.isVirtual())
2915 OffsetFlags |= BCTI_Virtual;
2916 if (Base.getAccessSpecifier() == AS_public)
2917 OffsetFlags |= BCTI_Public;
2918
2919 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2920 }
2921}
2922
2923/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2924/// used for pointer types.
2925void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2926 Qualifiers Quals;
2927 QualType UnqualifiedPointeeTy =
2928 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2929
2930 // Itanium C++ ABI 2.9.5p7:
2931 // __flags is a flag word describing the cv-qualification and other
2932 // attributes of the type pointed to
2933 unsigned Flags = ComputeQualifierFlags(Quals);
2934
2935 // Itanium C++ ABI 2.9.5p7:
2936 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2937 // incomplete class type, the incomplete target type flag is set.
2938 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2939 Flags |= PTI_Incomplete;
2940
2941 llvm::Type *UnsignedIntLTy =
2942 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2943 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2944
2945 // Itanium C++ ABI 2.9.5p7:
2946 // __pointee is a pointer to the std::type_info derivation for the
2947 // unqualified type being pointed to.
2948 llvm::Constant *PointeeTypeInfo =
2949 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2950 Fields.push_back(PointeeTypeInfo);
2951}
2952
2953/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2954/// struct, used for member pointer types.
2955void
2956ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2957 QualType PointeeTy = Ty->getPointeeType();
2958
2959 Qualifiers Quals;
2960 QualType UnqualifiedPointeeTy =
2961 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2962
2963 // Itanium C++ ABI 2.9.5p7:
2964 // __flags is a flag word describing the cv-qualification and other
2965 // attributes of the type pointed to.
2966 unsigned Flags = ComputeQualifierFlags(Quals);
2967
2968 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
2969
2970 // Itanium C++ ABI 2.9.5p7:
2971 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
2972 // incomplete class type, the incomplete target type flag is set.
2973 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2974 Flags |= PTI_Incomplete;
2975
2976 if (IsIncompleteClassType(ClassType))
2977 Flags |= PTI_ContainingClassIncomplete;
2978
2979 llvm::Type *UnsignedIntLTy =
2980 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2981 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2982
2983 // Itanium C++ ABI 2.9.5p7:
2984 // __pointee is a pointer to the std::type_info derivation for the
2985 // unqualified type being pointed to.
2986 llvm::Constant *PointeeTypeInfo =
2987 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2988 Fields.push_back(PointeeTypeInfo);
2989
2990 // Itanium C++ ABI 2.9.5p9:
2991 // __context is a pointer to an abi::__class_type_info corresponding to the
2992 // class type containing the member pointed to
2993 // (e.g., the "A" in "int A::*").
2994 Fields.push_back(
2995 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
2996}
2997
2998llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
2999 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3000}
3001
3002void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3003 QualType PointerType = getContext().getPointerType(Type);
3004 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3005 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3006 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3007 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3008}
3009
3010void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3011 QualType FundamentalTypes[] = {
3012 getContext().VoidTy, getContext().NullPtrTy,
3013 getContext().BoolTy, getContext().WCharTy,
3014 getContext().CharTy, getContext().UnsignedCharTy,
3015 getContext().SignedCharTy, getContext().ShortTy,
3016 getContext().UnsignedShortTy, getContext().IntTy,
3017 getContext().UnsignedIntTy, getContext().LongTy,
3018 getContext().UnsignedLongTy, getContext().LongLongTy,
3019 getContext().UnsignedLongLongTy, getContext().HalfTy,
3020 getContext().FloatTy, getContext().DoubleTy,
3021 getContext().LongDoubleTy, getContext().Char16Ty,
3022 getContext().Char32Ty,
3023 };
3024 for (const QualType &FundamentalType : FundamentalTypes)
3025 EmitFundamentalRTTIDescriptor(FundamentalType);
3026}
3027
3028/// What sort of uniqueness rules should we use for the RTTI for the
3029/// given type?
3030ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3031 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3032 if (shouldRTTIBeUnique())
3033 return RUK_Unique;
3034
3035 // It's only necessary for linkonce_odr or weak_odr linkage.
3036 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3037 Linkage != llvm::GlobalValue::WeakODRLinkage)
3038 return RUK_Unique;
3039
3040 // It's only necessary with default visibility.
3041 if (CanTy->getVisibility() != DefaultVisibility)
3042 return RUK_Unique;
3043
3044 // If we're not required to publish this symbol, hide it.
3045 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3046 return RUK_NonUniqueHidden;
3047
3048 // If we're required to publish this symbol, as we might be under an
3049 // explicit instantiation, leave it with default visibility but
3050 // enable string-comparisons.
3051 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3052 return RUK_NonUniqueVisible;
3053}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003054
Rafael Espindola1e4df922014-09-16 15:18:21 +00003055// Find out how to codegen the complete destructor and constructor
3056namespace {
3057enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3058}
3059static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3060 const CXXMethodDecl *MD) {
3061 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3062 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003063
Rafael Espindola1e4df922014-09-16 15:18:21 +00003064 // The complete and base structors are not equivalent if there are any virtual
3065 // bases, so emit separate functions.
3066 if (MD->getParent()->getNumVBases())
3067 return StructorCodegen::Emit;
3068
3069 GlobalDecl AliasDecl;
3070 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3071 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3072 } else {
3073 const auto *CD = cast<CXXConstructorDecl>(MD);
3074 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3075 }
3076 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3077
3078 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3079 return StructorCodegen::RAUW;
3080
3081 // FIXME: Should we allow available_externally aliases?
3082 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3083 return StructorCodegen::RAUW;
3084
Rafael Espindola0806f982014-09-16 20:19:43 +00003085 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3086 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3087 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3088 return StructorCodegen::COMDAT;
3089 return StructorCodegen::Emit;
3090 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003091
3092 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003093}
3094
Rafael Espindola1e4df922014-09-16 15:18:21 +00003095static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3096 GlobalDecl AliasDecl,
3097 GlobalDecl TargetDecl) {
3098 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3099
3100 StringRef MangledName = CGM.getMangledName(AliasDecl);
3101 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3102 if (Entry && !Entry->isDeclaration())
3103 return;
3104
3105 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3106 llvm::PointerType *AliasType = Aliasee->getType();
3107
3108 // Create the alias with no name.
3109 auto *Alias = llvm::GlobalAlias::create(
3110 AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule());
3111
3112 // Switch any previous uses to the alias.
3113 if (Entry) {
3114 assert(Entry->getType() == AliasType &&
3115 "declaration exists with different type");
3116 Alias->takeName(Entry);
3117 Entry->replaceAllUsesWith(Alias);
3118 Entry->eraseFromParent();
3119 } else {
3120 Alias->setName(MangledName);
3121 }
3122
3123 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003124 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003125}
3126
3127void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3128 StructorType Type) {
3129 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3130 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3131
3132 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3133
3134 if (Type == StructorType::Complete) {
3135 GlobalDecl CompleteDecl;
3136 GlobalDecl BaseDecl;
3137 if (CD) {
3138 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3139 BaseDecl = GlobalDecl(CD, Ctor_Base);
3140 } else {
3141 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3142 BaseDecl = GlobalDecl(DD, Dtor_Base);
3143 }
3144
3145 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3146 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3147 return;
3148 }
3149
3150 if (CGType == StructorCodegen::RAUW) {
3151 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3152 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3153 CGM.addReplacement(MangledName, Aliasee);
3154 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003155 }
3156 }
3157
3158 // The base destructor is equivalent to the base destructor of its
3159 // base class if there is exactly one non-virtual base class with a
3160 // non-trivial destructor, there are no fields with a non-trivial
3161 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003162 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3163 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003164 return;
3165
Rafael Espindola1e4df922014-09-16 15:18:21 +00003166 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003167
Rafael Espindola1e4df922014-09-16 15:18:21 +00003168 if (CGType == StructorCodegen::COMDAT) {
3169 SmallString<256> Buffer;
3170 llvm::raw_svector_ostream Out(Buffer);
3171 if (DD)
3172 getMangleContext().mangleCXXDtorComdat(DD, Out);
3173 else
3174 getMangleContext().mangleCXXCtorComdat(CD, Out);
3175 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3176 Fn->setComdat(C);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003177 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003178}