blob: ca9322840eb15874c0201f508d584d7b9956d6b5 [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"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000022#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000023#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000024#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000025#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000026#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000027#include "TargetInfo.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000028#include "clang/AST/Mangle.h"
29#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000030#include "clang/AST/StmtCXX.h"
David Majnemer1162d252014-06-22 19:05:33 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000033#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000036
37using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000038using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000039
40namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000041class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000042 /// VTables - All the vtables which have been defined.
43 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
44
John McCall475999d2010-08-22 00:05:51 +000045protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000046 bool UseARMMethodPtrABI;
47 bool UseARMGuardVarABI;
John McCall7a9aac22010-08-23 01:21:21 +000048
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000049 ItaniumMangleContext &getMangleContext() {
50 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
51 }
52
Charles Davis4e786dd2010-05-25 19:52:27 +000053public:
Mark Seabornedf0d382013-07-24 16:25:13 +000054 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
55 bool UseARMMethodPtrABI = false,
56 bool UseARMGuardVarABI = false) :
57 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
58 UseARMGuardVarABI(UseARMGuardVarABI) { }
John McCall475999d2010-08-22 00:05:51 +000059
Reid Kleckner40ca9132014-05-13 22:05:45 +000060 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000061
Craig Topper4f12f102014-03-12 06:41:41 +000062 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000063 // Structures with either a non-trivial destructor or a non-trivial
64 // copy constructor are always indirect.
65 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
66 // special members.
67 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068 return RAA_Indirect;
69 return RAA_Default;
70 }
71
Craig Topper4f12f102014-03-12 06:41:41 +000072 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000073
Craig Topper4f12f102014-03-12 06:41:41 +000074 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +000075
Craig Topper4f12f102014-03-12 06:41:41 +000076 llvm::Value *
77 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
78 const Expr *E,
79 llvm::Value *&This,
80 llvm::Value *MemFnPtr,
81 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +000082
Craig Topper4f12f102014-03-12 06:41:41 +000083 llvm::Value *
84 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
85 llvm::Value *Base,
86 llvm::Value *MemPtr,
87 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +000088
John McCall7a9aac22010-08-23 01:21:21 +000089 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
90 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000091 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +000092 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +000093 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +000094
Craig Topper4f12f102014-03-12 06:41:41 +000095 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +000096
Craig Topper4f12f102014-03-12 06:41:41 +000097 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000098 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000099 CharUnits offset) override;
100 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000101 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
102 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000103
John McCall7a9aac22010-08-23 01:21:21 +0000104 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000105 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000106 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000107 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000108
John McCall7a9aac22010-08-23 01:21:21 +0000109 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000110 llvm::Value *Addr,
111 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000112
David Majnemer08681372014-11-01 07:37:17 +0000113 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000114 llvm::Value *Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000115 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000116
David Majnemer442d0a22014-11-25 07:20:20 +0000117 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000118 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000119
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000120 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
121
122 llvm::CallInst *
123 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
124 llvm::Value *Exn) override;
125
David Majnemere2cb8d12014-07-07 06:20:47 +0000126 void EmitFundamentalRTTIDescriptor(QualType Type);
127 void EmitFundamentalRTTIDescriptors();
David Majnemer443250f2015-03-17 20:35:00 +0000128 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
129 llvm::Constant *getAddrOfCXXCatchDescriptor(QualType Ty) {
130 return getAddrOfRTTIDescriptor(Ty);
131 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000132
David Majnemer1162d252014-06-22 19:05:33 +0000133 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
134 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
135 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
136 llvm::Value *ThisPtr,
137 llvm::Type *StdTypeInfoPtrTy) override;
138
139 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
140 QualType SrcRecordTy) override;
141
142 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
143 QualType SrcRecordTy, QualType DestTy,
144 QualType DestRecordTy,
145 llvm::BasicBlock *CastEnd) override;
146
147 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
148 QualType SrcRecordTy,
149 QualType DestTy) override;
150
151 bool EmitBadCastCall(CodeGenFunction &CGF) override;
152
Craig Topper4f12f102014-03-12 06:41:41 +0000153 llvm::Value *
154 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
155 const CXXRecordDecl *ClassDecl,
156 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000157
Craig Topper4f12f102014-03-12 06:41:41 +0000158 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000159
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000160 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
161 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000162
Reid Klecknere7de47e2013-07-22 13:51:44 +0000163 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000164 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000165 // Itanium does not emit any destructor variant as an inline thunk.
166 // Delegating may occur as an optimization, but all variants are either
167 // emitted with external linkage or as linkonce if they are inline and used.
168 return false;
169 }
170
Craig Topper4f12f102014-03-12 06:41:41 +0000171 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000172
Reid Kleckner89077a12013-12-17 19:46:40 +0000173 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000174 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000175
Craig Topper4f12f102014-03-12 06:41:41 +0000176 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000177
Reid Kleckner89077a12013-12-17 19:46:40 +0000178 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
179 const CXXConstructorDecl *D,
180 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000181 bool Delegating,
182 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000183
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000184 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
185 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000186 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000187
Craig Topper4f12f102014-03-12 06:41:41 +0000188 void emitVTableDefinitions(CodeGenVTables &CGVT,
189 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000190
191 llvm::Value *getVTableAddressPointInStructor(
192 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
193 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000194 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000195
196 llvm::Constant *
197 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000198 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000199
200 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000201 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000202
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000203 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000204 llvm::Value *This,
205 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000206
David Majnemer0c0b6d92014-10-31 20:09:12 +0000207 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
208 const CXXDestructorDecl *Dtor,
209 CXXDtorType DtorType,
210 llvm::Value *This,
211 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000212
Craig Topper4f12f102014-03-12 06:41:41 +0000213 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000214
Hans Wennborgc94391d2014-06-06 20:04:01 +0000215 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
216 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000217 // Allow inlining of thunks by emitting them with available_externally
218 // linkage together with vtables when needed.
219 if (ForVTable)
220 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
221 }
222
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000223 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000224 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000225
226 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000227 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000228
David Majnemer196ac332014-09-11 23:05:02 +0000229 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
230 FunctionArgList &Args) const override {
231 assert(!Args.empty() && "expected the arglist to not be empty!");
232 return Args.size() - 1;
233 }
234
Craig Topper4f12f102014-03-12 06:41:41 +0000235 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
236 StringRef GetDeletedVirtualCallName() override
237 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000238
Craig Topper4f12f102014-03-12 06:41:41 +0000239 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000240 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
241 llvm::Value *NewPtr,
242 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000243 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000244 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000245 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
246 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000247 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000248
John McCallcdf7ef52010-11-06 09:44:32 +0000249 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000250 llvm::GlobalVariable *DeclPtr,
251 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000252 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000253 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000254
255 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000256 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000257 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000258 CodeGenModule &CGM,
259 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
260 CXXThreadLocals,
261 ArrayRef<llvm::Function *> CXXThreadLocalInits,
262 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
263
264 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000265 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
266 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000267
Craig Topper4f12f102014-03-12 06:41:41 +0000268 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000269
270 /**************************** RTTI Uniqueness ******************************/
271
272protected:
273 /// Returns true if the ABI requires RTTI type_info objects to be unique
274 /// across a program.
275 virtual bool shouldRTTIBeUnique() const { return true; }
276
277public:
278 /// What sort of unique-RTTI behavior should we use?
279 enum RTTIUniquenessKind {
280 /// We are guaranteeing, or need to guarantee, that the RTTI string
281 /// is unique.
282 RUK_Unique,
283
284 /// We are not guaranteeing uniqueness for the RTTI string, so we
285 /// can demote to hidden visibility but must use string comparisons.
286 RUK_NonUniqueHidden,
287
288 /// We are not guaranteeing uniqueness for the RTTI string, so we
289 /// have to use string comparisons, but we also have to emit it with
290 /// non-hidden visibility.
291 RUK_NonUniqueVisible
292 };
293
294 /// Return the required visibility status for the given type and linkage in
295 /// the current ABI.
296 RTTIUniquenessKind
297 classifyRTTIUniqueness(QualType CanTy,
298 llvm::GlobalValue::LinkageTypes Linkage) const;
299 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000300
301 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000302};
John McCall86353412010-08-21 22:46:04 +0000303
304class ARMCXXABI : public ItaniumCXXABI {
305public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000306 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
307 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
308 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000309
Craig Topper4f12f102014-03-12 06:41:41 +0000310 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000311 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
312 isa<CXXDestructorDecl>(GD.getDecl()) &&
313 GD.getDtorType() != Dtor_Deleting));
314 }
John McCall5d865c322010-08-31 07:33:07 +0000315
Craig Topper4f12f102014-03-12 06:41:41 +0000316 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
317 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000318
Craig Topper4f12f102014-03-12 06:41:41 +0000319 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000320 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
321 llvm::Value *NewPtr,
322 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000323 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000324 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000325 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000326 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000327};
Tim Northovera2ee4332014-03-29 15:09:45 +0000328
329class iOS64CXXABI : public ARMCXXABI {
330public:
331 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000332
333 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000334 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000335};
Charles Davis4e786dd2010-05-25 19:52:27 +0000336}
337
Charles Davis53c59df2010-08-16 03:33:14 +0000338CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000339 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000340 // For IR-generation purposes, there's no significant difference
341 // between the ARM and iOS ABIs.
342 case TargetCXXABI::GenericARM:
343 case TargetCXXABI::iOS:
344 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000345
Tim Northovera2ee4332014-03-29 15:09:45 +0000346 case TargetCXXABI::iOS64:
347 return new iOS64CXXABI(CGM);
348
Tim Northover9bb857a2013-01-31 12:13:10 +0000349 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
350 // include the other 32-bit ARM oddities: constructor/destructor return values
351 // and array cookies.
352 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000353 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
354 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000355
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000356 case TargetCXXABI::GenericMIPS:
357 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
358
John McCall57625922013-01-25 23:36:14 +0000359 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000360 if (CGM.getContext().getTargetInfo().getTriple().getArch()
361 == llvm::Triple::le32) {
362 // For PNaCl, use ARM-style method pointers so that PNaCl code
363 // does not assume anything about the alignment of function
364 // pointers.
365 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
366 /* UseARMGuardVarABI = */ false);
367 }
John McCall57625922013-01-25 23:36:14 +0000368 return new ItaniumCXXABI(CGM);
369
370 case TargetCXXABI::Microsoft:
371 llvm_unreachable("Microsoft ABI is not Itanium-based");
372 }
373 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000374}
375
Chris Lattnera5f58b02011-07-09 17:41:47 +0000376llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000377ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
378 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000379 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000380 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000381}
382
John McCalld9c6c0b2010-08-22 00:59:17 +0000383/// In the Itanium and ARM ABIs, method pointers have the form:
384/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
385///
386/// In the Itanium ABI:
387/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
388/// - the this-adjustment is (memptr.adj)
389/// - the virtual offset is (memptr.ptr - 1)
390///
391/// In the ARM ABI:
392/// - method pointers are virtual if (memptr.adj & 1) is nonzero
393/// - the this-adjustment is (memptr.adj >> 1)
394/// - the virtual offset is (memptr.ptr)
395/// ARM uses 'adj' for the virtual flag because Thumb functions
396/// may be only single-byte aligned.
397///
398/// If the member is virtual, the adjusted 'this' pointer points
399/// to a vtable pointer from which the virtual offset is applied.
400///
401/// If the member is non-virtual, memptr.ptr is the address of
402/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000403llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
404 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
405 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000406 CGBuilderTy &Builder = CGF.Builder;
407
408 const FunctionProtoType *FPT =
409 MPT->getPointeeType()->getAs<FunctionProtoType>();
410 const CXXRecordDecl *RD =
411 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
412
Chris Lattner2192fe52011-07-18 04:24:23 +0000413 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000414 CGM.getTypes().GetFunctionType(
415 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000416
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000417 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000418
John McCalld9c6c0b2010-08-22 00:59:17 +0000419 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
420 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
421 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
422
John McCalla1dee5302010-08-22 10:59:02 +0000423 // Extract memptr.adj, which is in the second field.
424 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000425
426 // Compute the true adjustment.
427 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000428 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000429 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000430
431 // Apply the adjustment and cast back to the original struct type
432 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000433 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
434 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
435 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000436
437 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000438 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000439
440 // If the LSB in the function pointer is 1, the function pointer points to
441 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000442 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000443 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000444 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
445 else
446 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
447 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000448 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
449
450 // In the virtual path, the adjustment left 'This' pointing to the
451 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000452 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000453 CGF.EmitBlock(FnVirtual);
454
455 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000456 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000457 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000458
459 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000460 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000461 if (!UseARMMethodPtrABI)
462 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000463 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000464
465 // Load the virtual function to call.
466 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000467 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000468 CGF.EmitBranch(FnEnd);
469
470 // In the non-virtual path, the function pointer is actually a
471 // function pointer.
472 CGF.EmitBlock(FnNonVirtual);
473 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000474 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000475
476 // We're done.
477 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000478 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000479 Callee->addIncoming(VirtualFn, FnVirtual);
480 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
481 return Callee;
482}
John McCalla8bbb822010-08-22 03:04:22 +0000483
John McCallc134eb52010-08-31 21:07:20 +0000484/// Compute an l-value by applying the given pointer-to-member to a
485/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000486llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
487 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
488 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000489 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000490
491 CGBuilderTy &Builder = CGF.Builder;
492
Micah Villmowea2fea22012-10-25 15:39:14 +0000493 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000494
495 // Cast to char*.
496 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
497
498 // Apply the offset, which we assume is non-null.
499 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
500
501 // Cast the address to the appropriate pointer type, adopting the
502 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000503 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000504 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000505 return Builder.CreateBitCast(Addr, PType);
506}
507
John McCallc62bb392012-02-15 01:22:51 +0000508/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
509/// conversion.
510///
511/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000512///
513/// Obligatory offset/adjustment diagram:
514/// <-- offset --> <-- adjustment -->
515/// |--------------------------|----------------------|--------------------|
516/// ^Derived address point ^Base address point ^Member address point
517///
518/// So when converting a base member pointer to a derived member pointer,
519/// we add the offset to the adjustment because the address point has
520/// decreased; and conversely, when converting a derived MP to a base MP
521/// we subtract the offset from the adjustment because the address point
522/// has increased.
523///
524/// The standard forbids (at compile time) conversion to and from
525/// virtual bases, which is why we don't have to consider them here.
526///
527/// The standard forbids (at run time) casting a derived MP to a base
528/// MP when the derived MP does not point to a member of the base.
529/// This is why -1 is a reasonable choice for null data member
530/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000531llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000532ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
533 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000534 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000535 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000536 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
537 E->getCastKind() == CK_ReinterpretMemberPointer);
538
539 // Under Itanium, reinterprets don't require any additional processing.
540 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
541
542 // Use constant emission if we can.
543 if (isa<llvm::Constant>(src))
544 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
545
546 llvm::Constant *adj = getMemberPointerAdjustment(E);
547 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000548
549 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000550 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000551
John McCallc62bb392012-02-15 01:22:51 +0000552 const MemberPointerType *destTy =
553 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000554
John McCall7a9aac22010-08-23 01:21:21 +0000555 // For member data pointers, this is just a matter of adding the
556 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000557 if (destTy->isMemberDataPointer()) {
558 llvm::Value *dst;
559 if (isDerivedToBase)
560 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000561 else
John McCallc62bb392012-02-15 01:22:51 +0000562 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000563
564 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000565 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
566 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
567 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000568 }
569
John McCalla1dee5302010-08-22 10:59:02 +0000570 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000571 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000572 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
573 offset <<= 1;
574 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000575 }
576
John McCallc62bb392012-02-15 01:22:51 +0000577 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
578 llvm::Value *dstAdj;
579 if (isDerivedToBase)
580 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000581 else
John McCallc62bb392012-02-15 01:22:51 +0000582 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000583
John McCallc62bb392012-02-15 01:22:51 +0000584 return Builder.CreateInsertValue(src, dstAdj, 1);
585}
586
587llvm::Constant *
588ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
589 llvm::Constant *src) {
590 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
591 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
592 E->getCastKind() == CK_ReinterpretMemberPointer);
593
594 // Under Itanium, reinterprets don't require any additional processing.
595 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
596
597 // If the adjustment is trivial, we don't need to do anything.
598 llvm::Constant *adj = getMemberPointerAdjustment(E);
599 if (!adj) return src;
600
601 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
602
603 const MemberPointerType *destTy =
604 E->getType()->castAs<MemberPointerType>();
605
606 // For member data pointers, this is just a matter of adding the
607 // offset if the source is non-null.
608 if (destTy->isMemberDataPointer()) {
609 // null maps to null.
610 if (src->isAllOnesValue()) return src;
611
612 if (isDerivedToBase)
613 return llvm::ConstantExpr::getNSWSub(src, adj);
614 else
615 return llvm::ConstantExpr::getNSWAdd(src, adj);
616 }
617
618 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000619 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000620 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
621 offset <<= 1;
622 adj = llvm::ConstantInt::get(adj->getType(), offset);
623 }
624
625 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
626 llvm::Constant *dstAdj;
627 if (isDerivedToBase)
628 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
629 else
630 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
631
632 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000633}
John McCall84fa5102010-08-22 04:16:24 +0000634
635llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000636ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000637 // Itanium C++ ABI 2.3:
638 // A NULL pointer is represented as -1.
639 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000640 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000641
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000642 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000643 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000644 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000645}
646
John McCallf3a88602011-02-03 08:15:49 +0000647llvm::Constant *
648ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
649 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000650 // Itanium C++ ABI 2.3:
651 // A pointer to data member is an offset from the base address of
652 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000653 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000654}
655
John McCall2979fe02011-04-12 00:42:48 +0000656llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000657 return BuildMemberPointer(MD, CharUnits::Zero());
658}
659
660llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
661 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000662 assert(MD->isInstance() && "Member function must not be static!");
663 MD = MD->getCanonicalDecl();
664
665 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000666
667 // Get the function pointer (or index if this is a virtual function).
668 llvm::Constant *MemPtr[2];
669 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000670 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000671
Ken Dyckdf016282011-04-09 01:30:02 +0000672 const ASTContext &Context = getContext();
673 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000674 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000675 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000676
Mark Seabornedf0d382013-07-24 16:25:13 +0000677 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000678 // ARM C++ ABI 3.2.1:
679 // This ABI specifies that adj contains twice the this
680 // adjustment, plus 1 if the member function is virtual. The
681 // least significant bit of adj then makes exactly the same
682 // discrimination as the least significant bit of ptr does for
683 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000684 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
685 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000686 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000687 } else {
688 // Itanium C++ ABI 2.3:
689 // For a virtual function, [the pointer field] is 1 plus the
690 // virtual table offset (in bytes) of the function,
691 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000692 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
693 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000694 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000695 }
696 } else {
John McCall2979fe02011-04-12 00:42:48 +0000697 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000698 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000699 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000700 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000701 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000702 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000703 } else {
John McCall2979fe02011-04-12 00:42:48 +0000704 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
705 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000706 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000707 }
John McCall2979fe02011-04-12 00:42:48 +0000708 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000709
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000710 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000711 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
712 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000713 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000714 }
John McCall1c456c82010-08-22 06:43:33 +0000715
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000716 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000717}
718
Richard Smithdafff942012-01-14 04:30:29 +0000719llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
720 QualType MPType) {
721 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
722 const ValueDecl *MPD = MP.getMemberPointerDecl();
723 if (!MPD)
724 return EmitNullMemberPointer(MPT);
725
Reid Kleckner452abac2013-05-09 21:01:17 +0000726 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000727
728 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
729 return BuildMemberPointer(MD, ThisAdjustment);
730
731 CharUnits FieldOffset =
732 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
733 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
734}
735
John McCall131d97d2010-08-22 08:30:07 +0000736/// The comparison algorithm is pretty easy: the member pointers are
737/// the same if they're either bitwise identical *or* both null.
738///
739/// ARM is different here only because null-ness is more complicated.
740llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000741ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
742 llvm::Value *L,
743 llvm::Value *R,
744 const MemberPointerType *MPT,
745 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000746 CGBuilderTy &Builder = CGF.Builder;
747
John McCall131d97d2010-08-22 08:30:07 +0000748 llvm::ICmpInst::Predicate Eq;
749 llvm::Instruction::BinaryOps And, Or;
750 if (Inequality) {
751 Eq = llvm::ICmpInst::ICMP_NE;
752 And = llvm::Instruction::Or;
753 Or = llvm::Instruction::And;
754 } else {
755 Eq = llvm::ICmpInst::ICMP_EQ;
756 And = llvm::Instruction::And;
757 Or = llvm::Instruction::Or;
758 }
759
John McCall7a9aac22010-08-23 01:21:21 +0000760 // Member data pointers are easy because there's a unique null
761 // value, so it just comes down to bitwise equality.
762 if (MPT->isMemberDataPointer())
763 return Builder.CreateICmp(Eq, L, R);
764
765 // For member function pointers, the tautologies are more complex.
766 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000767 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000768 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000769 // (L == R) <==> (L.ptr == R.ptr &&
770 // (L.adj == R.adj ||
771 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000772 // The inequality tautologies have exactly the same structure, except
773 // applying De Morgan's laws.
774
775 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
776 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
777
John McCall131d97d2010-08-22 08:30:07 +0000778 // This condition tests whether L.ptr == R.ptr. This must always be
779 // true for equality to hold.
780 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
781
782 // This condition, together with the assumption that L.ptr == R.ptr,
783 // tests whether the pointers are both null. ARM imposes an extra
784 // condition.
785 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
786 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
787
788 // This condition tests whether L.adj == R.adj. If this isn't
789 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000790 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
791 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000792 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
793
794 // Null member function pointers on ARM clear the low bit of Adj,
795 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000796 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000797 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
798
799 // Compute (l.adj | r.adj) & 1 and test it against zero.
800 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
801 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
802 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
803 "cmp.or.adj");
804 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
805 }
806
807 // Tie together all our conditions.
808 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
809 Result = Builder.CreateBinOp(And, PtrEq, Result,
810 Inequality ? "memptr.ne" : "memptr.eq");
811 return Result;
812}
813
814llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000815ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
816 llvm::Value *MemPtr,
817 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000818 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000819
820 /// For member data pointers, this is just a check against -1.
821 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000822 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000823 llvm::Value *NegativeOne =
824 llvm::Constant::getAllOnesValue(MemPtr->getType());
825 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
826 }
John McCall131d97d2010-08-22 08:30:07 +0000827
Daniel Dunbar914bc412011-04-19 23:10:47 +0000828 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000829 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000830
831 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
832 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
833
Daniel Dunbar914bc412011-04-19 23:10:47 +0000834 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
835 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000836 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000837 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000838 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000839 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000840 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
841 "memptr.isvirtual");
842 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000843 }
844
845 return Result;
846}
John McCall1c456c82010-08-22 06:43:33 +0000847
Reid Kleckner40ca9132014-05-13 22:05:45 +0000848bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
849 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
850 if (!RD)
851 return false;
852
Reid Klecknerd355ca72014-05-15 01:26:32 +0000853 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
854 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
855 // special members.
856 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000857 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
858 return true;
859 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000860 return false;
861}
862
John McCall614dbdc2010-08-22 21:01:12 +0000863/// The Itanium ABI requires non-zero initialization only for data
864/// member pointers, for which '0' is a valid offset.
865bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
866 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000867}
John McCall5d865c322010-08-31 07:33:07 +0000868
John McCall82fb8922012-09-25 10:10:39 +0000869/// The Itanium ABI always places an offset to the complete object
870/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000871void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
872 const CXXDeleteExpr *DE,
873 llvm::Value *Ptr,
874 QualType ElementType,
875 const CXXDestructorDecl *Dtor) {
876 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000877 if (UseGlobalDelete) {
878 // Derive the complete-object pointer, which is what we need
879 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000880
David Majnemer0c0b6d92014-10-31 20:09:12 +0000881 // Grab the vtable pointer as an intptr_t*.
882 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000883
David Majnemer0c0b6d92014-10-31 20:09:12 +0000884 // Track back to entry -2 and pull out the offset there.
885 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
886 VTable, -2, "complete-offset.ptr");
887 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
888 Offset->setAlignment(CGF.PointerAlignInBytes);
889
890 // Apply the offset.
891 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
892 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
893
894 // If we're supposed to call the global delete, make sure we do so
895 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000896 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
897 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000898 }
899
900 // FIXME: Provide a source location here even though there's no
901 // CXXMemberCallExpr for dtor call.
902 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
903 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
904
905 if (UseGlobalDelete)
906 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000907}
908
David Majnemer442d0a22014-11-25 07:20:20 +0000909void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
910 // void __cxa_rethrow();
911
912 llvm::FunctionType *FTy =
913 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
914
915 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
916
917 if (isNoReturn)
918 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
919 else
920 CGF.EmitRuntimeCallOrInvoke(Fn);
921}
922
David Majnemer7c237072015-03-05 00:46:22 +0000923static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
924 // void *__cxa_allocate_exception(size_t thrown_size);
925
926 llvm::FunctionType *FTy =
927 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
928
929 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
930}
931
932static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
933 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
934 // void (*dest) (void *));
935
936 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
937 llvm::FunctionType *FTy =
938 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
939
940 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
941}
942
943void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
944 QualType ThrowType = E->getSubExpr()->getType();
945 // Now allocate the exception object.
946 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
947 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
948
949 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
950 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
951 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
952
953 CGF.EmitAnyExprToExn(E->getSubExpr(), ExceptionPtr);
954
955 // Now throw the exception.
956 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
957 /*ForEH=*/true);
958
959 // The address of the destructor. If the exception type has a
960 // trivial destructor (or isn't a record), we just pass null.
961 llvm::Constant *Dtor = nullptr;
962 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
963 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
964 if (!Record->hasTrivialDestructor()) {
965 CXXDestructorDecl *DtorD = Record->getDestructor();
966 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
967 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
968 }
969 }
970 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
971
972 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
973 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
974}
975
David Majnemer1162d252014-06-22 19:05:33 +0000976static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
977 // void *__dynamic_cast(const void *sub,
978 // const abi::__class_type_info *src,
979 // const abi::__class_type_info *dst,
980 // std::ptrdiff_t src2dst_offset);
981
982 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
983 llvm::Type *PtrDiffTy =
984 CGF.ConvertType(CGF.getContext().getPointerDiffType());
985
986 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
987
988 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
989
990 // Mark the function as nounwind readonly.
991 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
992 llvm::Attribute::ReadOnly };
993 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
994 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
995
996 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
997}
998
999static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1000 // void __cxa_bad_cast();
1001 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1002 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1003}
1004
1005/// \brief Compute the src2dst_offset hint as described in the
1006/// Itanium C++ ABI [2.9.7]
1007static CharUnits computeOffsetHint(ASTContext &Context,
1008 const CXXRecordDecl *Src,
1009 const CXXRecordDecl *Dst) {
1010 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1011 /*DetectVirtual=*/false);
1012
1013 // If Dst is not derived from Src we can skip the whole computation below and
1014 // return that Src is not a public base of Dst. Record all inheritance paths.
1015 if (!Dst->isDerivedFrom(Src, Paths))
1016 return CharUnits::fromQuantity(-2ULL);
1017
1018 unsigned NumPublicPaths = 0;
1019 CharUnits Offset;
1020
1021 // Now walk all possible inheritance paths.
1022 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
1023 ++I) {
1024 if (I->Access != AS_public) // Ignore non-public inheritance.
1025 continue;
1026
1027 ++NumPublicPaths;
1028
1029 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
1030 // If the path contains a virtual base class we can't give any hint.
1031 // -1: no hint.
1032 if (J->Base->isVirtual())
1033 return CharUnits::fromQuantity(-1ULL);
1034
1035 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1036 continue;
1037
1038 // Accumulate the base class offsets.
1039 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
1040 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
1041 }
1042 }
1043
1044 // -2: Src is not a public base of Dst.
1045 if (NumPublicPaths == 0)
1046 return CharUnits::fromQuantity(-2ULL);
1047
1048 // -3: Src is a multiple public base type but never a virtual base type.
1049 if (NumPublicPaths > 1)
1050 return CharUnits::fromQuantity(-3ULL);
1051
1052 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1053 // Return the offset of Src from the origin of Dst.
1054 return Offset;
1055}
1056
1057static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1058 // void __cxa_bad_typeid();
1059 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1060
1061 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1062}
1063
1064bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1065 QualType SrcRecordTy) {
1066 return IsDeref;
1067}
1068
1069void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1070 llvm::Value *Fn = getBadTypeidFn(CGF);
1071 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1072 CGF.Builder.CreateUnreachable();
1073}
1074
1075llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1076 QualType SrcRecordTy,
1077 llvm::Value *ThisPtr,
1078 llvm::Type *StdTypeInfoPtrTy) {
1079 llvm::Value *Value =
1080 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1081
1082 // Load the type info.
1083 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1084 return CGF.Builder.CreateLoad(Value);
1085}
1086
1087bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1088 QualType SrcRecordTy) {
1089 return SrcIsPtr;
1090}
1091
1092llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1093 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1094 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1095 llvm::Type *PtrDiffLTy =
1096 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1097 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1098
1099 llvm::Value *SrcRTTI =
1100 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1101 llvm::Value *DestRTTI =
1102 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1103
1104 // Compute the offset hint.
1105 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1106 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1107 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1108 PtrDiffLTy,
1109 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1110
1111 // Emit the call to __dynamic_cast.
1112 Value = CGF.EmitCastToVoidPtr(Value);
1113
1114 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1115 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1116 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1117
1118 /// C++ [expr.dynamic.cast]p9:
1119 /// A failed cast to reference type throws std::bad_cast
1120 if (DestTy->isReferenceType()) {
1121 llvm::BasicBlock *BadCastBlock =
1122 CGF.createBasicBlock("dynamic_cast.bad_cast");
1123
1124 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1125 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1126
1127 CGF.EmitBlock(BadCastBlock);
1128 EmitBadCastCall(CGF);
1129 }
1130
1131 return Value;
1132}
1133
1134llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1135 llvm::Value *Value,
1136 QualType SrcRecordTy,
1137 QualType DestTy) {
1138 llvm::Type *PtrDiffLTy =
1139 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1140 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1141
1142 // Get the vtable pointer.
1143 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1144
1145 // Get the offset-to-top from the vtable.
1146 llvm::Value *OffsetToTop =
1147 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1148 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1149
1150 // Finally, add the offset to the pointer.
1151 Value = CGF.EmitCastToVoidPtr(Value);
1152 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1153
1154 return CGF.Builder.CreateBitCast(Value, DestLTy);
1155}
1156
1157bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1158 llvm::Value *Fn = getBadCastFn(CGF);
1159 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1160 CGF.Builder.CreateUnreachable();
1161 return true;
1162}
1163
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001164llvm::Value *
1165ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1166 llvm::Value *This,
1167 const CXXRecordDecl *ClassDecl,
1168 const CXXRecordDecl *BaseClassDecl) {
1169 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1170 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001171 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1172 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001173
1174 llvm::Value *VBaseOffsetPtr =
1175 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1176 "vbase.offset.ptr");
1177 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1178 CGM.PtrDiffTy->getPointerTo());
1179
1180 llvm::Value *VBaseOffset =
1181 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1182
1183 return VBaseOffset;
1184}
1185
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001186void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1187 // Just make sure we're in sync with TargetCXXABI.
1188 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1189
Rafael Espindolac3cde362013-12-09 14:51:17 +00001190 // The constructor used for constructing this as a base class;
1191 // ignores virtual bases.
1192 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1193
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001194 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001195 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001196 if (!D->getParent()->isAbstract()) {
1197 // We don't need to emit the complete ctor if the class is abstract.
1198 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1199 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001200}
1201
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001202void
1203ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1204 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001205 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001206
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001207 // All parameters are already in place except VTT, which goes after 'this'.
1208 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001209
1210 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001211 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1212 ArgTys.insert(ArgTys.begin() + 1,
1213 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001214}
1215
Reid Klecknere7de47e2013-07-22 13:51:44 +00001216void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001217 // The destructor used for destructing this as a base class; ignores
1218 // virtual bases.
1219 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001220
1221 // The destructor used for destructing this as a most-derived class;
1222 // call the base destructor and then destructs any virtual bases.
1223 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1224
Rafael Espindolac3cde362013-12-09 14:51:17 +00001225 // The destructor in a virtual table is always a 'deleting'
1226 // destructor, which calls the complete destructor and then uses the
1227 // appropriate operator delete.
1228 if (D->isVirtual())
1229 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001230}
1231
Reid Kleckner89077a12013-12-17 19:46:40 +00001232void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1233 QualType &ResTy,
1234 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001235 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001236 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001237
1238 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001239 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001240 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001241
1242 // FIXME: avoid the fake decl
1243 QualType T = Context.getPointerType(Context.VoidPtrTy);
1244 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001245 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001246 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001247 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001248 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001249 }
1250}
1251
John McCall5d865c322010-08-31 07:33:07 +00001252void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1253 /// Initialize the 'this' slot.
1254 EmitThisParam(CGF);
1255
1256 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001257 if (getStructorImplicitParamDecl(CGF)) {
1258 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1259 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001260 }
John McCall5d865c322010-08-31 07:33:07 +00001261
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001262 /// If this is a function that the ABI specifies returns 'this', initialize
1263 /// the return slot to 'this' at the start of the function.
1264 ///
1265 /// Unlike the setting of return types, this is done within the ABI
1266 /// implementation instead of by clients of CGCXXABI because:
1267 /// 1) getThisValue is currently protected
1268 /// 2) in theory, an ABI could implement 'this' returns some other way;
1269 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001270 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001271 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001272}
1273
Reid Kleckner89077a12013-12-17 19:46:40 +00001274unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1275 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1276 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1277 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1278 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001279
Reid Kleckner89077a12013-12-17 19:46:40 +00001280 // Insert the implicit 'vtt' argument as the second argument.
1281 llvm::Value *VTT =
1282 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1283 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1284 Args.insert(Args.begin() + 1,
1285 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1286 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001287}
1288
1289void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1290 const CXXDestructorDecl *DD,
1291 CXXDtorType Type, bool ForVirtualBase,
1292 bool Delegating, llvm::Value *This) {
1293 GlobalDecl GD(DD, Type);
1294 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1295 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1296
Craig Topper8a13c412014-05-21 05:09:00 +00001297 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001298 if (getContext().getLangOpts().AppleKext)
1299 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1300
1301 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001302 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001303
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001304 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1305 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001306}
1307
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001308void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1309 const CXXRecordDecl *RD) {
1310 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1311 if (VTable->hasInitializer())
1312 return;
1313
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001314 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001315 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1316 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001317 llvm::Constant *RTTI =
1318 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001319
1320 // Create and set the initializer.
1321 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1322 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001323 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001324 VTable->setInitializer(Init);
1325
1326 // Set the correct linkage.
1327 VTable->setLinkage(Linkage);
1328
Rafael Espindolacb92c192015-01-15 23:18:01 +00001329 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1330 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
1331
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001332 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001333 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001334
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001335 // Use pointer alignment for the vtable. Otherwise we would align them based
1336 // on the size of the initializer which doesn't make sense as only single
1337 // values are read.
1338 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1339 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1340
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001341 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1342 // we will emit the typeinfo for the fundamental types. This is the
1343 // same behaviour as GCC.
1344 const DeclContext *DC = RD->getDeclContext();
1345 if (RD->getIdentifier() &&
1346 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1347 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1348 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1349 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001350 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001351
1352 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001353}
1354
1355llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1356 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1357 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1358 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1359 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1360
1361 llvm::Value *VTableAddressPoint;
1362 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1363 // Get the secondary vpointer index.
1364 uint64_t VirtualPointerIndex =
1365 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1366
1367 /// Load the VTT.
1368 llvm::Value *VTT = CGF.LoadCXXVTT();
1369 if (VirtualPointerIndex)
1370 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1371
1372 // And load the address point from the VTT.
1373 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1374 } else {
1375 llvm::Constant *VTable =
1376 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001377 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1378 .getVTableLayout(VTableClass)
1379 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001380 VTableAddressPoint =
1381 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1382 }
1383
1384 return VTableAddressPoint;
1385}
1386
1387llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1388 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1389 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1390
1391 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001392 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1393 .getVTableLayout(VTableClass)
1394 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001395 llvm::Value *Indices[] = {
1396 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1397 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1398 };
1399
1400 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1401}
1402
1403llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1404 CharUnits VPtrOffset) {
1405 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1406
1407 llvm::GlobalVariable *&VTable = VTables[RD];
1408 if (VTable)
1409 return VTable;
1410
1411 // Queue up this v-table for possible deferred emission.
1412 CGM.addDeferredVTable(RD);
1413
1414 SmallString<256> OutName;
1415 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001416 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001417 Out.flush();
1418 StringRef Name = OutName.str();
1419
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001420 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001421 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1422 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1423
1424 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1425 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1426 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001427
1428 if (RD->hasAttr<DLLImportAttr>())
1429 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1430 else if (RD->hasAttr<DLLExportAttr>())
1431 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1432
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001433 return VTable;
1434}
1435
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001436llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1437 GlobalDecl GD,
1438 llvm::Value *This,
1439 llvm::Type *Ty) {
1440 GD = GD.getCanonicalDecl();
1441 Ty = Ty->getPointerTo()->getPointerTo();
1442 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1443
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001444 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable);
1445
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001446 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001447 llvm::Value *VFuncPtr =
1448 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1449 return CGF.Builder.CreateLoad(VFuncPtr);
1450}
1451
David Majnemer0c0b6d92014-10-31 20:09:12 +00001452llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1453 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1454 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001455 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001456 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1457
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001458 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1459 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001460 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001461 llvm::Value *Callee =
1462 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001463
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001464 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1465 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001466 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001467}
1468
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001469void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001470 CodeGenVTables &VTables = CGM.getVTables();
1471 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001472 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001473}
1474
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001475static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1476 llvm::Value *Ptr,
1477 int64_t NonVirtualAdjustment,
1478 int64_t VirtualAdjustment,
1479 bool IsReturnAdjustment) {
1480 if (!NonVirtualAdjustment && !VirtualAdjustment)
1481 return Ptr;
1482
1483 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1484 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1485
1486 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1487 // Perform the non-virtual adjustment for a base-to-derived cast.
1488 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1489 }
1490
1491 if (VirtualAdjustment) {
1492 llvm::Type *PtrDiffTy =
1493 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1494
1495 // Perform the virtual adjustment.
1496 llvm::Value *VTablePtrPtr =
1497 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1498
1499 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1500
1501 llvm::Value *OffsetPtr =
1502 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1503
1504 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1505
1506 // Load the adjustment offset from the vtable.
1507 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1508
1509 // Adjust our pointer.
1510 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1511 }
1512
1513 if (NonVirtualAdjustment && IsReturnAdjustment) {
1514 // Perform the non-virtual adjustment for a derived-to-base cast.
1515 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1516 }
1517
1518 // Cast back to the original type.
1519 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1520}
1521
1522llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1523 llvm::Value *This,
1524 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001525 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1526 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001527 /*IsReturnAdjustment=*/false);
1528}
1529
1530llvm::Value *
1531ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1532 const ReturnAdjustment &RA) {
1533 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1534 RA.Virtual.Itanium.VBaseOffsetOffset,
1535 /*IsReturnAdjustment=*/true);
1536}
1537
John McCall5d865c322010-08-31 07:33:07 +00001538void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1539 RValue RV, QualType ResultType) {
1540 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1541 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1542
1543 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001544 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001545 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1546 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1547 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1548}
John McCall8ed55a52010-09-02 09:58:18 +00001549
1550/************************** Array allocation cookies **************************/
1551
John McCallb91cd662012-05-01 05:23:51 +00001552CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1553 // The array cookie is a size_t; pad that up to the element alignment.
1554 // The cookie is actually right-justified in that space.
1555 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1556 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001557}
1558
1559llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1560 llvm::Value *NewPtr,
1561 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001562 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001563 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001564 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001565
Micah Villmowea2fea22012-10-25 15:39:14 +00001566 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001567
John McCall9bca9232010-09-02 10:25:57 +00001568 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001569 QualType SizeTy = Ctx.getSizeType();
1570 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1571
1572 // The size of the cookie.
1573 CharUnits CookieSize =
1574 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001575 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001576
1577 // Compute an offset to the cookie.
1578 llvm::Value *CookiePtr = NewPtr;
1579 CharUnits CookieOffset = CookieSize - SizeSize;
1580 if (!CookieOffset.isZero())
1581 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1582 CookieOffset.getQuantity());
1583
1584 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001585 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1586 llvm::Value *NumElementsPtr =
1587 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1588 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001589 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001590 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001591 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001592 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1593 llvm::FunctionType *FTy =
1594 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1595 llvm::Constant *F =
1596 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1597 CGF.Builder.CreateCall(F, NumElementsPtr);
1598 }
John McCall8ed55a52010-09-02 09:58:18 +00001599
1600 // Finally, compute a pointer to the actual data buffer by skipping
1601 // over the cookie completely.
1602 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1603 CookieSize.getQuantity());
1604}
1605
John McCallb91cd662012-05-01 05:23:51 +00001606llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1607 llvm::Value *allocPtr,
1608 CharUnits cookieSize) {
1609 // The element size is right-justified in the cookie.
1610 llvm::Value *numElementsPtr = allocPtr;
1611 CharUnits numElementsOffset =
1612 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1613 if (!numElementsOffset.isZero())
1614 numElementsPtr =
1615 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1616 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001617
Micah Villmowea2fea22012-10-25 15:39:14 +00001618 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001619 numElementsPtr =
1620 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001621 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001622 return CGF.Builder.CreateLoad(numElementsPtr);
1623 // In asan mode emit a function call instead of a regular load and let the
1624 // run-time deal with it: if the shadow is properly poisoned return the
1625 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1626 // We can't simply ignore this load using nosanitize metadata because
1627 // the metadata may be lost.
1628 llvm::FunctionType *FTy =
1629 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1630 llvm::Constant *F =
1631 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1632 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001633}
1634
John McCallb91cd662012-05-01 05:23:51 +00001635CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001636 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001637 // struct array_cookie {
1638 // std::size_t element_size; // element_size != 0
1639 // std::size_t element_count;
1640 // };
John McCallc19c7062013-01-25 23:36:19 +00001641 // But the base ABI doesn't give anything an alignment greater than
1642 // 8, so we can dismiss this as typical ABI-author blindness to
1643 // actual language complexity and round up to the element alignment.
1644 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1645 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001646}
1647
1648llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001649 llvm::Value *newPtr,
1650 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001651 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001652 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001653 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001654
John McCallc19c7062013-01-25 23:36:19 +00001655 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1656 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001657
1658 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001659 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001660
1661 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001662 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1663 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1664 getContext().getTypeSizeInChars(elementType).getQuantity());
1665 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001666
1667 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001668 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1669 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001670
1671 // Finally, compute a pointer to the actual data buffer by skipping
1672 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001673 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1674 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1675 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001676}
1677
John McCallb91cd662012-05-01 05:23:51 +00001678llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1679 llvm::Value *allocPtr,
1680 CharUnits cookieSize) {
1681 // The number of elements is at offset sizeof(size_t) relative to
1682 // the allocated pointer.
1683 llvm::Value *numElementsPtr
1684 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001685
Micah Villmowea2fea22012-10-25 15:39:14 +00001686 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001687 numElementsPtr =
1688 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1689 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001690}
1691
John McCall68ff0372010-09-08 01:44:27 +00001692/*********************** Static local initialization **************************/
1693
1694static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001695 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001696 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001697 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001698 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001699 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001700 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001701 llvm::AttributeSet::get(CGM.getLLVMContext(),
1702 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001703 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001704}
1705
1706static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001707 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001708 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001709 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001710 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001711 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001712 llvm::AttributeSet::get(CGM.getLLVMContext(),
1713 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001714 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001715}
1716
1717static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001718 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001719 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001720 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001721 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001722 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001723 llvm::AttributeSet::get(CGM.getLLVMContext(),
1724 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001725 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001726}
1727
1728namespace {
1729 struct CallGuardAbort : EHScopeStack::Cleanup {
1730 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001731 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001732
Craig Topper4f12f102014-03-12 06:41:41 +00001733 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001734 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1735 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001736 }
1737 };
1738}
1739
1740/// The ARM code here follows the Itanium code closely enough that we
1741/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001742void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1743 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001744 llvm::GlobalVariable *var,
1745 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001746 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001747
Richard Smithdbf74ba2013-04-14 23:01:42 +00001748 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001749 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001750 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1751 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001752
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001753 // If we have a global variable with internal linkage and thread-safe statics
1754 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001755 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1756
1757 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001758 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001759 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001760 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001761 // Guard variables are 64 bits in the generic ABI and size width on ARM
1762 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001763 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001764 }
John McCallb88a5662012-03-30 21:00:39 +00001765 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001766
John McCallb88a5662012-03-30 21:00:39 +00001767 // Create the guard variable if we don't already have it (as we
1768 // might if we're double-emitting this function body).
1769 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1770 if (!guard) {
1771 // Mangle the name for the guard.
1772 SmallString<256> guardName;
1773 {
1774 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001775 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001776 out.flush();
1777 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001778
John McCallb88a5662012-03-30 21:00:39 +00001779 // Create the guard variable with a zero-initializer.
1780 // Just absorb linkage and visibility from the guarded variable.
1781 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1782 false, var->getLinkage(),
1783 llvm::ConstantInt::get(guardTy, 0),
1784 guardName.str());
1785 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001786 // If the variable is thread-local, so is its guard variable.
1787 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001788
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001789 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1790 // as the associated data object
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001791 llvm::Comdat *C = var->getComdat();
1792 if (!D.isLocalVarDecl() && C) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001793 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001794 CGF.CurFn->setComdat(C);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001795 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1796 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001797 }
1798
John McCallb88a5662012-03-30 21:00:39 +00001799 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1800 }
John McCall87590e62012-03-30 07:09:50 +00001801
John McCall68ff0372010-09-08 01:44:27 +00001802 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001803 //
John McCall68ff0372010-09-08 01:44:27 +00001804 // Itanium C++ ABI 3.3.2:
1805 // The following is pseudo-code showing how these functions can be used:
1806 // if (obj_guard.first_byte == 0) {
1807 // if ( __cxa_guard_acquire (&obj_guard) ) {
1808 // try {
1809 // ... initialize the object ...;
1810 // } catch (...) {
1811 // __cxa_guard_abort (&obj_guard);
1812 // throw;
1813 // }
1814 // ... queue object destructor with __cxa_atexit() ...;
1815 // __cxa_guard_release (&obj_guard);
1816 // }
1817 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001818
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001819 // Load the first byte of the guard variable.
1820 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001821 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001822 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001823
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001824 // Itanium ABI:
1825 // An implementation supporting thread-safety on multiprocessor
1826 // systems must also guarantee that references to the initialized
1827 // object do not occur before the load of the initialization flag.
1828 //
1829 // In LLVM, we do this by marking the load Acquire.
1830 if (threadsafe)
1831 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001832
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001833 // For ARM, we should only check the first bit, rather than the entire byte:
1834 //
1835 // ARM C++ ABI 3.2.3.1:
1836 // To support the potential use of initialization guard variables
1837 // as semaphores that are the target of ARM SWP and LDREX/STREX
1838 // synchronizing instructions we define a static initialization
1839 // guard variable to be a 4-byte aligned, 4-byte word with the
1840 // following inline access protocol.
1841 // #define INITIALIZED 1
1842 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1843 // if (__cxa_guard_acquire(&obj_guard))
1844 // ...
1845 // }
1846 //
1847 // and similarly for ARM64:
1848 //
1849 // ARM64 C++ ABI 3.2.2:
1850 // This ABI instead only specifies the value bit 0 of the static guard
1851 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1852 // variable is not initialized and 1 when it is.
1853 llvm::Value *V =
1854 (UseARMGuardVarABI && !useInt8GuardVariable)
1855 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1856 : LI;
1857 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001858
1859 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1860 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1861
1862 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001863 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001864
1865 CGF.EmitBlock(InitCheckBlock);
1866
1867 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001868 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001869 // Call __cxa_guard_acquire.
1870 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001871 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001872
1873 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1874
1875 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1876 InitBlock, EndBlock);
1877
1878 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001879 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001880
1881 CGF.EmitBlock(InitBlock);
1882 }
1883
1884 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001885 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001886
John McCall5aa52592011-06-17 07:33:57 +00001887 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001888 // Pop the guard-abort cleanup if we pushed one.
1889 CGF.PopCleanupBlock();
1890
1891 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001892 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001893 } else {
John McCallb88a5662012-03-30 21:00:39 +00001894 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001895 }
1896
1897 CGF.EmitBlock(EndBlock);
1898}
John McCallc84ed6a2012-05-01 06:13:13 +00001899
1900/// Register a global destructor using __cxa_atexit.
1901static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1902 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001903 llvm::Constant *addr,
1904 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001905 const char *Name = "__cxa_atexit";
1906 if (TLS) {
1907 const llvm::Triple &T = CGF.getTarget().getTriple();
1908 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1909 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001910
John McCallc84ed6a2012-05-01 06:13:13 +00001911 // We're assuming that the destructor function is something we can
1912 // reasonably call with the default CC. Go ahead and cast it to the
1913 // right prototype.
1914 llvm::Type *dtorTy =
1915 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1916
1917 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1918 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1919 llvm::FunctionType *atexitTy =
1920 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1921
1922 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001923 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001924 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1925 fn->setDoesNotThrow();
1926
1927 // Create a variable that binds the atexit to this shared object.
1928 llvm::Constant *handle =
1929 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1930
1931 llvm::Value *args[] = {
1932 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1933 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1934 handle
1935 };
John McCall882987f2013-02-28 19:01:20 +00001936 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001937}
1938
1939/// Register a global destructor as best as we know how.
1940void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001941 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001942 llvm::Constant *dtor,
1943 llvm::Constant *addr) {
1944 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001945 if (CGM.getCodeGenOpts().CXAAtExit)
1946 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1947
1948 if (D.getTLSKind())
1949 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001950
1951 // In Apple kexts, we want to add a global destructor entry.
1952 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001953 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001954 // Generate a global destructor entry.
1955 return CGM.AddCXXDtorEntry(dtor, addr);
1956 }
1957
David Blaikieebe87e12013-08-27 23:57:18 +00001958 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001959}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001960
David Majnemer9b21c332014-07-11 20:28:10 +00001961static bool isThreadWrapperReplaceable(const VarDecl *VD,
1962 CodeGen::CodeGenModule &CGM) {
1963 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1964 // OS X prefers to have references to thread local variables to go through
1965 // the thread wrapper instead of directly referencing the backing variable.
1966 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1967 CGM.getTarget().getTriple().isMacOSX();
1968}
1969
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001970/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001971/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001972/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001973static llvm::GlobalValue::LinkageTypes
1974getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1975 llvm::GlobalValue::LinkageTypes VarLinkage =
1976 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1977
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001978 // For internal linkage variables, we don't need an external or weak wrapper.
1979 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1980 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001981
David Majnemer9b21c332014-07-11 20:28:10 +00001982 // If the thread wrapper is replaceable, give it appropriate linkage.
1983 if (isThreadWrapperReplaceable(VD, CGM)) {
1984 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1985 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1986 return llvm::GlobalVariable::WeakAnyLinkage;
1987 return VarLinkage;
1988 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001989 return llvm::GlobalValue::WeakODRLinkage;
1990}
1991
1992llvm::Function *
1993ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00001994 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001995 // Mangle the name for the thread_local wrapper function.
1996 SmallString<256> WrapperName;
1997 {
1998 llvm::raw_svector_ostream Out(WrapperName);
1999 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
2000 Out.flush();
2001 }
2002
Alexander Musmanf94c3182014-09-26 06:28:25 +00002003 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002004 return cast<llvm::Function>(V);
2005
Alexander Musmanf94c3182014-09-26 06:28:25 +00002006 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002007 if (VD->getType()->isReferenceType())
2008 RetTy = RetTy->getPointerElementType();
2009
2010 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002011 llvm::Function *Wrapper =
2012 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2013 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002014 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002015 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002016 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002017 return Wrapper;
2018}
2019
2020void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002021 CodeGenModule &CGM,
2022 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2023 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2024 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2025 llvm::Function *InitFunc = nullptr;
2026 if (!CXXThreadLocalInits.empty()) {
2027 // Generate a guarded initialization function.
2028 llvm::FunctionType *FTy =
2029 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2030 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002031 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002032 /*TLS=*/true);
2033 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2034 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2035 llvm::GlobalVariable::InternalLinkage,
2036 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2037 Guard->setThreadLocal(true);
2038 CodeGenFunction(CGM)
2039 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2040 }
2041 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
2042 const VarDecl *VD = CXXThreadLocals[I].first;
2043 llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002044
David Majnemer9b21c332014-07-11 20:28:10 +00002045 // Some targets require that all access to thread local variables go through
2046 // the thread wrapper. This means that we cannot attempt to create a thread
2047 // wrapper or a thread helper.
2048 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2049 continue;
2050
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002051 // Mangle the name for the thread_local initialization function.
2052 SmallString<256> InitFnName;
2053 {
2054 llvm::raw_svector_ostream Out(InitFnName);
2055 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
2056 Out.flush();
2057 }
2058
2059 // If we have a definition for the variable, emit the initialization
2060 // function as an alias to the global Init function (if any). Otherwise,
2061 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002062 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002063 bool InitIsInitFunc = false;
2064 if (VD->hasDefinition()) {
2065 InitIsInitFunc = true;
2066 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002067 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2068 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002069 } else {
2070 // Emit a weak global function referring to the initialization function.
2071 // This function will not exist if the TU defining the thread_local
2072 // variable in question does not need any dynamic initialization for
2073 // its thread_local variables.
2074 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2075 Init = llvm::Function::Create(
2076 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2077 &CGM.getModule());
2078 }
2079
2080 if (Init)
2081 Init->setVisibility(Var->getVisibility());
2082
2083 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2084 llvm::LLVMContext &Context = CGM.getModule().getContext();
2085 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2086 CGBuilderTy Builder(Entry);
2087 if (InitIsInitFunc) {
2088 if (Init)
2089 Builder.CreateCall(Init);
2090 } else {
2091 // Don't know whether we have an init function. Call it if it exists.
2092 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2093 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2094 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2095 Builder.CreateCondBr(Have, InitBB, ExitBB);
2096
2097 Builder.SetInsertPoint(InitBB);
2098 Builder.CreateCall(Init);
2099 Builder.CreateBr(ExitBB);
2100
2101 Builder.SetInsertPoint(ExitBB);
2102 }
2103
2104 // For a reference, the result of the wrapper function is a pointer to
2105 // the referenced object.
2106 llvm::Value *Val = Var;
2107 if (VD->getType()->isReferenceType()) {
2108 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2109 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2110 Val = LI;
2111 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002112 if (Val->getType() != Wrapper->getReturnType())
2113 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2114 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002115 Builder.CreateRet(Val);
2116 }
2117}
2118
Richard Smith0f383742014-03-26 22:48:22 +00002119LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2120 const VarDecl *VD,
2121 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002122 QualType T = VD->getType();
2123 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2124 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002125 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002126
2127 Val = CGF.Builder.CreateCall(Wrapper);
2128
2129 LValue LV;
2130 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002131 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002132 else
Richard Smith0f383742014-03-26 22:48:22 +00002133 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002134 // FIXME: need setObjCGCLValueClass?
2135 return LV;
2136}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002137
2138/// Return whether the given global decl needs a VTT parameter, which it does
2139/// if it's a base constructor or destructor with virtual bases.
2140bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2141 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2142
2143 // We don't have any virtual bases, just return early.
2144 if (!MD->getParent()->getNumVBases())
2145 return false;
2146
2147 // Check if we have a base constructor.
2148 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2149 return true;
2150
2151 // Check if we have a base destructor.
2152 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2153 return true;
2154
2155 return false;
2156}
David Majnemere2cb8d12014-07-07 06:20:47 +00002157
2158namespace {
2159class ItaniumRTTIBuilder {
2160 CodeGenModule &CGM; // Per-module state.
2161 llvm::LLVMContext &VMContext;
2162 const ItaniumCXXABI &CXXABI; // Per-module state.
2163
2164 /// Fields - The fields of the RTTI descriptor currently being built.
2165 SmallVector<llvm::Constant *, 16> Fields;
2166
2167 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2168 llvm::GlobalVariable *
2169 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2170
2171 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2172 /// descriptor of the given type.
2173 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2174
2175 /// BuildVTablePointer - Build the vtable pointer for the given type.
2176 void BuildVTablePointer(const Type *Ty);
2177
2178 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2179 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2180 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2181
2182 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2183 /// classes with bases that do not satisfy the abi::__si_class_type_info
2184 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2185 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2186
2187 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2188 /// for pointer types.
2189 void BuildPointerTypeInfo(QualType PointeeTy);
2190
2191 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2192 /// type_info for an object type.
2193 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2194
2195 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2196 /// struct, used for member pointer types.
2197 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2198
2199public:
2200 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2201 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2202
2203 // Pointer type info flags.
2204 enum {
2205 /// PTI_Const - Type has const qualifier.
2206 PTI_Const = 0x1,
2207
2208 /// PTI_Volatile - Type has volatile qualifier.
2209 PTI_Volatile = 0x2,
2210
2211 /// PTI_Restrict - Type has restrict qualifier.
2212 PTI_Restrict = 0x4,
2213
2214 /// PTI_Incomplete - Type is incomplete.
2215 PTI_Incomplete = 0x8,
2216
2217 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2218 /// (in pointer to member).
2219 PTI_ContainingClassIncomplete = 0x10
2220 };
2221
2222 // VMI type info flags.
2223 enum {
2224 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2225 VMI_NonDiamondRepeat = 0x1,
2226
2227 /// VMI_DiamondShaped - Class is diamond shaped.
2228 VMI_DiamondShaped = 0x2
2229 };
2230
2231 // Base class type info flags.
2232 enum {
2233 /// BCTI_Virtual - Base class is virtual.
2234 BCTI_Virtual = 0x1,
2235
2236 /// BCTI_Public - Base class is public.
2237 BCTI_Public = 0x2
2238 };
2239
2240 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2241 ///
2242 /// \param Force - true to force the creation of this RTTI value
2243 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2244};
2245}
2246
2247llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2248 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2249 SmallString<256> OutName;
2250 llvm::raw_svector_ostream Out(OutName);
2251 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2252 Out.flush();
2253 StringRef Name = OutName.str();
2254
2255 // We know that the mangled name of the type starts at index 4 of the
2256 // mangled name of the typename, so we can just index into it in order to
2257 // get the mangled name of the type.
2258 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2259 Name.substr(4));
2260
2261 llvm::GlobalVariable *GV =
2262 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2263
2264 GV->setInitializer(Init);
2265
2266 return GV;
2267}
2268
2269llvm::Constant *
2270ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2271 // Mangle the RTTI name.
2272 SmallString<256> OutName;
2273 llvm::raw_svector_ostream Out(OutName);
2274 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2275 Out.flush();
2276 StringRef Name = OutName.str();
2277
2278 // Look for an existing global.
2279 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2280
2281 if (!GV) {
2282 // Create a new global variable.
2283 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2284 /*Constant=*/true,
2285 llvm::GlobalValue::ExternalLinkage, nullptr,
2286 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002287 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2288 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2289 if (RD->hasAttr<DLLImportAttr>())
2290 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2291 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002292 }
2293
2294 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2295}
2296
2297/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2298/// info for that type is defined in the standard library.
2299static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2300 // Itanium C++ ABI 2.9.2:
2301 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2302 // the run-time support library. Specifically, the run-time support
2303 // library should contain type_info objects for the types X, X* and
2304 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2305 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2306 // long, unsigned long, long long, unsigned long long, float, double,
2307 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2308 // half-precision floating point types.
2309 switch (Ty->getKind()) {
2310 case BuiltinType::Void:
2311 case BuiltinType::NullPtr:
2312 case BuiltinType::Bool:
2313 case BuiltinType::WChar_S:
2314 case BuiltinType::WChar_U:
2315 case BuiltinType::Char_U:
2316 case BuiltinType::Char_S:
2317 case BuiltinType::UChar:
2318 case BuiltinType::SChar:
2319 case BuiltinType::Short:
2320 case BuiltinType::UShort:
2321 case BuiltinType::Int:
2322 case BuiltinType::UInt:
2323 case BuiltinType::Long:
2324 case BuiltinType::ULong:
2325 case BuiltinType::LongLong:
2326 case BuiltinType::ULongLong:
2327 case BuiltinType::Half:
2328 case BuiltinType::Float:
2329 case BuiltinType::Double:
2330 case BuiltinType::LongDouble:
2331 case BuiltinType::Char16:
2332 case BuiltinType::Char32:
2333 case BuiltinType::Int128:
2334 case BuiltinType::UInt128:
2335 case BuiltinType::OCLImage1d:
2336 case BuiltinType::OCLImage1dArray:
2337 case BuiltinType::OCLImage1dBuffer:
2338 case BuiltinType::OCLImage2d:
2339 case BuiltinType::OCLImage2dArray:
2340 case BuiltinType::OCLImage3d:
2341 case BuiltinType::OCLSampler:
2342 case BuiltinType::OCLEvent:
2343 return true;
2344
2345 case BuiltinType::Dependent:
2346#define BUILTIN_TYPE(Id, SingletonId)
2347#define PLACEHOLDER_TYPE(Id, SingletonId) \
2348 case BuiltinType::Id:
2349#include "clang/AST/BuiltinTypes.def"
2350 llvm_unreachable("asking for RRTI for a placeholder type!");
2351
2352 case BuiltinType::ObjCId:
2353 case BuiltinType::ObjCClass:
2354 case BuiltinType::ObjCSel:
2355 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2356 }
2357
2358 llvm_unreachable("Invalid BuiltinType Kind!");
2359}
2360
2361static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2362 QualType PointeeTy = PointerTy->getPointeeType();
2363 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2364 if (!BuiltinTy)
2365 return false;
2366
2367 // Check the qualifiers.
2368 Qualifiers Quals = PointeeTy.getQualifiers();
2369 Quals.removeConst();
2370
2371 if (!Quals.empty())
2372 return false;
2373
2374 return TypeInfoIsInStandardLibrary(BuiltinTy);
2375}
2376
2377/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2378/// information for the given type exists in the standard library.
2379static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2380 // Type info for builtin types is defined in the standard library.
2381 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2382 return TypeInfoIsInStandardLibrary(BuiltinTy);
2383
2384 // Type info for some pointer types to builtin types is defined in the
2385 // standard library.
2386 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2387 return TypeInfoIsInStandardLibrary(PointerTy);
2388
2389 return false;
2390}
2391
2392/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2393/// the given type exists somewhere else, and that we should not emit the type
2394/// information in this translation unit. Assumes that it is not a
2395/// standard-library type.
2396static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2397 QualType Ty) {
2398 ASTContext &Context = CGM.getContext();
2399
2400 // If RTTI is disabled, assume it might be disabled in the
2401 // translation unit that defines any potential key function, too.
2402 if (!Context.getLangOpts().RTTI) return false;
2403
2404 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2405 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2406 if (!RD->hasDefinition())
2407 return false;
2408
2409 if (!RD->isDynamicClass())
2410 return false;
2411
2412 // FIXME: this may need to be reconsidered if the key function
2413 // changes.
David Majnemer1fb1a042014-11-07 07:26:38 +00002414 if (CGM.getVTables().isVTableExternal(RD))
2415 return true;
2416
2417 if (RD->hasAttr<DLLImportAttr>())
2418 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002419 }
2420
2421 return false;
2422}
2423
2424/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2425static bool IsIncompleteClassType(const RecordType *RecordTy) {
2426 return !RecordTy->getDecl()->isCompleteDefinition();
2427}
2428
2429/// ContainsIncompleteClassType - Returns whether the given type contains an
2430/// incomplete class type. This is true if
2431///
2432/// * The given type is an incomplete class type.
2433/// * The given type is a pointer type whose pointee type contains an
2434/// incomplete class type.
2435/// * The given type is a member pointer type whose class is an incomplete
2436/// class type.
2437/// * The given type is a member pointer type whoise pointee type contains an
2438/// incomplete class type.
2439/// is an indirect or direct pointer to an incomplete class type.
2440static bool ContainsIncompleteClassType(QualType Ty) {
2441 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2442 if (IsIncompleteClassType(RecordTy))
2443 return true;
2444 }
2445
2446 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2447 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2448
2449 if (const MemberPointerType *MemberPointerTy =
2450 dyn_cast<MemberPointerType>(Ty)) {
2451 // Check if the class type is incomplete.
2452 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2453 if (IsIncompleteClassType(ClassType))
2454 return true;
2455
2456 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2457 }
2458
2459 return false;
2460}
2461
2462// CanUseSingleInheritance - Return whether the given record decl has a "single,
2463// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2464// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2465static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2466 // Check the number of bases.
2467 if (RD->getNumBases() != 1)
2468 return false;
2469
2470 // Get the base.
2471 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2472
2473 // Check that the base is not virtual.
2474 if (Base->isVirtual())
2475 return false;
2476
2477 // Check that the base is public.
2478 if (Base->getAccessSpecifier() != AS_public)
2479 return false;
2480
2481 // Check that the class is dynamic iff the base is.
2482 const CXXRecordDecl *BaseDecl =
2483 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2484 if (!BaseDecl->isEmpty() &&
2485 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2486 return false;
2487
2488 return true;
2489}
2490
2491void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2492 // abi::__class_type_info.
2493 static const char * const ClassTypeInfo =
2494 "_ZTVN10__cxxabiv117__class_type_infoE";
2495 // abi::__si_class_type_info.
2496 static const char * const SIClassTypeInfo =
2497 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2498 // abi::__vmi_class_type_info.
2499 static const char * const VMIClassTypeInfo =
2500 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2501
2502 const char *VTableName = nullptr;
2503
2504 switch (Ty->getTypeClass()) {
2505#define TYPE(Class, Base)
2506#define ABSTRACT_TYPE(Class, Base)
2507#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2508#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2509#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2510#include "clang/AST/TypeNodes.def"
2511 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2512
2513 case Type::LValueReference:
2514 case Type::RValueReference:
2515 llvm_unreachable("References shouldn't get here");
2516
2517 case Type::Auto:
2518 llvm_unreachable("Undeduced auto type shouldn't get here");
2519
2520 case Type::Builtin:
2521 // GCC treats vector and complex types as fundamental types.
2522 case Type::Vector:
2523 case Type::ExtVector:
2524 case Type::Complex:
2525 case Type::Atomic:
2526 // FIXME: GCC treats block pointers as fundamental types?!
2527 case Type::BlockPointer:
2528 // abi::__fundamental_type_info.
2529 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2530 break;
2531
2532 case Type::ConstantArray:
2533 case Type::IncompleteArray:
2534 case Type::VariableArray:
2535 // abi::__array_type_info.
2536 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2537 break;
2538
2539 case Type::FunctionNoProto:
2540 case Type::FunctionProto:
2541 // abi::__function_type_info.
2542 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2543 break;
2544
2545 case Type::Enum:
2546 // abi::__enum_type_info.
2547 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2548 break;
2549
2550 case Type::Record: {
2551 const CXXRecordDecl *RD =
2552 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2553
2554 if (!RD->hasDefinition() || !RD->getNumBases()) {
2555 VTableName = ClassTypeInfo;
2556 } else if (CanUseSingleInheritance(RD)) {
2557 VTableName = SIClassTypeInfo;
2558 } else {
2559 VTableName = VMIClassTypeInfo;
2560 }
2561
2562 break;
2563 }
2564
2565 case Type::ObjCObject:
2566 // Ignore protocol qualifiers.
2567 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2568
2569 // Handle id and Class.
2570 if (isa<BuiltinType>(Ty)) {
2571 VTableName = ClassTypeInfo;
2572 break;
2573 }
2574
2575 assert(isa<ObjCInterfaceType>(Ty));
2576 // Fall through.
2577
2578 case Type::ObjCInterface:
2579 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2580 VTableName = SIClassTypeInfo;
2581 } else {
2582 VTableName = ClassTypeInfo;
2583 }
2584 break;
2585
2586 case Type::ObjCObjectPointer:
2587 case Type::Pointer:
2588 // abi::__pointer_type_info.
2589 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2590 break;
2591
2592 case Type::MemberPointer:
2593 // abi::__pointer_to_member_type_info.
2594 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2595 break;
2596 }
2597
2598 llvm::Constant *VTable =
2599 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2600
2601 llvm::Type *PtrDiffTy =
2602 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2603
2604 // The vtable address point is 2.
2605 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2606 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2607 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2608
2609 Fields.push_back(VTable);
2610}
2611
2612/// \brief Return the linkage that the type info and type info name constants
2613/// should have for the given type.
2614static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2615 QualType Ty) {
2616 // Itanium C++ ABI 2.9.5p7:
2617 // In addition, it and all of the intermediate abi::__pointer_type_info
2618 // structs in the chain down to the abi::__class_type_info for the
2619 // incomplete class type must be prevented from resolving to the
2620 // corresponding type_info structs for the complete class type, possibly
2621 // by making them local static objects. Finally, a dummy class RTTI is
2622 // generated for the incomplete type that will not resolve to the final
2623 // complete class RTTI (because the latter need not exist), possibly by
2624 // making it a local static object.
2625 if (ContainsIncompleteClassType(Ty))
2626 return llvm::GlobalValue::InternalLinkage;
2627
2628 switch (Ty->getLinkage()) {
2629 case NoLinkage:
2630 case InternalLinkage:
2631 case UniqueExternalLinkage:
2632 return llvm::GlobalValue::InternalLinkage;
2633
2634 case VisibleNoLinkage:
2635 case ExternalLinkage:
2636 if (!CGM.getLangOpts().RTTI) {
2637 // RTTI is not enabled, which means that this type info struct is going
2638 // to be used for exception handling. Give it linkonce_odr linkage.
2639 return llvm::GlobalValue::LinkOnceODRLinkage;
2640 }
2641
2642 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2643 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2644 if (RD->hasAttr<WeakAttr>())
2645 return llvm::GlobalValue::WeakODRLinkage;
2646 if (RD->isDynamicClass())
2647 return CGM.getVTableLinkage(RD);
2648 }
2649
2650 return llvm::GlobalValue::LinkOnceODRLinkage;
2651 }
2652
2653 llvm_unreachable("Invalid linkage!");
2654}
2655
2656llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2657 // We want to operate on the canonical type.
2658 Ty = CGM.getContext().getCanonicalType(Ty);
2659
2660 // Check if we've already emitted an RTTI descriptor for this type.
2661 SmallString<256> OutName;
2662 llvm::raw_svector_ostream Out(OutName);
2663 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2664 Out.flush();
2665 StringRef Name = OutName.str();
2666
2667 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2668 if (OldGV && !OldGV->isDeclaration()) {
2669 assert(!OldGV->hasAvailableExternallyLinkage() &&
2670 "available_externally typeinfos not yet implemented");
2671
2672 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2673 }
2674
2675 // Check if there is already an external RTTI descriptor for this type.
2676 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2677 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2678 return GetAddrOfExternalRTTIDescriptor(Ty);
2679
2680 // Emit the standard library with external linkage.
2681 llvm::GlobalVariable::LinkageTypes Linkage;
2682 if (IsStdLib)
2683 Linkage = llvm::GlobalValue::ExternalLinkage;
2684 else
2685 Linkage = getTypeInfoLinkage(CGM, Ty);
2686
2687 // Add the vtable pointer.
2688 BuildVTablePointer(cast<Type>(Ty));
2689
2690 // And the name.
2691 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2692 llvm::Constant *TypeNameField;
2693
2694 // If we're supposed to demote the visibility, be sure to set a flag
2695 // to use a string comparison for type_info comparisons.
2696 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2697 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2698 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2699 // The flag is the sign bit, which on ARM64 is defined to be clear
2700 // for global pointers. This is very ARM64-specific.
2701 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2702 llvm::Constant *flag =
2703 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2704 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2705 TypeNameField =
2706 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2707 } else {
2708 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2709 }
2710 Fields.push_back(TypeNameField);
2711
2712 switch (Ty->getTypeClass()) {
2713#define TYPE(Class, Base)
2714#define ABSTRACT_TYPE(Class, Base)
2715#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2716#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2717#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2718#include "clang/AST/TypeNodes.def"
2719 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2720
2721 // GCC treats vector types as fundamental types.
2722 case Type::Builtin:
2723 case Type::Vector:
2724 case Type::ExtVector:
2725 case Type::Complex:
2726 case Type::BlockPointer:
2727 // Itanium C++ ABI 2.9.5p4:
2728 // abi::__fundamental_type_info adds no data members to std::type_info.
2729 break;
2730
2731 case Type::LValueReference:
2732 case Type::RValueReference:
2733 llvm_unreachable("References shouldn't get here");
2734
2735 case Type::Auto:
2736 llvm_unreachable("Undeduced auto type shouldn't get here");
2737
2738 case Type::ConstantArray:
2739 case Type::IncompleteArray:
2740 case Type::VariableArray:
2741 // Itanium C++ ABI 2.9.5p5:
2742 // abi::__array_type_info adds no data members to std::type_info.
2743 break;
2744
2745 case Type::FunctionNoProto:
2746 case Type::FunctionProto:
2747 // Itanium C++ ABI 2.9.5p5:
2748 // abi::__function_type_info adds no data members to std::type_info.
2749 break;
2750
2751 case Type::Enum:
2752 // Itanium C++ ABI 2.9.5p5:
2753 // abi::__enum_type_info adds no data members to std::type_info.
2754 break;
2755
2756 case Type::Record: {
2757 const CXXRecordDecl *RD =
2758 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2759 if (!RD->hasDefinition() || !RD->getNumBases()) {
2760 // We don't need to emit any fields.
2761 break;
2762 }
2763
2764 if (CanUseSingleInheritance(RD))
2765 BuildSIClassTypeInfo(RD);
2766 else
2767 BuildVMIClassTypeInfo(RD);
2768
2769 break;
2770 }
2771
2772 case Type::ObjCObject:
2773 case Type::ObjCInterface:
2774 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2775 break;
2776
2777 case Type::ObjCObjectPointer:
2778 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2779 break;
2780
2781 case Type::Pointer:
2782 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2783 break;
2784
2785 case Type::MemberPointer:
2786 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2787 break;
2788
2789 case Type::Atomic:
2790 // No fields, at least for the moment.
2791 break;
2792 }
2793
2794 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2795
Rafael Espindolacb92c192015-01-15 23:18:01 +00002796 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002797 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002798 new llvm::GlobalVariable(M, Init->getType(),
2799 /*Constant=*/true, Linkage, Init, Name);
2800
2801 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2802 GV->setComdat(M.getOrInsertComdat(GV->getName()));
David Majnemere2cb8d12014-07-07 06:20:47 +00002803
2804 // If there's already an old global variable, replace it with the new one.
2805 if (OldGV) {
2806 GV->takeName(OldGV);
2807 llvm::Constant *NewPtr =
2808 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2809 OldGV->replaceAllUsesWith(NewPtr);
2810 OldGV->eraseFromParent();
2811 }
2812
2813 // The Itanium ABI specifies that type_info objects must be globally
2814 // unique, with one exception: if the type is an incomplete class
2815 // type or a (possibly indirect) pointer to one. That exception
2816 // affects the general case of comparing type_info objects produced
2817 // by the typeid operator, which is why the comparison operators on
2818 // std::type_info generally use the type_info name pointers instead
2819 // of the object addresses. However, the language's built-in uses
2820 // of RTTI generally require class types to be complete, even when
2821 // manipulating pointers to those class types. This allows the
2822 // implementation of dynamic_cast to rely on address equality tests,
2823 // which is much faster.
2824
2825 // All of this is to say that it's important that both the type_info
2826 // object and the type_info name be uniqued when weakly emitted.
2827
2828 // Give the type_info object and name the formal visibility of the
2829 // type itself.
2830 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2831 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2832 // If the linkage is local, only default visibility makes sense.
2833 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2834 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2835 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2836 else
2837 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2838 TypeName->setVisibility(llvmVisibility);
2839 GV->setVisibility(llvmVisibility);
2840
2841 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2842}
2843
2844/// ComputeQualifierFlags - Compute the pointer type info flags from the
2845/// given qualifier.
2846static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2847 unsigned Flags = 0;
2848
2849 if (Quals.hasConst())
2850 Flags |= ItaniumRTTIBuilder::PTI_Const;
2851 if (Quals.hasVolatile())
2852 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2853 if (Quals.hasRestrict())
2854 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2855
2856 return Flags;
2857}
2858
2859/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2860/// for the given Objective-C object type.
2861void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2862 // Drop qualifiers.
2863 const Type *T = OT->getBaseType().getTypePtr();
2864 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2865
2866 // The builtin types are abi::__class_type_infos and don't require
2867 // extra fields.
2868 if (isa<BuiltinType>(T)) return;
2869
2870 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2871 ObjCInterfaceDecl *Super = Class->getSuperClass();
2872
2873 // Root classes are also __class_type_info.
2874 if (!Super) return;
2875
2876 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2877
2878 // Everything else is single inheritance.
2879 llvm::Constant *BaseTypeInfo =
2880 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2881 Fields.push_back(BaseTypeInfo);
2882}
2883
2884/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2885/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2886void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2887 // Itanium C++ ABI 2.9.5p6b:
2888 // It adds to abi::__class_type_info a single member pointing to the
2889 // type_info structure for the base type,
2890 llvm::Constant *BaseTypeInfo =
2891 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2892 Fields.push_back(BaseTypeInfo);
2893}
2894
2895namespace {
2896 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2897 /// a class hierarchy.
2898 struct SeenBases {
2899 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2900 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2901 };
2902}
2903
2904/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2905/// abi::__vmi_class_type_info.
2906///
2907static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2908 SeenBases &Bases) {
2909
2910 unsigned Flags = 0;
2911
2912 const CXXRecordDecl *BaseDecl =
2913 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2914
2915 if (Base->isVirtual()) {
2916 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002917 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002918 // If this virtual base has been seen before, then the class is diamond
2919 // shaped.
2920 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2921 } else {
2922 if (Bases.NonVirtualBases.count(BaseDecl))
2923 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2924 }
2925 } else {
2926 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002927 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002928 // If this non-virtual base has been seen before, then the class has non-
2929 // diamond shaped repeated inheritance.
2930 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2931 } else {
2932 if (Bases.VirtualBases.count(BaseDecl))
2933 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2934 }
2935 }
2936
2937 // Walk all bases.
2938 for (const auto &I : BaseDecl->bases())
2939 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2940
2941 return Flags;
2942}
2943
2944static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2945 unsigned Flags = 0;
2946 SeenBases Bases;
2947
2948 // Walk all bases.
2949 for (const auto &I : RD->bases())
2950 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2951
2952 return Flags;
2953}
2954
2955/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2956/// classes with bases that do not satisfy the abi::__si_class_type_info
2957/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2958void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2959 llvm::Type *UnsignedIntLTy =
2960 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2961
2962 // Itanium C++ ABI 2.9.5p6c:
2963 // __flags is a word with flags describing details about the class
2964 // structure, which may be referenced by using the __flags_masks
2965 // enumeration. These flags refer to both direct and indirect bases.
2966 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2967 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2968
2969 // Itanium C++ ABI 2.9.5p6c:
2970 // __base_count is a word with the number of direct proper base class
2971 // descriptions that follow.
2972 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2973
2974 if (!RD->getNumBases())
2975 return;
2976
2977 llvm::Type *LongLTy =
2978 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2979
2980 // Now add the base class descriptions.
2981
2982 // Itanium C++ ABI 2.9.5p6c:
2983 // __base_info[] is an array of base class descriptions -- one for every
2984 // direct proper base. Each description is of the type:
2985 //
2986 // struct abi::__base_class_type_info {
2987 // public:
2988 // const __class_type_info *__base_type;
2989 // long __offset_flags;
2990 //
2991 // enum __offset_flags_masks {
2992 // __virtual_mask = 0x1,
2993 // __public_mask = 0x2,
2994 // __offset_shift = 8
2995 // };
2996 // };
2997 for (const auto &Base : RD->bases()) {
2998 // The __base_type member points to the RTTI for the base type.
2999 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3000
3001 const CXXRecordDecl *BaseDecl =
3002 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3003
3004 int64_t OffsetFlags = 0;
3005
3006 // All but the lower 8 bits of __offset_flags are a signed offset.
3007 // For a non-virtual base, this is the offset in the object of the base
3008 // subobject. For a virtual base, this is the offset in the virtual table of
3009 // the virtual base offset for the virtual base referenced (negative).
3010 CharUnits Offset;
3011 if (Base.isVirtual())
3012 Offset =
3013 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3014 else {
3015 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3016 Offset = Layout.getBaseClassOffset(BaseDecl);
3017 };
3018
3019 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3020
3021 // The low-order byte of __offset_flags contains flags, as given by the
3022 // masks from the enumeration __offset_flags_masks.
3023 if (Base.isVirtual())
3024 OffsetFlags |= BCTI_Virtual;
3025 if (Base.getAccessSpecifier() == AS_public)
3026 OffsetFlags |= BCTI_Public;
3027
3028 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3029 }
3030}
3031
3032/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3033/// used for pointer types.
3034void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3035 Qualifiers Quals;
3036 QualType UnqualifiedPointeeTy =
3037 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3038
3039 // Itanium C++ ABI 2.9.5p7:
3040 // __flags is a flag word describing the cv-qualification and other
3041 // attributes of the type pointed to
3042 unsigned Flags = ComputeQualifierFlags(Quals);
3043
3044 // Itanium C++ ABI 2.9.5p7:
3045 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3046 // incomplete class type, the incomplete target type flag is set.
3047 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3048 Flags |= PTI_Incomplete;
3049
3050 llvm::Type *UnsignedIntLTy =
3051 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3052 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3053
3054 // Itanium C++ ABI 2.9.5p7:
3055 // __pointee is a pointer to the std::type_info derivation for the
3056 // unqualified type being pointed to.
3057 llvm::Constant *PointeeTypeInfo =
3058 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3059 Fields.push_back(PointeeTypeInfo);
3060}
3061
3062/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3063/// struct, used for member pointer types.
3064void
3065ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3066 QualType PointeeTy = Ty->getPointeeType();
3067
3068 Qualifiers Quals;
3069 QualType UnqualifiedPointeeTy =
3070 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3071
3072 // Itanium C++ ABI 2.9.5p7:
3073 // __flags is a flag word describing the cv-qualification and other
3074 // attributes of the type pointed to.
3075 unsigned Flags = ComputeQualifierFlags(Quals);
3076
3077 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3078
3079 // Itanium C++ ABI 2.9.5p7:
3080 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3081 // incomplete class type, the incomplete target type flag is set.
3082 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3083 Flags |= PTI_Incomplete;
3084
3085 if (IsIncompleteClassType(ClassType))
3086 Flags |= PTI_ContainingClassIncomplete;
3087
3088 llvm::Type *UnsignedIntLTy =
3089 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3090 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3091
3092 // Itanium C++ ABI 2.9.5p7:
3093 // __pointee is a pointer to the std::type_info derivation for the
3094 // unqualified type being pointed to.
3095 llvm::Constant *PointeeTypeInfo =
3096 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3097 Fields.push_back(PointeeTypeInfo);
3098
3099 // Itanium C++ ABI 2.9.5p9:
3100 // __context is a pointer to an abi::__class_type_info corresponding to the
3101 // class type containing the member pointed to
3102 // (e.g., the "A" in "int A::*").
3103 Fields.push_back(
3104 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3105}
3106
David Majnemer443250f2015-03-17 20:35:00 +00003107llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003108 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3109}
3110
3111void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3112 QualType PointerType = getContext().getPointerType(Type);
3113 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3114 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3115 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3116 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3117}
3118
3119void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3120 QualType FundamentalTypes[] = {
3121 getContext().VoidTy, getContext().NullPtrTy,
3122 getContext().BoolTy, getContext().WCharTy,
3123 getContext().CharTy, getContext().UnsignedCharTy,
3124 getContext().SignedCharTy, getContext().ShortTy,
3125 getContext().UnsignedShortTy, getContext().IntTy,
3126 getContext().UnsignedIntTy, getContext().LongTy,
3127 getContext().UnsignedLongTy, getContext().LongLongTy,
3128 getContext().UnsignedLongLongTy, getContext().HalfTy,
3129 getContext().FloatTy, getContext().DoubleTy,
3130 getContext().LongDoubleTy, getContext().Char16Ty,
3131 getContext().Char32Ty,
3132 };
3133 for (const QualType &FundamentalType : FundamentalTypes)
3134 EmitFundamentalRTTIDescriptor(FundamentalType);
3135}
3136
3137/// What sort of uniqueness rules should we use for the RTTI for the
3138/// given type?
3139ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3140 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3141 if (shouldRTTIBeUnique())
3142 return RUK_Unique;
3143
3144 // It's only necessary for linkonce_odr or weak_odr linkage.
3145 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3146 Linkage != llvm::GlobalValue::WeakODRLinkage)
3147 return RUK_Unique;
3148
3149 // It's only necessary with default visibility.
3150 if (CanTy->getVisibility() != DefaultVisibility)
3151 return RUK_Unique;
3152
3153 // If we're not required to publish this symbol, hide it.
3154 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3155 return RUK_NonUniqueHidden;
3156
3157 // If we're required to publish this symbol, as we might be under an
3158 // explicit instantiation, leave it with default visibility but
3159 // enable string-comparisons.
3160 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3161 return RUK_NonUniqueVisible;
3162}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003163
Rafael Espindola1e4df922014-09-16 15:18:21 +00003164// Find out how to codegen the complete destructor and constructor
3165namespace {
3166enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3167}
3168static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3169 const CXXMethodDecl *MD) {
3170 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3171 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003172
Rafael Espindola1e4df922014-09-16 15:18:21 +00003173 // The complete and base structors are not equivalent if there are any virtual
3174 // bases, so emit separate functions.
3175 if (MD->getParent()->getNumVBases())
3176 return StructorCodegen::Emit;
3177
3178 GlobalDecl AliasDecl;
3179 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3180 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3181 } else {
3182 const auto *CD = cast<CXXConstructorDecl>(MD);
3183 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3184 }
3185 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3186
3187 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3188 return StructorCodegen::RAUW;
3189
3190 // FIXME: Should we allow available_externally aliases?
3191 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3192 return StructorCodegen::RAUW;
3193
Rafael Espindola0806f982014-09-16 20:19:43 +00003194 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3195 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3196 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3197 return StructorCodegen::COMDAT;
3198 return StructorCodegen::Emit;
3199 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003200
3201 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003202}
3203
Rafael Espindola1e4df922014-09-16 15:18:21 +00003204static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3205 GlobalDecl AliasDecl,
3206 GlobalDecl TargetDecl) {
3207 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3208
3209 StringRef MangledName = CGM.getMangledName(AliasDecl);
3210 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3211 if (Entry && !Entry->isDeclaration())
3212 return;
3213
3214 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3215 llvm::PointerType *AliasType = Aliasee->getType();
3216
3217 // Create the alias with no name.
3218 auto *Alias = llvm::GlobalAlias::create(
3219 AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule());
3220
3221 // Switch any previous uses to the alias.
3222 if (Entry) {
3223 assert(Entry->getType() == AliasType &&
3224 "declaration exists with different type");
3225 Alias->takeName(Entry);
3226 Entry->replaceAllUsesWith(Alias);
3227 Entry->eraseFromParent();
3228 } else {
3229 Alias->setName(MangledName);
3230 }
3231
3232 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003233 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003234}
3235
3236void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3237 StructorType Type) {
3238 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3239 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3240
3241 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3242
3243 if (Type == StructorType::Complete) {
3244 GlobalDecl CompleteDecl;
3245 GlobalDecl BaseDecl;
3246 if (CD) {
3247 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3248 BaseDecl = GlobalDecl(CD, Ctor_Base);
3249 } else {
3250 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3251 BaseDecl = GlobalDecl(DD, Dtor_Base);
3252 }
3253
3254 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3255 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3256 return;
3257 }
3258
3259 if (CGType == StructorCodegen::RAUW) {
3260 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3261 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3262 CGM.addReplacement(MangledName, Aliasee);
3263 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003264 }
3265 }
3266
3267 // The base destructor is equivalent to the base destructor of its
3268 // base class if there is exactly one non-virtual base class with a
3269 // non-trivial destructor, there are no fields with a non-trivial
3270 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003271 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3272 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003273 return;
3274
Rafael Espindola1e4df922014-09-16 15:18:21 +00003275 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003276
Rafael Espindola1e4df922014-09-16 15:18:21 +00003277 if (CGType == StructorCodegen::COMDAT) {
3278 SmallString<256> Buffer;
3279 llvm::raw_svector_ostream Out(Buffer);
3280 if (DD)
3281 getMangleContext().mangleCXXDtorComdat(DD, Out);
3282 else
3283 getMangleContext().mangleCXXCtorComdat(CD, Out);
3284 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3285 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003286 } else {
3287 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003288 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003289}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003290
3291static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3292 // void *__cxa_begin_catch(void*);
3293 llvm::FunctionType *FTy = llvm::FunctionType::get(
3294 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3295
3296 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3297}
3298
3299static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3300 // void __cxa_end_catch();
3301 llvm::FunctionType *FTy =
3302 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3303
3304 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3305}
3306
3307static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3308 // void *__cxa_get_exception_ptr(void*);
3309 llvm::FunctionType *FTy = llvm::FunctionType::get(
3310 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3311
3312 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3313}
3314
3315namespace {
3316 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3317 /// exception type lets us state definitively that the thrown exception
3318 /// type does not have a destructor. In particular:
3319 /// - Catch-alls tell us nothing, so we have to conservatively
3320 /// assume that the thrown exception might have a destructor.
3321 /// - Catches by reference behave according to their base types.
3322 /// - Catches of non-record types will only trigger for exceptions
3323 /// of non-record types, which never have destructors.
3324 /// - Catches of record types can trigger for arbitrary subclasses
3325 /// of the caught type, so we have to assume the actual thrown
3326 /// exception type might have a throwing destructor, even if the
3327 /// caught type's destructor is trivial or nothrow.
3328 struct CallEndCatch : EHScopeStack::Cleanup {
3329 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3330 bool MightThrow;
3331
3332 void Emit(CodeGenFunction &CGF, Flags flags) override {
3333 if (!MightThrow) {
3334 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3335 return;
3336 }
3337
3338 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3339 }
3340 };
3341}
3342
3343/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3344/// __cxa_end_catch.
3345///
3346/// \param EndMightThrow - true if __cxa_end_catch might throw
3347static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3348 llvm::Value *Exn,
3349 bool EndMightThrow) {
3350 llvm::CallInst *call =
3351 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3352
3353 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3354
3355 return call;
3356}
3357
3358/// A "special initializer" callback for initializing a catch
3359/// parameter during catch initialization.
3360static void InitCatchParam(CodeGenFunction &CGF,
3361 const VarDecl &CatchParam,
3362 llvm::Value *ParamAddr,
3363 SourceLocation Loc) {
3364 // Load the exception from where the landing pad saved it.
3365 llvm::Value *Exn = CGF.getExceptionFromSlot();
3366
3367 CanQualType CatchType =
3368 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3369 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3370
3371 // If we're catching by reference, we can just cast the object
3372 // pointer to the appropriate pointer.
3373 if (isa<ReferenceType>(CatchType)) {
3374 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3375 bool EndCatchMightThrow = CaughtType->isRecordType();
3376
3377 // __cxa_begin_catch returns the adjusted object pointer.
3378 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3379
3380 // We have no way to tell the personality function that we're
3381 // catching by reference, so if we're catching a pointer,
3382 // __cxa_begin_catch will actually return that pointer by value.
3383 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3384 QualType PointeeType = PT->getPointeeType();
3385
3386 // When catching by reference, generally we should just ignore
3387 // this by-value pointer and use the exception object instead.
3388 if (!PointeeType->isRecordType()) {
3389
3390 // Exn points to the struct _Unwind_Exception header, which
3391 // we have to skip past in order to reach the exception data.
3392 unsigned HeaderSize =
3393 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3394 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3395
3396 // However, if we're catching a pointer-to-record type that won't
3397 // work, because the personality function might have adjusted
3398 // the pointer. There's actually no way for us to fully satisfy
3399 // the language/ABI contract here: we can't use Exn because it
3400 // might have the wrong adjustment, but we can't use the by-value
3401 // pointer because it's off by a level of abstraction.
3402 //
3403 // The current solution is to dump the adjusted pointer into an
3404 // alloca, which breaks language semantics (because changing the
3405 // pointer doesn't change the exception) but at least works.
3406 // The better solution would be to filter out non-exact matches
3407 // and rethrow them, but this is tricky because the rethrow
3408 // really needs to be catchable by other sites at this landing
3409 // pad. The best solution is to fix the personality function.
3410 } else {
3411 // Pull the pointer for the reference type off.
3412 llvm::Type *PtrTy =
3413 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3414
3415 // Create the temporary and write the adjusted pointer into it.
3416 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3417 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3418 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3419
3420 // Bind the reference to the temporary.
3421 AdjustedExn = ExnPtrTmp;
3422 }
3423 }
3424
3425 llvm::Value *ExnCast =
3426 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3427 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3428 return;
3429 }
3430
3431 // Scalars and complexes.
3432 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3433 if (TEK != TEK_Aggregate) {
3434 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3435
3436 // If the catch type is a pointer type, __cxa_begin_catch returns
3437 // the pointer by value.
3438 if (CatchType->hasPointerRepresentation()) {
3439 llvm::Value *CastExn =
3440 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3441
3442 switch (CatchType.getQualifiers().getObjCLifetime()) {
3443 case Qualifiers::OCL_Strong:
3444 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3445 // fallthrough
3446
3447 case Qualifiers::OCL_None:
3448 case Qualifiers::OCL_ExplicitNone:
3449 case Qualifiers::OCL_Autoreleasing:
3450 CGF.Builder.CreateStore(CastExn, ParamAddr);
3451 return;
3452
3453 case Qualifiers::OCL_Weak:
3454 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3455 return;
3456 }
3457 llvm_unreachable("bad ownership qualifier!");
3458 }
3459
3460 // Otherwise, it returns a pointer into the exception object.
3461
3462 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3463 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3464
3465 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3466 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3467 CGF.getContext().getDeclAlign(&CatchParam));
3468 switch (TEK) {
3469 case TEK_Complex:
3470 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3471 /*init*/ true);
3472 return;
3473 case TEK_Scalar: {
3474 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3475 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3476 return;
3477 }
3478 case TEK_Aggregate:
3479 llvm_unreachable("evaluation kind filtered out!");
3480 }
3481 llvm_unreachable("bad evaluation kind");
3482 }
3483
3484 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3485
3486 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3487
3488 // Check for a copy expression. If we don't have a copy expression,
3489 // that means a trivial copy is okay.
3490 const Expr *copyExpr = CatchParam.getInit();
3491 if (!copyExpr) {
3492 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3493 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3494 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3495 return;
3496 }
3497
3498 // We have to call __cxa_get_exception_ptr to get the adjusted
3499 // pointer before copying.
3500 llvm::CallInst *rawAdjustedExn =
3501 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3502
3503 // Cast that to the appropriate type.
3504 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3505
3506 // The copy expression is defined in terms of an OpaqueValueExpr.
3507 // Find it and map it to the adjusted expression.
3508 CodeGenFunction::OpaqueValueMapping
3509 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3510 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3511
3512 // Call the copy ctor in a terminate scope.
3513 CGF.EHStack.pushTerminate();
3514
3515 // Perform the copy construction.
3516 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3517 CGF.EmitAggExpr(copyExpr,
3518 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3519 AggValueSlot::IsNotDestructed,
3520 AggValueSlot::DoesNotNeedGCBarriers,
3521 AggValueSlot::IsNotAliased));
3522
3523 // Leave the terminate scope.
3524 CGF.EHStack.popTerminate();
3525
3526 // Undo the opaque value mapping.
3527 opaque.pop();
3528
3529 // Finally we can call __cxa_begin_catch.
3530 CallBeginCatch(CGF, Exn, true);
3531}
3532
3533/// Begins a catch statement by initializing the catch variable and
3534/// calling __cxa_begin_catch.
3535void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3536 const CXXCatchStmt *S) {
3537 // We have to be very careful with the ordering of cleanups here:
3538 // C++ [except.throw]p4:
3539 // The destruction [of the exception temporary] occurs
3540 // immediately after the destruction of the object declared in
3541 // the exception-declaration in the handler.
3542 //
3543 // So the precise ordering is:
3544 // 1. Construct catch variable.
3545 // 2. __cxa_begin_catch
3546 // 3. Enter __cxa_end_catch cleanup
3547 // 4. Enter dtor cleanup
3548 //
3549 // We do this by using a slightly abnormal initialization process.
3550 // Delegation sequence:
3551 // - ExitCXXTryStmt opens a RunCleanupsScope
3552 // - EmitAutoVarAlloca creates the variable and debug info
3553 // - InitCatchParam initializes the variable from the exception
3554 // - CallBeginCatch calls __cxa_begin_catch
3555 // - CallBeginCatch enters the __cxa_end_catch cleanup
3556 // - EmitAutoVarCleanups enters the variable destructor cleanup
3557 // - EmitCXXTryStmt emits the code for the catch body
3558 // - EmitCXXTryStmt close the RunCleanupsScope
3559
3560 VarDecl *CatchParam = S->getExceptionDecl();
3561 if (!CatchParam) {
3562 llvm::Value *Exn = CGF.getExceptionFromSlot();
3563 CallBeginCatch(CGF, Exn, true);
3564 return;
3565 }
3566
3567 // Emit the local.
3568 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3569 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3570 CGF.EmitAutoVarCleanups(var);
3571}
3572
3573/// Get or define the following function:
3574/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3575/// This code is used only in C++.
3576static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3577 llvm::FunctionType *fnTy =
3578 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3579 llvm::Constant *fnRef =
3580 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3581
3582 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3583 if (fn && fn->empty()) {
3584 fn->setDoesNotThrow();
3585 fn->setDoesNotReturn();
3586
3587 // What we really want is to massively penalize inlining without
3588 // forbidding it completely. The difference between that and
3589 // 'noinline' is negligible.
3590 fn->addFnAttr(llvm::Attribute::NoInline);
3591
3592 // Allow this function to be shared across translation units, but
3593 // we don't want it to turn into an exported symbol.
3594 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3595 fn->setVisibility(llvm::Function::HiddenVisibility);
3596 if (CGM.supportsCOMDAT())
3597 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
3598
3599 // Set up the function.
3600 llvm::BasicBlock *entry =
3601 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3602 CGBuilderTy builder(entry);
3603
3604 // Pull the exception pointer out of the parameter list.
3605 llvm::Value *exn = &*fn->arg_begin();
3606
3607 // Call __cxa_begin_catch(exn).
3608 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3609 catchCall->setDoesNotThrow();
3610 catchCall->setCallingConv(CGM.getRuntimeCC());
3611
3612 // Call std::terminate().
3613 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
3614 termCall->setDoesNotThrow();
3615 termCall->setDoesNotReturn();
3616 termCall->setCallingConv(CGM.getRuntimeCC());
3617
3618 // std::terminate cannot return.
3619 builder.CreateUnreachable();
3620 }
3621
3622 return fnRef;
3623}
3624
3625llvm::CallInst *
3626ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3627 llvm::Value *Exn) {
3628 // In C++, we want to call __cxa_begin_catch() before terminating.
3629 if (Exn) {
3630 assert(CGF.CGM.getLangOpts().CPlusPlus);
3631 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3632 }
3633 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3634}