blob: f23cd9f9481ef39d1d8ea7a2dc0f48380e6285c5 [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;
Justin Bogner0729afa2015-03-17 22:31:34 +0000129 llvm::Constant *
130 getAddrOfCXXHandlerMapEntry(QualType Ty, QualType CatchHandlerType) override {
David Majnemer443250f2015-03-17 20:35:00 +0000131 return getAddrOfRTTIDescriptor(Ty);
132 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000133
David Majnemer1162d252014-06-22 19:05:33 +0000134 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
135 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
136 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
137 llvm::Value *ThisPtr,
138 llvm::Type *StdTypeInfoPtrTy) override;
139
140 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
141 QualType SrcRecordTy) override;
142
143 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
144 QualType SrcRecordTy, QualType DestTy,
145 QualType DestRecordTy,
146 llvm::BasicBlock *CastEnd) override;
147
148 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
149 QualType SrcRecordTy,
150 QualType DestTy) override;
151
152 bool EmitBadCastCall(CodeGenFunction &CGF) override;
153
Craig Topper4f12f102014-03-12 06:41:41 +0000154 llvm::Value *
155 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
156 const CXXRecordDecl *ClassDecl,
157 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000158
Craig Topper4f12f102014-03-12 06:41:41 +0000159 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000160
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000161 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
162 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000163
Reid Klecknere7de47e2013-07-22 13:51:44 +0000164 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000165 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000166 // Itanium does not emit any destructor variant as an inline thunk.
167 // Delegating may occur as an optimization, but all variants are either
168 // emitted with external linkage or as linkonce if they are inline and used.
169 return false;
170 }
171
Craig Topper4f12f102014-03-12 06:41:41 +0000172 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000173
Reid Kleckner89077a12013-12-17 19:46:40 +0000174 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000175 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000176
Craig Topper4f12f102014-03-12 06:41:41 +0000177 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000178
Reid Kleckner89077a12013-12-17 19:46:40 +0000179 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
180 const CXXConstructorDecl *D,
181 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000182 bool Delegating,
183 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000184
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000185 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
186 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000187 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000188
Craig Topper4f12f102014-03-12 06:41:41 +0000189 void emitVTableDefinitions(CodeGenVTables &CGVT,
190 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000191
192 llvm::Value *getVTableAddressPointInStructor(
193 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
194 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000195 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000196
197 llvm::Constant *
198 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000199 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000200
201 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000202 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000203
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000204 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000205 llvm::Value *This,
206 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000207
David Majnemer0c0b6d92014-10-31 20:09:12 +0000208 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
209 const CXXDestructorDecl *Dtor,
210 CXXDtorType DtorType,
211 llvm::Value *This,
212 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000213
Craig Topper4f12f102014-03-12 06:41:41 +0000214 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000215
Hans Wennborgc94391d2014-06-06 20:04:01 +0000216 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
217 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000218 // Allow inlining of thunks by emitting them with available_externally
219 // linkage together with vtables when needed.
220 if (ForVTable)
221 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
222 }
223
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000224 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000225 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000226
227 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000228 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000229
David Majnemer196ac332014-09-11 23:05:02 +0000230 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
231 FunctionArgList &Args) const override {
232 assert(!Args.empty() && "expected the arglist to not be empty!");
233 return Args.size() - 1;
234 }
235
Craig Topper4f12f102014-03-12 06:41:41 +0000236 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
237 StringRef GetDeletedVirtualCallName() override
238 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000239
Craig Topper4f12f102014-03-12 06:41:41 +0000240 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000241 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
242 llvm::Value *NewPtr,
243 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000244 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000245 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000246 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
247 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000248 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000249
John McCallcdf7ef52010-11-06 09:44:32 +0000250 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000251 llvm::GlobalVariable *DeclPtr,
252 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000253 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000254 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000255
256 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000257 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000258 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000259 CodeGenModule &CGM,
260 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
261 CXXThreadLocals,
262 ArrayRef<llvm::Function *> CXXThreadLocalInits,
263 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
264
265 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000266 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
267 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000268
Craig Topper4f12f102014-03-12 06:41:41 +0000269 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000270
271 /**************************** RTTI Uniqueness ******************************/
272
273protected:
274 /// Returns true if the ABI requires RTTI type_info objects to be unique
275 /// across a program.
276 virtual bool shouldRTTIBeUnique() const { return true; }
277
278public:
279 /// What sort of unique-RTTI behavior should we use?
280 enum RTTIUniquenessKind {
281 /// We are guaranteeing, or need to guarantee, that the RTTI string
282 /// is unique.
283 RUK_Unique,
284
285 /// We are not guaranteeing uniqueness for the RTTI string, so we
286 /// can demote to hidden visibility but must use string comparisons.
287 RUK_NonUniqueHidden,
288
289 /// We are not guaranteeing uniqueness for the RTTI string, so we
290 /// have to use string comparisons, but we also have to emit it with
291 /// non-hidden visibility.
292 RUK_NonUniqueVisible
293 };
294
295 /// Return the required visibility status for the given type and linkage in
296 /// the current ABI.
297 RTTIUniquenessKind
298 classifyRTTIUniqueness(QualType CanTy,
299 llvm::GlobalValue::LinkageTypes Linkage) const;
300 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000301
302 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000303};
John McCall86353412010-08-21 22:46:04 +0000304
305class ARMCXXABI : public ItaniumCXXABI {
306public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000307 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
308 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
309 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000310
Craig Topper4f12f102014-03-12 06:41:41 +0000311 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000312 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
313 isa<CXXDestructorDecl>(GD.getDecl()) &&
314 GD.getDtorType() != Dtor_Deleting));
315 }
John McCall5d865c322010-08-31 07:33:07 +0000316
Craig Topper4f12f102014-03-12 06:41:41 +0000317 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
318 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000319
Craig Topper4f12f102014-03-12 06:41:41 +0000320 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000321 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
322 llvm::Value *NewPtr,
323 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000324 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000325 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000326 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000327 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000328};
Tim Northovera2ee4332014-03-29 15:09:45 +0000329
330class iOS64CXXABI : public ARMCXXABI {
331public:
332 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000333
334 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000335 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000336};
Charles Davis4e786dd2010-05-25 19:52:27 +0000337}
338
Charles Davis53c59df2010-08-16 03:33:14 +0000339CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000340 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000341 // For IR-generation purposes, there's no significant difference
342 // between the ARM and iOS ABIs.
343 case TargetCXXABI::GenericARM:
344 case TargetCXXABI::iOS:
345 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000346
Tim Northovera2ee4332014-03-29 15:09:45 +0000347 case TargetCXXABI::iOS64:
348 return new iOS64CXXABI(CGM);
349
Tim Northover9bb857a2013-01-31 12:13:10 +0000350 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
351 // include the other 32-bit ARM oddities: constructor/destructor return values
352 // and array cookies.
353 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000354 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
355 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000356
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000357 case TargetCXXABI::GenericMIPS:
358 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
359
John McCall57625922013-01-25 23:36:14 +0000360 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000361 if (CGM.getContext().getTargetInfo().getTriple().getArch()
362 == llvm::Triple::le32) {
363 // For PNaCl, use ARM-style method pointers so that PNaCl code
364 // does not assume anything about the alignment of function
365 // pointers.
366 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
367 /* UseARMGuardVarABI = */ false);
368 }
John McCall57625922013-01-25 23:36:14 +0000369 return new ItaniumCXXABI(CGM);
370
371 case TargetCXXABI::Microsoft:
372 llvm_unreachable("Microsoft ABI is not Itanium-based");
373 }
374 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000375}
376
Chris Lattnera5f58b02011-07-09 17:41:47 +0000377llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000378ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
379 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000380 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000381 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000382}
383
John McCalld9c6c0b2010-08-22 00:59:17 +0000384/// In the Itanium and ARM ABIs, method pointers have the form:
385/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
386///
387/// In the Itanium ABI:
388/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
389/// - the this-adjustment is (memptr.adj)
390/// - the virtual offset is (memptr.ptr - 1)
391///
392/// In the ARM ABI:
393/// - method pointers are virtual if (memptr.adj & 1) is nonzero
394/// - the this-adjustment is (memptr.adj >> 1)
395/// - the virtual offset is (memptr.ptr)
396/// ARM uses 'adj' for the virtual flag because Thumb functions
397/// may be only single-byte aligned.
398///
399/// If the member is virtual, the adjusted 'this' pointer points
400/// to a vtable pointer from which the virtual offset is applied.
401///
402/// If the member is non-virtual, memptr.ptr is the address of
403/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000404llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
405 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
406 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000407 CGBuilderTy &Builder = CGF.Builder;
408
409 const FunctionProtoType *FPT =
410 MPT->getPointeeType()->getAs<FunctionProtoType>();
411 const CXXRecordDecl *RD =
412 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
413
Chris Lattner2192fe52011-07-18 04:24:23 +0000414 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000415 CGM.getTypes().GetFunctionType(
416 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000417
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000418 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000419
John McCalld9c6c0b2010-08-22 00:59:17 +0000420 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
421 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
422 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
423
John McCalla1dee5302010-08-22 10:59:02 +0000424 // Extract memptr.adj, which is in the second field.
425 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000426
427 // Compute the true adjustment.
428 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000429 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000430 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000431
432 // Apply the adjustment and cast back to the original struct type
433 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000434 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
435 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
436 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000437
438 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000439 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000440
441 // If the LSB in the function pointer is 1, the function pointer points to
442 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000443 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000444 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000445 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
446 else
447 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
448 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000449 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
450
451 // In the virtual path, the adjustment left 'This' pointing to the
452 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000453 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000454 CGF.EmitBlock(FnVirtual);
455
456 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000457 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000458 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000459
460 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000461 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000462 if (!UseARMMethodPtrABI)
463 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000464 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000465
466 // Load the virtual function to call.
467 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000468 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000469 CGF.EmitBranch(FnEnd);
470
471 // In the non-virtual path, the function pointer is actually a
472 // function pointer.
473 CGF.EmitBlock(FnNonVirtual);
474 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000475 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000476
477 // We're done.
478 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000479 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000480 Callee->addIncoming(VirtualFn, FnVirtual);
481 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
482 return Callee;
483}
John McCalla8bbb822010-08-22 03:04:22 +0000484
John McCallc134eb52010-08-31 21:07:20 +0000485/// Compute an l-value by applying the given pointer-to-member to a
486/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000487llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
488 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
489 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000490 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000491
492 CGBuilderTy &Builder = CGF.Builder;
493
Micah Villmowea2fea22012-10-25 15:39:14 +0000494 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000495
496 // Cast to char*.
497 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
498
499 // Apply the offset, which we assume is non-null.
500 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
501
502 // Cast the address to the appropriate pointer type, adopting the
503 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000504 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000505 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000506 return Builder.CreateBitCast(Addr, PType);
507}
508
John McCallc62bb392012-02-15 01:22:51 +0000509/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
510/// conversion.
511///
512/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000513///
514/// Obligatory offset/adjustment diagram:
515/// <-- offset --> <-- adjustment -->
516/// |--------------------------|----------------------|--------------------|
517/// ^Derived address point ^Base address point ^Member address point
518///
519/// So when converting a base member pointer to a derived member pointer,
520/// we add the offset to the adjustment because the address point has
521/// decreased; and conversely, when converting a derived MP to a base MP
522/// we subtract the offset from the adjustment because the address point
523/// has increased.
524///
525/// The standard forbids (at compile time) conversion to and from
526/// virtual bases, which is why we don't have to consider them here.
527///
528/// The standard forbids (at run time) casting a derived MP to a base
529/// MP when the derived MP does not point to a member of the base.
530/// This is why -1 is a reasonable choice for null data member
531/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000532llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000533ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
534 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000535 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000536 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000537 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
538 E->getCastKind() == CK_ReinterpretMemberPointer);
539
540 // Under Itanium, reinterprets don't require any additional processing.
541 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
542
543 // Use constant emission if we can.
544 if (isa<llvm::Constant>(src))
545 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
546
547 llvm::Constant *adj = getMemberPointerAdjustment(E);
548 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000549
550 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000551 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000552
John McCallc62bb392012-02-15 01:22:51 +0000553 const MemberPointerType *destTy =
554 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000555
John McCall7a9aac22010-08-23 01:21:21 +0000556 // For member data pointers, this is just a matter of adding the
557 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000558 if (destTy->isMemberDataPointer()) {
559 llvm::Value *dst;
560 if (isDerivedToBase)
561 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000562 else
John McCallc62bb392012-02-15 01:22:51 +0000563 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000564
565 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000566 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
567 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
568 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000569 }
570
John McCalla1dee5302010-08-22 10:59:02 +0000571 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000572 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000573 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
574 offset <<= 1;
575 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000576 }
577
John McCallc62bb392012-02-15 01:22:51 +0000578 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
579 llvm::Value *dstAdj;
580 if (isDerivedToBase)
581 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000582 else
John McCallc62bb392012-02-15 01:22:51 +0000583 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000584
John McCallc62bb392012-02-15 01:22:51 +0000585 return Builder.CreateInsertValue(src, dstAdj, 1);
586}
587
588llvm::Constant *
589ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
590 llvm::Constant *src) {
591 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
592 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
593 E->getCastKind() == CK_ReinterpretMemberPointer);
594
595 // Under Itanium, reinterprets don't require any additional processing.
596 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
597
598 // If the adjustment is trivial, we don't need to do anything.
599 llvm::Constant *adj = getMemberPointerAdjustment(E);
600 if (!adj) return src;
601
602 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
603
604 const MemberPointerType *destTy =
605 E->getType()->castAs<MemberPointerType>();
606
607 // For member data pointers, this is just a matter of adding the
608 // offset if the source is non-null.
609 if (destTy->isMemberDataPointer()) {
610 // null maps to null.
611 if (src->isAllOnesValue()) return src;
612
613 if (isDerivedToBase)
614 return llvm::ConstantExpr::getNSWSub(src, adj);
615 else
616 return llvm::ConstantExpr::getNSWAdd(src, adj);
617 }
618
619 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000620 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000621 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
622 offset <<= 1;
623 adj = llvm::ConstantInt::get(adj->getType(), offset);
624 }
625
626 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
627 llvm::Constant *dstAdj;
628 if (isDerivedToBase)
629 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
630 else
631 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
632
633 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000634}
John McCall84fa5102010-08-22 04:16:24 +0000635
636llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000637ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000638 // Itanium C++ ABI 2.3:
639 // A NULL pointer is represented as -1.
640 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000641 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000642
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000643 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000644 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000645 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000646}
647
John McCallf3a88602011-02-03 08:15:49 +0000648llvm::Constant *
649ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
650 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000651 // Itanium C++ ABI 2.3:
652 // A pointer to data member is an offset from the base address of
653 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000654 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000655}
656
John McCall2979fe02011-04-12 00:42:48 +0000657llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000658 return BuildMemberPointer(MD, CharUnits::Zero());
659}
660
661llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
662 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000663 assert(MD->isInstance() && "Member function must not be static!");
664 MD = MD->getCanonicalDecl();
665
666 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000667
668 // Get the function pointer (or index if this is a virtual function).
669 llvm::Constant *MemPtr[2];
670 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000671 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000672
Ken Dyckdf016282011-04-09 01:30:02 +0000673 const ASTContext &Context = getContext();
674 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000675 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000676 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000677
Mark Seabornedf0d382013-07-24 16:25:13 +0000678 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000679 // ARM C++ ABI 3.2.1:
680 // This ABI specifies that adj contains twice the this
681 // adjustment, plus 1 if the member function is virtual. The
682 // least significant bit of adj then makes exactly the same
683 // discrimination as the least significant bit of ptr does for
684 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000685 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
686 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000687 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000688 } else {
689 // Itanium C++ ABI 2.3:
690 // For a virtual function, [the pointer field] is 1 plus the
691 // virtual table offset (in bytes) of the function,
692 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000693 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
694 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000695 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000696 }
697 } else {
John McCall2979fe02011-04-12 00:42:48 +0000698 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000699 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000700 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000701 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000702 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000703 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000704 } else {
John McCall2979fe02011-04-12 00:42:48 +0000705 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
706 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000707 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000708 }
John McCall2979fe02011-04-12 00:42:48 +0000709 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000710
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000711 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000712 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
713 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000714 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000715 }
John McCall1c456c82010-08-22 06:43:33 +0000716
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000717 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000718}
719
Richard Smithdafff942012-01-14 04:30:29 +0000720llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
721 QualType MPType) {
722 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
723 const ValueDecl *MPD = MP.getMemberPointerDecl();
724 if (!MPD)
725 return EmitNullMemberPointer(MPT);
726
Reid Kleckner452abac2013-05-09 21:01:17 +0000727 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000728
729 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
730 return BuildMemberPointer(MD, ThisAdjustment);
731
732 CharUnits FieldOffset =
733 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
734 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
735}
736
John McCall131d97d2010-08-22 08:30:07 +0000737/// The comparison algorithm is pretty easy: the member pointers are
738/// the same if they're either bitwise identical *or* both null.
739///
740/// ARM is different here only because null-ness is more complicated.
741llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000742ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
743 llvm::Value *L,
744 llvm::Value *R,
745 const MemberPointerType *MPT,
746 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000747 CGBuilderTy &Builder = CGF.Builder;
748
John McCall131d97d2010-08-22 08:30:07 +0000749 llvm::ICmpInst::Predicate Eq;
750 llvm::Instruction::BinaryOps And, Or;
751 if (Inequality) {
752 Eq = llvm::ICmpInst::ICMP_NE;
753 And = llvm::Instruction::Or;
754 Or = llvm::Instruction::And;
755 } else {
756 Eq = llvm::ICmpInst::ICMP_EQ;
757 And = llvm::Instruction::And;
758 Or = llvm::Instruction::Or;
759 }
760
John McCall7a9aac22010-08-23 01:21:21 +0000761 // Member data pointers are easy because there's a unique null
762 // value, so it just comes down to bitwise equality.
763 if (MPT->isMemberDataPointer())
764 return Builder.CreateICmp(Eq, L, R);
765
766 // For member function pointers, the tautologies are more complex.
767 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000768 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000769 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000770 // (L == R) <==> (L.ptr == R.ptr &&
771 // (L.adj == R.adj ||
772 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000773 // The inequality tautologies have exactly the same structure, except
774 // applying De Morgan's laws.
775
776 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
777 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
778
John McCall131d97d2010-08-22 08:30:07 +0000779 // This condition tests whether L.ptr == R.ptr. This must always be
780 // true for equality to hold.
781 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
782
783 // This condition, together with the assumption that L.ptr == R.ptr,
784 // tests whether the pointers are both null. ARM imposes an extra
785 // condition.
786 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
787 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
788
789 // This condition tests whether L.adj == R.adj. If this isn't
790 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000791 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
792 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000793 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
794
795 // Null member function pointers on ARM clear the low bit of Adj,
796 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000797 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000798 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
799
800 // Compute (l.adj | r.adj) & 1 and test it against zero.
801 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
802 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
803 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
804 "cmp.or.adj");
805 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
806 }
807
808 // Tie together all our conditions.
809 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
810 Result = Builder.CreateBinOp(And, PtrEq, Result,
811 Inequality ? "memptr.ne" : "memptr.eq");
812 return Result;
813}
814
815llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000816ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
817 llvm::Value *MemPtr,
818 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000819 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000820
821 /// For member data pointers, this is just a check against -1.
822 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000823 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000824 llvm::Value *NegativeOne =
825 llvm::Constant::getAllOnesValue(MemPtr->getType());
826 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
827 }
John McCall131d97d2010-08-22 08:30:07 +0000828
Daniel Dunbar914bc412011-04-19 23:10:47 +0000829 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000830 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000831
832 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
833 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
834
Daniel Dunbar914bc412011-04-19 23:10:47 +0000835 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
836 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000837 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000838 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000839 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000840 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000841 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
842 "memptr.isvirtual");
843 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000844 }
845
846 return Result;
847}
John McCall1c456c82010-08-22 06:43:33 +0000848
Reid Kleckner40ca9132014-05-13 22:05:45 +0000849bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
850 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
851 if (!RD)
852 return false;
853
Reid Klecknerd355ca72014-05-15 01:26:32 +0000854 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
855 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
856 // special members.
857 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000858 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
859 return true;
860 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000861 return false;
862}
863
John McCall614dbdc2010-08-22 21:01:12 +0000864/// The Itanium ABI requires non-zero initialization only for data
865/// member pointers, for which '0' is a valid offset.
866bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
867 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000868}
John McCall5d865c322010-08-31 07:33:07 +0000869
John McCall82fb8922012-09-25 10:10:39 +0000870/// The Itanium ABI always places an offset to the complete object
871/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000872void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
873 const CXXDeleteExpr *DE,
874 llvm::Value *Ptr,
875 QualType ElementType,
876 const CXXDestructorDecl *Dtor) {
877 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000878 if (UseGlobalDelete) {
879 // Derive the complete-object pointer, which is what we need
880 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000881
David Majnemer0c0b6d92014-10-31 20:09:12 +0000882 // Grab the vtable pointer as an intptr_t*.
883 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000884
David Majnemer0c0b6d92014-10-31 20:09:12 +0000885 // Track back to entry -2 and pull out the offset there.
886 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
887 VTable, -2, "complete-offset.ptr");
888 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
889 Offset->setAlignment(CGF.PointerAlignInBytes);
890
891 // Apply the offset.
892 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
893 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
894
895 // If we're supposed to call the global delete, make sure we do so
896 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000897 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
898 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000899 }
900
901 // FIXME: Provide a source location here even though there's no
902 // CXXMemberCallExpr for dtor call.
903 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
904 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
905
906 if (UseGlobalDelete)
907 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000908}
909
David Majnemer442d0a22014-11-25 07:20:20 +0000910void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
911 // void __cxa_rethrow();
912
913 llvm::FunctionType *FTy =
914 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
915
916 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
917
918 if (isNoReturn)
919 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
920 else
921 CGF.EmitRuntimeCallOrInvoke(Fn);
922}
923
David Majnemer7c237072015-03-05 00:46:22 +0000924static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
925 // void *__cxa_allocate_exception(size_t thrown_size);
926
927 llvm::FunctionType *FTy =
928 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
929
930 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
931}
932
933static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
934 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
935 // void (*dest) (void *));
936
937 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
938 llvm::FunctionType *FTy =
939 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
940
941 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
942}
943
944void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
945 QualType ThrowType = E->getSubExpr()->getType();
946 // Now allocate the exception object.
947 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
948 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
949
950 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
951 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
952 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
953
954 CGF.EmitAnyExprToExn(E->getSubExpr(), ExceptionPtr);
955
956 // Now throw the exception.
957 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
958 /*ForEH=*/true);
959
960 // The address of the destructor. If the exception type has a
961 // trivial destructor (or isn't a record), we just pass null.
962 llvm::Constant *Dtor = nullptr;
963 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
964 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
965 if (!Record->hasTrivialDestructor()) {
966 CXXDestructorDecl *DtorD = Record->getDestructor();
967 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
968 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
969 }
970 }
971 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
972
973 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
974 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
975}
976
David Majnemer1162d252014-06-22 19:05:33 +0000977static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
978 // void *__dynamic_cast(const void *sub,
979 // const abi::__class_type_info *src,
980 // const abi::__class_type_info *dst,
981 // std::ptrdiff_t src2dst_offset);
982
983 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
984 llvm::Type *PtrDiffTy =
985 CGF.ConvertType(CGF.getContext().getPointerDiffType());
986
987 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
988
989 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
990
991 // Mark the function as nounwind readonly.
992 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
993 llvm::Attribute::ReadOnly };
994 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
995 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
996
997 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
998}
999
1000static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1001 // void __cxa_bad_cast();
1002 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1003 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1004}
1005
1006/// \brief Compute the src2dst_offset hint as described in the
1007/// Itanium C++ ABI [2.9.7]
1008static CharUnits computeOffsetHint(ASTContext &Context,
1009 const CXXRecordDecl *Src,
1010 const CXXRecordDecl *Dst) {
1011 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1012 /*DetectVirtual=*/false);
1013
1014 // If Dst is not derived from Src we can skip the whole computation below and
1015 // return that Src is not a public base of Dst. Record all inheritance paths.
1016 if (!Dst->isDerivedFrom(Src, Paths))
1017 return CharUnits::fromQuantity(-2ULL);
1018
1019 unsigned NumPublicPaths = 0;
1020 CharUnits Offset;
1021
1022 // Now walk all possible inheritance paths.
1023 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
1024 ++I) {
1025 if (I->Access != AS_public) // Ignore non-public inheritance.
1026 continue;
1027
1028 ++NumPublicPaths;
1029
1030 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
1031 // If the path contains a virtual base class we can't give any hint.
1032 // -1: no hint.
1033 if (J->Base->isVirtual())
1034 return CharUnits::fromQuantity(-1ULL);
1035
1036 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1037 continue;
1038
1039 // Accumulate the base class offsets.
1040 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
1041 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
1042 }
1043 }
1044
1045 // -2: Src is not a public base of Dst.
1046 if (NumPublicPaths == 0)
1047 return CharUnits::fromQuantity(-2ULL);
1048
1049 // -3: Src is a multiple public base type but never a virtual base type.
1050 if (NumPublicPaths > 1)
1051 return CharUnits::fromQuantity(-3ULL);
1052
1053 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1054 // Return the offset of Src from the origin of Dst.
1055 return Offset;
1056}
1057
1058static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1059 // void __cxa_bad_typeid();
1060 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1061
1062 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1063}
1064
1065bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1066 QualType SrcRecordTy) {
1067 return IsDeref;
1068}
1069
1070void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1071 llvm::Value *Fn = getBadTypeidFn(CGF);
1072 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1073 CGF.Builder.CreateUnreachable();
1074}
1075
1076llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1077 QualType SrcRecordTy,
1078 llvm::Value *ThisPtr,
1079 llvm::Type *StdTypeInfoPtrTy) {
1080 llvm::Value *Value =
1081 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1082
1083 // Load the type info.
1084 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1085 return CGF.Builder.CreateLoad(Value);
1086}
1087
1088bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1089 QualType SrcRecordTy) {
1090 return SrcIsPtr;
1091}
1092
1093llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1094 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1095 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1096 llvm::Type *PtrDiffLTy =
1097 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1098 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1099
1100 llvm::Value *SrcRTTI =
1101 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1102 llvm::Value *DestRTTI =
1103 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1104
1105 // Compute the offset hint.
1106 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1107 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1108 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1109 PtrDiffLTy,
1110 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1111
1112 // Emit the call to __dynamic_cast.
1113 Value = CGF.EmitCastToVoidPtr(Value);
1114
1115 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1116 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1117 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1118
1119 /// C++ [expr.dynamic.cast]p9:
1120 /// A failed cast to reference type throws std::bad_cast
1121 if (DestTy->isReferenceType()) {
1122 llvm::BasicBlock *BadCastBlock =
1123 CGF.createBasicBlock("dynamic_cast.bad_cast");
1124
1125 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1126 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1127
1128 CGF.EmitBlock(BadCastBlock);
1129 EmitBadCastCall(CGF);
1130 }
1131
1132 return Value;
1133}
1134
1135llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1136 llvm::Value *Value,
1137 QualType SrcRecordTy,
1138 QualType DestTy) {
1139 llvm::Type *PtrDiffLTy =
1140 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1141 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1142
1143 // Get the vtable pointer.
1144 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1145
1146 // Get the offset-to-top from the vtable.
1147 llvm::Value *OffsetToTop =
1148 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1149 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1150
1151 // Finally, add the offset to the pointer.
1152 Value = CGF.EmitCastToVoidPtr(Value);
1153 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1154
1155 return CGF.Builder.CreateBitCast(Value, DestLTy);
1156}
1157
1158bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1159 llvm::Value *Fn = getBadCastFn(CGF);
1160 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1161 CGF.Builder.CreateUnreachable();
1162 return true;
1163}
1164
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001165llvm::Value *
1166ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1167 llvm::Value *This,
1168 const CXXRecordDecl *ClassDecl,
1169 const CXXRecordDecl *BaseClassDecl) {
1170 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1171 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001172 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1173 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001174
1175 llvm::Value *VBaseOffsetPtr =
1176 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1177 "vbase.offset.ptr");
1178 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1179 CGM.PtrDiffTy->getPointerTo());
1180
1181 llvm::Value *VBaseOffset =
1182 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1183
1184 return VBaseOffset;
1185}
1186
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001187void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1188 // Just make sure we're in sync with TargetCXXABI.
1189 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1190
Rafael Espindolac3cde362013-12-09 14:51:17 +00001191 // The constructor used for constructing this as a base class;
1192 // ignores virtual bases.
1193 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1194
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001195 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001196 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001197 if (!D->getParent()->isAbstract()) {
1198 // We don't need to emit the complete ctor if the class is abstract.
1199 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1200 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001201}
1202
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001203void
1204ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1205 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001206 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001207
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001208 // All parameters are already in place except VTT, which goes after 'this'.
1209 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001210
1211 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001212 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1213 ArgTys.insert(ArgTys.begin() + 1,
1214 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001215}
1216
Reid Klecknere7de47e2013-07-22 13:51:44 +00001217void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001218 // The destructor used for destructing this as a base class; ignores
1219 // virtual bases.
1220 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001221
1222 // The destructor used for destructing this as a most-derived class;
1223 // call the base destructor and then destructs any virtual bases.
1224 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1225
Rafael Espindolac3cde362013-12-09 14:51:17 +00001226 // The destructor in a virtual table is always a 'deleting'
1227 // destructor, which calls the complete destructor and then uses the
1228 // appropriate operator delete.
1229 if (D->isVirtual())
1230 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001231}
1232
Reid Kleckner89077a12013-12-17 19:46:40 +00001233void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1234 QualType &ResTy,
1235 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001236 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001237 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001238
1239 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001240 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001241 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001242
1243 // FIXME: avoid the fake decl
1244 QualType T = Context.getPointerType(Context.VoidPtrTy);
1245 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001246 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001247 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001248 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001249 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001250 }
1251}
1252
John McCall5d865c322010-08-31 07:33:07 +00001253void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1254 /// Initialize the 'this' slot.
1255 EmitThisParam(CGF);
1256
1257 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001258 if (getStructorImplicitParamDecl(CGF)) {
1259 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1260 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001261 }
John McCall5d865c322010-08-31 07:33:07 +00001262
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001263 /// If this is a function that the ABI specifies returns 'this', initialize
1264 /// the return slot to 'this' at the start of the function.
1265 ///
1266 /// Unlike the setting of return types, this is done within the ABI
1267 /// implementation instead of by clients of CGCXXABI because:
1268 /// 1) getThisValue is currently protected
1269 /// 2) in theory, an ABI could implement 'this' returns some other way;
1270 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001271 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001272 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001273}
1274
Reid Kleckner89077a12013-12-17 19:46:40 +00001275unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1276 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1277 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1278 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1279 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001280
Reid Kleckner89077a12013-12-17 19:46:40 +00001281 // Insert the implicit 'vtt' argument as the second argument.
1282 llvm::Value *VTT =
1283 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1284 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1285 Args.insert(Args.begin() + 1,
1286 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1287 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001288}
1289
1290void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1291 const CXXDestructorDecl *DD,
1292 CXXDtorType Type, bool ForVirtualBase,
1293 bool Delegating, llvm::Value *This) {
1294 GlobalDecl GD(DD, Type);
1295 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1296 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1297
Craig Topper8a13c412014-05-21 05:09:00 +00001298 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001299 if (getContext().getLangOpts().AppleKext)
1300 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1301
1302 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001303 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001304
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001305 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1306 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001307}
1308
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001309void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1310 const CXXRecordDecl *RD) {
1311 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1312 if (VTable->hasInitializer())
1313 return;
1314
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001315 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001316 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1317 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001318 llvm::Constant *RTTI =
1319 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001320
1321 // Create and set the initializer.
1322 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1323 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001324 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001325 VTable->setInitializer(Init);
1326
1327 // Set the correct linkage.
1328 VTable->setLinkage(Linkage);
1329
Rafael Espindolacb92c192015-01-15 23:18:01 +00001330 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1331 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
1332
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001333 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001334 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001335
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001336 // Use pointer alignment for the vtable. Otherwise we would align them based
1337 // on the size of the initializer which doesn't make sense as only single
1338 // values are read.
1339 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1340 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1341
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001342 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1343 // we will emit the typeinfo for the fundamental types. This is the
1344 // same behaviour as GCC.
1345 const DeclContext *DC = RD->getDeclContext();
1346 if (RD->getIdentifier() &&
1347 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1348 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1349 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1350 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001351 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001352
1353 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001354}
1355
1356llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1357 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1358 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1359 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1360 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1361
1362 llvm::Value *VTableAddressPoint;
1363 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1364 // Get the secondary vpointer index.
1365 uint64_t VirtualPointerIndex =
1366 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1367
1368 /// Load the VTT.
1369 llvm::Value *VTT = CGF.LoadCXXVTT();
1370 if (VirtualPointerIndex)
1371 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1372
1373 // And load the address point from the VTT.
1374 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1375 } else {
1376 llvm::Constant *VTable =
1377 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001378 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1379 .getVTableLayout(VTableClass)
1380 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001381 VTableAddressPoint =
1382 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1383 }
1384
1385 return VTableAddressPoint;
1386}
1387
1388llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1389 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1390 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1391
1392 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001393 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1394 .getVTableLayout(VTableClass)
1395 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001396 llvm::Value *Indices[] = {
1397 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1398 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1399 };
1400
1401 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1402}
1403
1404llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1405 CharUnits VPtrOffset) {
1406 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1407
1408 llvm::GlobalVariable *&VTable = VTables[RD];
1409 if (VTable)
1410 return VTable;
1411
1412 // Queue up this v-table for possible deferred emission.
1413 CGM.addDeferredVTable(RD);
1414
1415 SmallString<256> OutName;
1416 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001417 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001418 Out.flush();
1419 StringRef Name = OutName.str();
1420
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001421 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001422 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1423 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1424
1425 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1426 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1427 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001428
1429 if (RD->hasAttr<DLLImportAttr>())
1430 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1431 else if (RD->hasAttr<DLLExportAttr>())
1432 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1433
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001434 return VTable;
1435}
1436
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001437llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1438 GlobalDecl GD,
1439 llvm::Value *This,
1440 llvm::Type *Ty) {
1441 GD = GD.getCanonicalDecl();
1442 Ty = Ty->getPointerTo()->getPointerTo();
1443 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1444
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001445 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable);
1446
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001447 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001448 llvm::Value *VFuncPtr =
1449 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1450 return CGF.Builder.CreateLoad(VFuncPtr);
1451}
1452
David Majnemer0c0b6d92014-10-31 20:09:12 +00001453llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1454 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1455 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001456 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001457 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1458
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001459 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1460 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001461 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001462 llvm::Value *Callee =
1463 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001464
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001465 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1466 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001467 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001468}
1469
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001470void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001471 CodeGenVTables &VTables = CGM.getVTables();
1472 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001473 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001474}
1475
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001476static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1477 llvm::Value *Ptr,
1478 int64_t NonVirtualAdjustment,
1479 int64_t VirtualAdjustment,
1480 bool IsReturnAdjustment) {
1481 if (!NonVirtualAdjustment && !VirtualAdjustment)
1482 return Ptr;
1483
1484 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1485 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1486
1487 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1488 // Perform the non-virtual adjustment for a base-to-derived cast.
1489 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1490 }
1491
1492 if (VirtualAdjustment) {
1493 llvm::Type *PtrDiffTy =
1494 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1495
1496 // Perform the virtual adjustment.
1497 llvm::Value *VTablePtrPtr =
1498 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1499
1500 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1501
1502 llvm::Value *OffsetPtr =
1503 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1504
1505 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1506
1507 // Load the adjustment offset from the vtable.
1508 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1509
1510 // Adjust our pointer.
1511 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1512 }
1513
1514 if (NonVirtualAdjustment && IsReturnAdjustment) {
1515 // Perform the non-virtual adjustment for a derived-to-base cast.
1516 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1517 }
1518
1519 // Cast back to the original type.
1520 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1521}
1522
1523llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1524 llvm::Value *This,
1525 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001526 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1527 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001528 /*IsReturnAdjustment=*/false);
1529}
1530
1531llvm::Value *
1532ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1533 const ReturnAdjustment &RA) {
1534 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1535 RA.Virtual.Itanium.VBaseOffsetOffset,
1536 /*IsReturnAdjustment=*/true);
1537}
1538
John McCall5d865c322010-08-31 07:33:07 +00001539void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1540 RValue RV, QualType ResultType) {
1541 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1542 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1543
1544 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001545 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001546 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1547 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1548 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1549}
John McCall8ed55a52010-09-02 09:58:18 +00001550
1551/************************** Array allocation cookies **************************/
1552
John McCallb91cd662012-05-01 05:23:51 +00001553CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1554 // The array cookie is a size_t; pad that up to the element alignment.
1555 // The cookie is actually right-justified in that space.
1556 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1557 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001558}
1559
1560llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1561 llvm::Value *NewPtr,
1562 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001563 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001564 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001565 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001566
Micah Villmowea2fea22012-10-25 15:39:14 +00001567 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001568
John McCall9bca9232010-09-02 10:25:57 +00001569 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001570 QualType SizeTy = Ctx.getSizeType();
1571 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1572
1573 // The size of the cookie.
1574 CharUnits CookieSize =
1575 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001576 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001577
1578 // Compute an offset to the cookie.
1579 llvm::Value *CookiePtr = NewPtr;
1580 CharUnits CookieOffset = CookieSize - SizeSize;
1581 if (!CookieOffset.isZero())
1582 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1583 CookieOffset.getQuantity());
1584
1585 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001586 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1587 llvm::Value *NumElementsPtr =
1588 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1589 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001590 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001591 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001592 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001593 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1594 llvm::FunctionType *FTy =
1595 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1596 llvm::Constant *F =
1597 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1598 CGF.Builder.CreateCall(F, NumElementsPtr);
1599 }
John McCall8ed55a52010-09-02 09:58:18 +00001600
1601 // Finally, compute a pointer to the actual data buffer by skipping
1602 // over the cookie completely.
1603 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1604 CookieSize.getQuantity());
1605}
1606
John McCallb91cd662012-05-01 05:23:51 +00001607llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1608 llvm::Value *allocPtr,
1609 CharUnits cookieSize) {
1610 // The element size is right-justified in the cookie.
1611 llvm::Value *numElementsPtr = allocPtr;
1612 CharUnits numElementsOffset =
1613 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1614 if (!numElementsOffset.isZero())
1615 numElementsPtr =
1616 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1617 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001618
Micah Villmowea2fea22012-10-25 15:39:14 +00001619 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001620 numElementsPtr =
1621 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001622 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001623 return CGF.Builder.CreateLoad(numElementsPtr);
1624 // In asan mode emit a function call instead of a regular load and let the
1625 // run-time deal with it: if the shadow is properly poisoned return the
1626 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1627 // We can't simply ignore this load using nosanitize metadata because
1628 // the metadata may be lost.
1629 llvm::FunctionType *FTy =
1630 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1631 llvm::Constant *F =
1632 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1633 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001634}
1635
John McCallb91cd662012-05-01 05:23:51 +00001636CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001637 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001638 // struct array_cookie {
1639 // std::size_t element_size; // element_size != 0
1640 // std::size_t element_count;
1641 // };
John McCallc19c7062013-01-25 23:36:19 +00001642 // But the base ABI doesn't give anything an alignment greater than
1643 // 8, so we can dismiss this as typical ABI-author blindness to
1644 // actual language complexity and round up to the element alignment.
1645 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1646 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001647}
1648
1649llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001650 llvm::Value *newPtr,
1651 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001652 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001653 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001654 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001655
John McCallc19c7062013-01-25 23:36:19 +00001656 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1657 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001658
1659 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001660 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001661
1662 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001663 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1664 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1665 getContext().getTypeSizeInChars(elementType).getQuantity());
1666 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001667
1668 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001669 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1670 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001671
1672 // Finally, compute a pointer to the actual data buffer by skipping
1673 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001674 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1675 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1676 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001677}
1678
John McCallb91cd662012-05-01 05:23:51 +00001679llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1680 llvm::Value *allocPtr,
1681 CharUnits cookieSize) {
1682 // The number of elements is at offset sizeof(size_t) relative to
1683 // the allocated pointer.
1684 llvm::Value *numElementsPtr
1685 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001686
Micah Villmowea2fea22012-10-25 15:39:14 +00001687 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001688 numElementsPtr =
1689 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1690 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001691}
1692
John McCall68ff0372010-09-08 01:44:27 +00001693/*********************** Static local initialization **************************/
1694
1695static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001696 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001697 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001698 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001699 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001700 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001701 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001702 llvm::AttributeSet::get(CGM.getLLVMContext(),
1703 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001704 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001705}
1706
1707static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001708 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001709 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001710 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001711 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001712 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001713 llvm::AttributeSet::get(CGM.getLLVMContext(),
1714 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001715 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001716}
1717
1718static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001719 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001720 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001721 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001722 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001723 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001724 llvm::AttributeSet::get(CGM.getLLVMContext(),
1725 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001726 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001727}
1728
1729namespace {
1730 struct CallGuardAbort : EHScopeStack::Cleanup {
1731 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001732 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001733
Craig Topper4f12f102014-03-12 06:41:41 +00001734 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001735 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1736 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001737 }
1738 };
1739}
1740
1741/// The ARM code here follows the Itanium code closely enough that we
1742/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001743void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1744 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001745 llvm::GlobalVariable *var,
1746 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001747 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001748
Richard Smithdbf74ba2013-04-14 23:01:42 +00001749 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001750 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001751 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1752 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001753
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001754 // If we have a global variable with internal linkage and thread-safe statics
1755 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001756 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1757
1758 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001759 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001760 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001761 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001762 // Guard variables are 64 bits in the generic ABI and size width on ARM
1763 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001764 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001765 }
John McCallb88a5662012-03-30 21:00:39 +00001766 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001767
John McCallb88a5662012-03-30 21:00:39 +00001768 // Create the guard variable if we don't already have it (as we
1769 // might if we're double-emitting this function body).
1770 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1771 if (!guard) {
1772 // Mangle the name for the guard.
1773 SmallString<256> guardName;
1774 {
1775 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001776 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001777 out.flush();
1778 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001779
John McCallb88a5662012-03-30 21:00:39 +00001780 // Create the guard variable with a zero-initializer.
1781 // Just absorb linkage and visibility from the guarded variable.
1782 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1783 false, var->getLinkage(),
1784 llvm::ConstantInt::get(guardTy, 0),
1785 guardName.str());
1786 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001787 // If the variable is thread-local, so is its guard variable.
1788 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001789
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001790 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1791 // as the associated data object
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001792 llvm::Comdat *C = var->getComdat();
1793 if (!D.isLocalVarDecl() && C) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001794 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001795 CGF.CurFn->setComdat(C);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001796 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1797 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001798 }
1799
John McCallb88a5662012-03-30 21:00:39 +00001800 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1801 }
John McCall87590e62012-03-30 07:09:50 +00001802
John McCall68ff0372010-09-08 01:44:27 +00001803 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001804 //
John McCall68ff0372010-09-08 01:44:27 +00001805 // Itanium C++ ABI 3.3.2:
1806 // The following is pseudo-code showing how these functions can be used:
1807 // if (obj_guard.first_byte == 0) {
1808 // if ( __cxa_guard_acquire (&obj_guard) ) {
1809 // try {
1810 // ... initialize the object ...;
1811 // } catch (...) {
1812 // __cxa_guard_abort (&obj_guard);
1813 // throw;
1814 // }
1815 // ... queue object destructor with __cxa_atexit() ...;
1816 // __cxa_guard_release (&obj_guard);
1817 // }
1818 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001819
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001820 // Load the first byte of the guard variable.
1821 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001822 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001823 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001824
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001825 // Itanium ABI:
1826 // An implementation supporting thread-safety on multiprocessor
1827 // systems must also guarantee that references to the initialized
1828 // object do not occur before the load of the initialization flag.
1829 //
1830 // In LLVM, we do this by marking the load Acquire.
1831 if (threadsafe)
1832 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001833
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001834 // For ARM, we should only check the first bit, rather than the entire byte:
1835 //
1836 // ARM C++ ABI 3.2.3.1:
1837 // To support the potential use of initialization guard variables
1838 // as semaphores that are the target of ARM SWP and LDREX/STREX
1839 // synchronizing instructions we define a static initialization
1840 // guard variable to be a 4-byte aligned, 4-byte word with the
1841 // following inline access protocol.
1842 // #define INITIALIZED 1
1843 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1844 // if (__cxa_guard_acquire(&obj_guard))
1845 // ...
1846 // }
1847 //
1848 // and similarly for ARM64:
1849 //
1850 // ARM64 C++ ABI 3.2.2:
1851 // This ABI instead only specifies the value bit 0 of the static guard
1852 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1853 // variable is not initialized and 1 when it is.
1854 llvm::Value *V =
1855 (UseARMGuardVarABI && !useInt8GuardVariable)
1856 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1857 : LI;
1858 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001859
1860 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1861 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1862
1863 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001864 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001865
1866 CGF.EmitBlock(InitCheckBlock);
1867
1868 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001869 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001870 // Call __cxa_guard_acquire.
1871 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001872 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001873
1874 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1875
1876 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1877 InitBlock, EndBlock);
1878
1879 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001880 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001881
1882 CGF.EmitBlock(InitBlock);
1883 }
1884
1885 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001886 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001887
John McCall5aa52592011-06-17 07:33:57 +00001888 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001889 // Pop the guard-abort cleanup if we pushed one.
1890 CGF.PopCleanupBlock();
1891
1892 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001893 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001894 } else {
John McCallb88a5662012-03-30 21:00:39 +00001895 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001896 }
1897
1898 CGF.EmitBlock(EndBlock);
1899}
John McCallc84ed6a2012-05-01 06:13:13 +00001900
1901/// Register a global destructor using __cxa_atexit.
1902static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1903 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001904 llvm::Constant *addr,
1905 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001906 const char *Name = "__cxa_atexit";
1907 if (TLS) {
1908 const llvm::Triple &T = CGF.getTarget().getTriple();
1909 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1910 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001911
John McCallc84ed6a2012-05-01 06:13:13 +00001912 // We're assuming that the destructor function is something we can
1913 // reasonably call with the default CC. Go ahead and cast it to the
1914 // right prototype.
1915 llvm::Type *dtorTy =
1916 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1917
1918 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1919 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1920 llvm::FunctionType *atexitTy =
1921 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1922
1923 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001924 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001925 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1926 fn->setDoesNotThrow();
1927
1928 // Create a variable that binds the atexit to this shared object.
1929 llvm::Constant *handle =
1930 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1931
1932 llvm::Value *args[] = {
1933 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1934 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1935 handle
1936 };
John McCall882987f2013-02-28 19:01:20 +00001937 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001938}
1939
1940/// Register a global destructor as best as we know how.
1941void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001942 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001943 llvm::Constant *dtor,
1944 llvm::Constant *addr) {
1945 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001946 if (CGM.getCodeGenOpts().CXAAtExit)
1947 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1948
1949 if (D.getTLSKind())
1950 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001951
1952 // In Apple kexts, we want to add a global destructor entry.
1953 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001954 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001955 // Generate a global destructor entry.
1956 return CGM.AddCXXDtorEntry(dtor, addr);
1957 }
1958
David Blaikieebe87e12013-08-27 23:57:18 +00001959 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001960}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001961
David Majnemer9b21c332014-07-11 20:28:10 +00001962static bool isThreadWrapperReplaceable(const VarDecl *VD,
1963 CodeGen::CodeGenModule &CGM) {
1964 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1965 // OS X prefers to have references to thread local variables to go through
1966 // the thread wrapper instead of directly referencing the backing variable.
1967 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1968 CGM.getTarget().getTriple().isMacOSX();
1969}
1970
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001971/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001972/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001973/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001974static llvm::GlobalValue::LinkageTypes
1975getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1976 llvm::GlobalValue::LinkageTypes VarLinkage =
1977 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1978
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001979 // For internal linkage variables, we don't need an external or weak wrapper.
1980 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1981 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001982
David Majnemer9b21c332014-07-11 20:28:10 +00001983 // If the thread wrapper is replaceable, give it appropriate linkage.
1984 if (isThreadWrapperReplaceable(VD, CGM)) {
1985 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1986 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1987 return llvm::GlobalVariable::WeakAnyLinkage;
1988 return VarLinkage;
1989 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001990 return llvm::GlobalValue::WeakODRLinkage;
1991}
1992
1993llvm::Function *
1994ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00001995 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001996 // Mangle the name for the thread_local wrapper function.
1997 SmallString<256> WrapperName;
1998 {
1999 llvm::raw_svector_ostream Out(WrapperName);
2000 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
2001 Out.flush();
2002 }
2003
Alexander Musmanf94c3182014-09-26 06:28:25 +00002004 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002005 return cast<llvm::Function>(V);
2006
Alexander Musmanf94c3182014-09-26 06:28:25 +00002007 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002008 if (VD->getType()->isReferenceType())
2009 RetTy = RetTy->getPointerElementType();
2010
2011 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002012 llvm::Function *Wrapper =
2013 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2014 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002015 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002016 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002017 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002018 return Wrapper;
2019}
2020
2021void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002022 CodeGenModule &CGM,
2023 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2024 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2025 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2026 llvm::Function *InitFunc = nullptr;
2027 if (!CXXThreadLocalInits.empty()) {
2028 // Generate a guarded initialization function.
2029 llvm::FunctionType *FTy =
2030 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2031 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002032 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002033 /*TLS=*/true);
2034 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2035 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2036 llvm::GlobalVariable::InternalLinkage,
2037 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2038 Guard->setThreadLocal(true);
2039 CodeGenFunction(CGM)
2040 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2041 }
2042 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
2043 const VarDecl *VD = CXXThreadLocals[I].first;
2044 llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002045
David Majnemer9b21c332014-07-11 20:28:10 +00002046 // Some targets require that all access to thread local variables go through
2047 // the thread wrapper. This means that we cannot attempt to create a thread
2048 // wrapper or a thread helper.
2049 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2050 continue;
2051
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002052 // Mangle the name for the thread_local initialization function.
2053 SmallString<256> InitFnName;
2054 {
2055 llvm::raw_svector_ostream Out(InitFnName);
2056 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
2057 Out.flush();
2058 }
2059
2060 // If we have a definition for the variable, emit the initialization
2061 // function as an alias to the global Init function (if any). Otherwise,
2062 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002063 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002064 bool InitIsInitFunc = false;
2065 if (VD->hasDefinition()) {
2066 InitIsInitFunc = true;
2067 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002068 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2069 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002070 } else {
2071 // Emit a weak global function referring to the initialization function.
2072 // This function will not exist if the TU defining the thread_local
2073 // variable in question does not need any dynamic initialization for
2074 // its thread_local variables.
2075 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2076 Init = llvm::Function::Create(
2077 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2078 &CGM.getModule());
2079 }
2080
2081 if (Init)
2082 Init->setVisibility(Var->getVisibility());
2083
2084 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2085 llvm::LLVMContext &Context = CGM.getModule().getContext();
2086 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2087 CGBuilderTy Builder(Entry);
2088 if (InitIsInitFunc) {
2089 if (Init)
2090 Builder.CreateCall(Init);
2091 } else {
2092 // Don't know whether we have an init function. Call it if it exists.
2093 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2094 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2095 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2096 Builder.CreateCondBr(Have, InitBB, ExitBB);
2097
2098 Builder.SetInsertPoint(InitBB);
2099 Builder.CreateCall(Init);
2100 Builder.CreateBr(ExitBB);
2101
2102 Builder.SetInsertPoint(ExitBB);
2103 }
2104
2105 // For a reference, the result of the wrapper function is a pointer to
2106 // the referenced object.
2107 llvm::Value *Val = Var;
2108 if (VD->getType()->isReferenceType()) {
2109 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2110 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2111 Val = LI;
2112 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002113 if (Val->getType() != Wrapper->getReturnType())
2114 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2115 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002116 Builder.CreateRet(Val);
2117 }
2118}
2119
Richard Smith0f383742014-03-26 22:48:22 +00002120LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2121 const VarDecl *VD,
2122 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002123 QualType T = VD->getType();
2124 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2125 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002126 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002127
2128 Val = CGF.Builder.CreateCall(Wrapper);
2129
2130 LValue LV;
2131 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002132 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002133 else
Richard Smith0f383742014-03-26 22:48:22 +00002134 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002135 // FIXME: need setObjCGCLValueClass?
2136 return LV;
2137}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002138
2139/// Return whether the given global decl needs a VTT parameter, which it does
2140/// if it's a base constructor or destructor with virtual bases.
2141bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2142 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2143
2144 // We don't have any virtual bases, just return early.
2145 if (!MD->getParent()->getNumVBases())
2146 return false;
2147
2148 // Check if we have a base constructor.
2149 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2150 return true;
2151
2152 // Check if we have a base destructor.
2153 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2154 return true;
2155
2156 return false;
2157}
David Majnemere2cb8d12014-07-07 06:20:47 +00002158
2159namespace {
2160class ItaniumRTTIBuilder {
2161 CodeGenModule &CGM; // Per-module state.
2162 llvm::LLVMContext &VMContext;
2163 const ItaniumCXXABI &CXXABI; // Per-module state.
2164
2165 /// Fields - The fields of the RTTI descriptor currently being built.
2166 SmallVector<llvm::Constant *, 16> Fields;
2167
2168 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2169 llvm::GlobalVariable *
2170 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2171
2172 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2173 /// descriptor of the given type.
2174 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2175
2176 /// BuildVTablePointer - Build the vtable pointer for the given type.
2177 void BuildVTablePointer(const Type *Ty);
2178
2179 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2180 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2181 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2182
2183 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2184 /// classes with bases that do not satisfy the abi::__si_class_type_info
2185 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2186 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2187
2188 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2189 /// for pointer types.
2190 void BuildPointerTypeInfo(QualType PointeeTy);
2191
2192 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2193 /// type_info for an object type.
2194 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2195
2196 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2197 /// struct, used for member pointer types.
2198 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2199
2200public:
2201 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2202 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2203
2204 // Pointer type info flags.
2205 enum {
2206 /// PTI_Const - Type has const qualifier.
2207 PTI_Const = 0x1,
2208
2209 /// PTI_Volatile - Type has volatile qualifier.
2210 PTI_Volatile = 0x2,
2211
2212 /// PTI_Restrict - Type has restrict qualifier.
2213 PTI_Restrict = 0x4,
2214
2215 /// PTI_Incomplete - Type is incomplete.
2216 PTI_Incomplete = 0x8,
2217
2218 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2219 /// (in pointer to member).
2220 PTI_ContainingClassIncomplete = 0x10
2221 };
2222
2223 // VMI type info flags.
2224 enum {
2225 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2226 VMI_NonDiamondRepeat = 0x1,
2227
2228 /// VMI_DiamondShaped - Class is diamond shaped.
2229 VMI_DiamondShaped = 0x2
2230 };
2231
2232 // Base class type info flags.
2233 enum {
2234 /// BCTI_Virtual - Base class is virtual.
2235 BCTI_Virtual = 0x1,
2236
2237 /// BCTI_Public - Base class is public.
2238 BCTI_Public = 0x2
2239 };
2240
2241 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2242 ///
2243 /// \param Force - true to force the creation of this RTTI value
2244 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2245};
2246}
2247
2248llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2249 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2250 SmallString<256> OutName;
2251 llvm::raw_svector_ostream Out(OutName);
2252 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2253 Out.flush();
2254 StringRef Name = OutName.str();
2255
2256 // We know that the mangled name of the type starts at index 4 of the
2257 // mangled name of the typename, so we can just index into it in order to
2258 // get the mangled name of the type.
2259 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2260 Name.substr(4));
2261
2262 llvm::GlobalVariable *GV =
2263 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2264
2265 GV->setInitializer(Init);
2266
2267 return GV;
2268}
2269
2270llvm::Constant *
2271ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2272 // Mangle the RTTI name.
2273 SmallString<256> OutName;
2274 llvm::raw_svector_ostream Out(OutName);
2275 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2276 Out.flush();
2277 StringRef Name = OutName.str();
2278
2279 // Look for an existing global.
2280 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2281
2282 if (!GV) {
2283 // Create a new global variable.
2284 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2285 /*Constant=*/true,
2286 llvm::GlobalValue::ExternalLinkage, nullptr,
2287 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002288 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2289 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2290 if (RD->hasAttr<DLLImportAttr>())
2291 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2292 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002293 }
2294
2295 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2296}
2297
2298/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2299/// info for that type is defined in the standard library.
2300static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2301 // Itanium C++ ABI 2.9.2:
2302 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2303 // the run-time support library. Specifically, the run-time support
2304 // library should contain type_info objects for the types X, X* and
2305 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2306 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2307 // long, unsigned long, long long, unsigned long long, float, double,
2308 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2309 // half-precision floating point types.
2310 switch (Ty->getKind()) {
2311 case BuiltinType::Void:
2312 case BuiltinType::NullPtr:
2313 case BuiltinType::Bool:
2314 case BuiltinType::WChar_S:
2315 case BuiltinType::WChar_U:
2316 case BuiltinType::Char_U:
2317 case BuiltinType::Char_S:
2318 case BuiltinType::UChar:
2319 case BuiltinType::SChar:
2320 case BuiltinType::Short:
2321 case BuiltinType::UShort:
2322 case BuiltinType::Int:
2323 case BuiltinType::UInt:
2324 case BuiltinType::Long:
2325 case BuiltinType::ULong:
2326 case BuiltinType::LongLong:
2327 case BuiltinType::ULongLong:
2328 case BuiltinType::Half:
2329 case BuiltinType::Float:
2330 case BuiltinType::Double:
2331 case BuiltinType::LongDouble:
2332 case BuiltinType::Char16:
2333 case BuiltinType::Char32:
2334 case BuiltinType::Int128:
2335 case BuiltinType::UInt128:
2336 case BuiltinType::OCLImage1d:
2337 case BuiltinType::OCLImage1dArray:
2338 case BuiltinType::OCLImage1dBuffer:
2339 case BuiltinType::OCLImage2d:
2340 case BuiltinType::OCLImage2dArray:
2341 case BuiltinType::OCLImage3d:
2342 case BuiltinType::OCLSampler:
2343 case BuiltinType::OCLEvent:
2344 return true;
2345
2346 case BuiltinType::Dependent:
2347#define BUILTIN_TYPE(Id, SingletonId)
2348#define PLACEHOLDER_TYPE(Id, SingletonId) \
2349 case BuiltinType::Id:
2350#include "clang/AST/BuiltinTypes.def"
2351 llvm_unreachable("asking for RRTI for a placeholder type!");
2352
2353 case BuiltinType::ObjCId:
2354 case BuiltinType::ObjCClass:
2355 case BuiltinType::ObjCSel:
2356 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2357 }
2358
2359 llvm_unreachable("Invalid BuiltinType Kind!");
2360}
2361
2362static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2363 QualType PointeeTy = PointerTy->getPointeeType();
2364 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2365 if (!BuiltinTy)
2366 return false;
2367
2368 // Check the qualifiers.
2369 Qualifiers Quals = PointeeTy.getQualifiers();
2370 Quals.removeConst();
2371
2372 if (!Quals.empty())
2373 return false;
2374
2375 return TypeInfoIsInStandardLibrary(BuiltinTy);
2376}
2377
2378/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2379/// information for the given type exists in the standard library.
2380static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2381 // Type info for builtin types is defined in the standard library.
2382 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2383 return TypeInfoIsInStandardLibrary(BuiltinTy);
2384
2385 // Type info for some pointer types to builtin types is defined in the
2386 // standard library.
2387 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2388 return TypeInfoIsInStandardLibrary(PointerTy);
2389
2390 return false;
2391}
2392
2393/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2394/// the given type exists somewhere else, and that we should not emit the type
2395/// information in this translation unit. Assumes that it is not a
2396/// standard-library type.
2397static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2398 QualType Ty) {
2399 ASTContext &Context = CGM.getContext();
2400
2401 // If RTTI is disabled, assume it might be disabled in the
2402 // translation unit that defines any potential key function, too.
2403 if (!Context.getLangOpts().RTTI) return false;
2404
2405 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2406 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2407 if (!RD->hasDefinition())
2408 return false;
2409
2410 if (!RD->isDynamicClass())
2411 return false;
2412
2413 // FIXME: this may need to be reconsidered if the key function
2414 // changes.
David Majnemer1fb1a042014-11-07 07:26:38 +00002415 if (CGM.getVTables().isVTableExternal(RD))
2416 return true;
2417
2418 if (RD->hasAttr<DLLImportAttr>())
2419 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002420 }
2421
2422 return false;
2423}
2424
2425/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2426static bool IsIncompleteClassType(const RecordType *RecordTy) {
2427 return !RecordTy->getDecl()->isCompleteDefinition();
2428}
2429
2430/// ContainsIncompleteClassType - Returns whether the given type contains an
2431/// incomplete class type. This is true if
2432///
2433/// * The given type is an incomplete class type.
2434/// * The given type is a pointer type whose pointee type contains an
2435/// incomplete class type.
2436/// * The given type is a member pointer type whose class is an incomplete
2437/// class type.
2438/// * The given type is a member pointer type whoise pointee type contains an
2439/// incomplete class type.
2440/// is an indirect or direct pointer to an incomplete class type.
2441static bool ContainsIncompleteClassType(QualType Ty) {
2442 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2443 if (IsIncompleteClassType(RecordTy))
2444 return true;
2445 }
2446
2447 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2448 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2449
2450 if (const MemberPointerType *MemberPointerTy =
2451 dyn_cast<MemberPointerType>(Ty)) {
2452 // Check if the class type is incomplete.
2453 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2454 if (IsIncompleteClassType(ClassType))
2455 return true;
2456
2457 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2458 }
2459
2460 return false;
2461}
2462
2463// CanUseSingleInheritance - Return whether the given record decl has a "single,
2464// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2465// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2466static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2467 // Check the number of bases.
2468 if (RD->getNumBases() != 1)
2469 return false;
2470
2471 // Get the base.
2472 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2473
2474 // Check that the base is not virtual.
2475 if (Base->isVirtual())
2476 return false;
2477
2478 // Check that the base is public.
2479 if (Base->getAccessSpecifier() != AS_public)
2480 return false;
2481
2482 // Check that the class is dynamic iff the base is.
2483 const CXXRecordDecl *BaseDecl =
2484 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2485 if (!BaseDecl->isEmpty() &&
2486 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2487 return false;
2488
2489 return true;
2490}
2491
2492void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2493 // abi::__class_type_info.
2494 static const char * const ClassTypeInfo =
2495 "_ZTVN10__cxxabiv117__class_type_infoE";
2496 // abi::__si_class_type_info.
2497 static const char * const SIClassTypeInfo =
2498 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2499 // abi::__vmi_class_type_info.
2500 static const char * const VMIClassTypeInfo =
2501 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2502
2503 const char *VTableName = nullptr;
2504
2505 switch (Ty->getTypeClass()) {
2506#define TYPE(Class, Base)
2507#define ABSTRACT_TYPE(Class, Base)
2508#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2509#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2510#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2511#include "clang/AST/TypeNodes.def"
2512 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2513
2514 case Type::LValueReference:
2515 case Type::RValueReference:
2516 llvm_unreachable("References shouldn't get here");
2517
2518 case Type::Auto:
2519 llvm_unreachable("Undeduced auto type shouldn't get here");
2520
2521 case Type::Builtin:
2522 // GCC treats vector and complex types as fundamental types.
2523 case Type::Vector:
2524 case Type::ExtVector:
2525 case Type::Complex:
2526 case Type::Atomic:
2527 // FIXME: GCC treats block pointers as fundamental types?!
2528 case Type::BlockPointer:
2529 // abi::__fundamental_type_info.
2530 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2531 break;
2532
2533 case Type::ConstantArray:
2534 case Type::IncompleteArray:
2535 case Type::VariableArray:
2536 // abi::__array_type_info.
2537 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2538 break;
2539
2540 case Type::FunctionNoProto:
2541 case Type::FunctionProto:
2542 // abi::__function_type_info.
2543 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2544 break;
2545
2546 case Type::Enum:
2547 // abi::__enum_type_info.
2548 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2549 break;
2550
2551 case Type::Record: {
2552 const CXXRecordDecl *RD =
2553 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2554
2555 if (!RD->hasDefinition() || !RD->getNumBases()) {
2556 VTableName = ClassTypeInfo;
2557 } else if (CanUseSingleInheritance(RD)) {
2558 VTableName = SIClassTypeInfo;
2559 } else {
2560 VTableName = VMIClassTypeInfo;
2561 }
2562
2563 break;
2564 }
2565
2566 case Type::ObjCObject:
2567 // Ignore protocol qualifiers.
2568 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2569
2570 // Handle id and Class.
2571 if (isa<BuiltinType>(Ty)) {
2572 VTableName = ClassTypeInfo;
2573 break;
2574 }
2575
2576 assert(isa<ObjCInterfaceType>(Ty));
2577 // Fall through.
2578
2579 case Type::ObjCInterface:
2580 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2581 VTableName = SIClassTypeInfo;
2582 } else {
2583 VTableName = ClassTypeInfo;
2584 }
2585 break;
2586
2587 case Type::ObjCObjectPointer:
2588 case Type::Pointer:
2589 // abi::__pointer_type_info.
2590 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2591 break;
2592
2593 case Type::MemberPointer:
2594 // abi::__pointer_to_member_type_info.
2595 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2596 break;
2597 }
2598
2599 llvm::Constant *VTable =
2600 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2601
2602 llvm::Type *PtrDiffTy =
2603 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2604
2605 // The vtable address point is 2.
2606 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2607 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2608 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2609
2610 Fields.push_back(VTable);
2611}
2612
2613/// \brief Return the linkage that the type info and type info name constants
2614/// should have for the given type.
2615static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2616 QualType Ty) {
2617 // Itanium C++ ABI 2.9.5p7:
2618 // In addition, it and all of the intermediate abi::__pointer_type_info
2619 // structs in the chain down to the abi::__class_type_info for the
2620 // incomplete class type must be prevented from resolving to the
2621 // corresponding type_info structs for the complete class type, possibly
2622 // by making them local static objects. Finally, a dummy class RTTI is
2623 // generated for the incomplete type that will not resolve to the final
2624 // complete class RTTI (because the latter need not exist), possibly by
2625 // making it a local static object.
2626 if (ContainsIncompleteClassType(Ty))
2627 return llvm::GlobalValue::InternalLinkage;
2628
2629 switch (Ty->getLinkage()) {
2630 case NoLinkage:
2631 case InternalLinkage:
2632 case UniqueExternalLinkage:
2633 return llvm::GlobalValue::InternalLinkage;
2634
2635 case VisibleNoLinkage:
2636 case ExternalLinkage:
2637 if (!CGM.getLangOpts().RTTI) {
2638 // RTTI is not enabled, which means that this type info struct is going
2639 // to be used for exception handling. Give it linkonce_odr linkage.
2640 return llvm::GlobalValue::LinkOnceODRLinkage;
2641 }
2642
2643 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2644 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2645 if (RD->hasAttr<WeakAttr>())
2646 return llvm::GlobalValue::WeakODRLinkage;
2647 if (RD->isDynamicClass())
2648 return CGM.getVTableLinkage(RD);
2649 }
2650
2651 return llvm::GlobalValue::LinkOnceODRLinkage;
2652 }
2653
2654 llvm_unreachable("Invalid linkage!");
2655}
2656
2657llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2658 // We want to operate on the canonical type.
2659 Ty = CGM.getContext().getCanonicalType(Ty);
2660
2661 // Check if we've already emitted an RTTI descriptor for this type.
2662 SmallString<256> OutName;
2663 llvm::raw_svector_ostream Out(OutName);
2664 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2665 Out.flush();
2666 StringRef Name = OutName.str();
2667
2668 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2669 if (OldGV && !OldGV->isDeclaration()) {
2670 assert(!OldGV->hasAvailableExternallyLinkage() &&
2671 "available_externally typeinfos not yet implemented");
2672
2673 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2674 }
2675
2676 // Check if there is already an external RTTI descriptor for this type.
2677 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2678 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2679 return GetAddrOfExternalRTTIDescriptor(Ty);
2680
2681 // Emit the standard library with external linkage.
2682 llvm::GlobalVariable::LinkageTypes Linkage;
2683 if (IsStdLib)
2684 Linkage = llvm::GlobalValue::ExternalLinkage;
2685 else
2686 Linkage = getTypeInfoLinkage(CGM, Ty);
2687
2688 // Add the vtable pointer.
2689 BuildVTablePointer(cast<Type>(Ty));
2690
2691 // And the name.
2692 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2693 llvm::Constant *TypeNameField;
2694
2695 // If we're supposed to demote the visibility, be sure to set a flag
2696 // to use a string comparison for type_info comparisons.
2697 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2698 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2699 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2700 // The flag is the sign bit, which on ARM64 is defined to be clear
2701 // for global pointers. This is very ARM64-specific.
2702 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2703 llvm::Constant *flag =
2704 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2705 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2706 TypeNameField =
2707 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2708 } else {
2709 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2710 }
2711 Fields.push_back(TypeNameField);
2712
2713 switch (Ty->getTypeClass()) {
2714#define TYPE(Class, Base)
2715#define ABSTRACT_TYPE(Class, Base)
2716#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2717#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2718#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2719#include "clang/AST/TypeNodes.def"
2720 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2721
2722 // GCC treats vector types as fundamental types.
2723 case Type::Builtin:
2724 case Type::Vector:
2725 case Type::ExtVector:
2726 case Type::Complex:
2727 case Type::BlockPointer:
2728 // Itanium C++ ABI 2.9.5p4:
2729 // abi::__fundamental_type_info adds no data members to std::type_info.
2730 break;
2731
2732 case Type::LValueReference:
2733 case Type::RValueReference:
2734 llvm_unreachable("References shouldn't get here");
2735
2736 case Type::Auto:
2737 llvm_unreachable("Undeduced auto type shouldn't get here");
2738
2739 case Type::ConstantArray:
2740 case Type::IncompleteArray:
2741 case Type::VariableArray:
2742 // Itanium C++ ABI 2.9.5p5:
2743 // abi::__array_type_info adds no data members to std::type_info.
2744 break;
2745
2746 case Type::FunctionNoProto:
2747 case Type::FunctionProto:
2748 // Itanium C++ ABI 2.9.5p5:
2749 // abi::__function_type_info adds no data members to std::type_info.
2750 break;
2751
2752 case Type::Enum:
2753 // Itanium C++ ABI 2.9.5p5:
2754 // abi::__enum_type_info adds no data members to std::type_info.
2755 break;
2756
2757 case Type::Record: {
2758 const CXXRecordDecl *RD =
2759 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2760 if (!RD->hasDefinition() || !RD->getNumBases()) {
2761 // We don't need to emit any fields.
2762 break;
2763 }
2764
2765 if (CanUseSingleInheritance(RD))
2766 BuildSIClassTypeInfo(RD);
2767 else
2768 BuildVMIClassTypeInfo(RD);
2769
2770 break;
2771 }
2772
2773 case Type::ObjCObject:
2774 case Type::ObjCInterface:
2775 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2776 break;
2777
2778 case Type::ObjCObjectPointer:
2779 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2780 break;
2781
2782 case Type::Pointer:
2783 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2784 break;
2785
2786 case Type::MemberPointer:
2787 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2788 break;
2789
2790 case Type::Atomic:
2791 // No fields, at least for the moment.
2792 break;
2793 }
2794
2795 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2796
Rafael Espindolacb92c192015-01-15 23:18:01 +00002797 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002798 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002799 new llvm::GlobalVariable(M, Init->getType(),
2800 /*Constant=*/true, Linkage, Init, Name);
2801
2802 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2803 GV->setComdat(M.getOrInsertComdat(GV->getName()));
David Majnemere2cb8d12014-07-07 06:20:47 +00002804
2805 // If there's already an old global variable, replace it with the new one.
2806 if (OldGV) {
2807 GV->takeName(OldGV);
2808 llvm::Constant *NewPtr =
2809 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2810 OldGV->replaceAllUsesWith(NewPtr);
2811 OldGV->eraseFromParent();
2812 }
2813
2814 // The Itanium ABI specifies that type_info objects must be globally
2815 // unique, with one exception: if the type is an incomplete class
2816 // type or a (possibly indirect) pointer to one. That exception
2817 // affects the general case of comparing type_info objects produced
2818 // by the typeid operator, which is why the comparison operators on
2819 // std::type_info generally use the type_info name pointers instead
2820 // of the object addresses. However, the language's built-in uses
2821 // of RTTI generally require class types to be complete, even when
2822 // manipulating pointers to those class types. This allows the
2823 // implementation of dynamic_cast to rely on address equality tests,
2824 // which is much faster.
2825
2826 // All of this is to say that it's important that both the type_info
2827 // object and the type_info name be uniqued when weakly emitted.
2828
2829 // Give the type_info object and name the formal visibility of the
2830 // type itself.
2831 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2832 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2833 // If the linkage is local, only default visibility makes sense.
2834 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2835 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2836 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2837 else
2838 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2839 TypeName->setVisibility(llvmVisibility);
2840 GV->setVisibility(llvmVisibility);
2841
2842 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2843}
2844
2845/// ComputeQualifierFlags - Compute the pointer type info flags from the
2846/// given qualifier.
2847static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2848 unsigned Flags = 0;
2849
2850 if (Quals.hasConst())
2851 Flags |= ItaniumRTTIBuilder::PTI_Const;
2852 if (Quals.hasVolatile())
2853 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2854 if (Quals.hasRestrict())
2855 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2856
2857 return Flags;
2858}
2859
2860/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2861/// for the given Objective-C object type.
2862void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2863 // Drop qualifiers.
2864 const Type *T = OT->getBaseType().getTypePtr();
2865 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2866
2867 // The builtin types are abi::__class_type_infos and don't require
2868 // extra fields.
2869 if (isa<BuiltinType>(T)) return;
2870
2871 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2872 ObjCInterfaceDecl *Super = Class->getSuperClass();
2873
2874 // Root classes are also __class_type_info.
2875 if (!Super) return;
2876
2877 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2878
2879 // Everything else is single inheritance.
2880 llvm::Constant *BaseTypeInfo =
2881 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2882 Fields.push_back(BaseTypeInfo);
2883}
2884
2885/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2886/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2887void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2888 // Itanium C++ ABI 2.9.5p6b:
2889 // It adds to abi::__class_type_info a single member pointing to the
2890 // type_info structure for the base type,
2891 llvm::Constant *BaseTypeInfo =
2892 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2893 Fields.push_back(BaseTypeInfo);
2894}
2895
2896namespace {
2897 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2898 /// a class hierarchy.
2899 struct SeenBases {
2900 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2901 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2902 };
2903}
2904
2905/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2906/// abi::__vmi_class_type_info.
2907///
2908static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2909 SeenBases &Bases) {
2910
2911 unsigned Flags = 0;
2912
2913 const CXXRecordDecl *BaseDecl =
2914 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2915
2916 if (Base->isVirtual()) {
2917 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002918 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002919 // If this virtual base has been seen before, then the class is diamond
2920 // shaped.
2921 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2922 } else {
2923 if (Bases.NonVirtualBases.count(BaseDecl))
2924 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2925 }
2926 } else {
2927 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002928 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002929 // If this non-virtual base has been seen before, then the class has non-
2930 // diamond shaped repeated inheritance.
2931 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2932 } else {
2933 if (Bases.VirtualBases.count(BaseDecl))
2934 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2935 }
2936 }
2937
2938 // Walk all bases.
2939 for (const auto &I : BaseDecl->bases())
2940 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2941
2942 return Flags;
2943}
2944
2945static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2946 unsigned Flags = 0;
2947 SeenBases Bases;
2948
2949 // Walk all bases.
2950 for (const auto &I : RD->bases())
2951 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2952
2953 return Flags;
2954}
2955
2956/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2957/// classes with bases that do not satisfy the abi::__si_class_type_info
2958/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2959void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2960 llvm::Type *UnsignedIntLTy =
2961 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2962
2963 // Itanium C++ ABI 2.9.5p6c:
2964 // __flags is a word with flags describing details about the class
2965 // structure, which may be referenced by using the __flags_masks
2966 // enumeration. These flags refer to both direct and indirect bases.
2967 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2968 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2969
2970 // Itanium C++ ABI 2.9.5p6c:
2971 // __base_count is a word with the number of direct proper base class
2972 // descriptions that follow.
2973 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2974
2975 if (!RD->getNumBases())
2976 return;
2977
2978 llvm::Type *LongLTy =
2979 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2980
2981 // Now add the base class descriptions.
2982
2983 // Itanium C++ ABI 2.9.5p6c:
2984 // __base_info[] is an array of base class descriptions -- one for every
2985 // direct proper base. Each description is of the type:
2986 //
2987 // struct abi::__base_class_type_info {
2988 // public:
2989 // const __class_type_info *__base_type;
2990 // long __offset_flags;
2991 //
2992 // enum __offset_flags_masks {
2993 // __virtual_mask = 0x1,
2994 // __public_mask = 0x2,
2995 // __offset_shift = 8
2996 // };
2997 // };
2998 for (const auto &Base : RD->bases()) {
2999 // The __base_type member points to the RTTI for the base type.
3000 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3001
3002 const CXXRecordDecl *BaseDecl =
3003 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3004
3005 int64_t OffsetFlags = 0;
3006
3007 // All but the lower 8 bits of __offset_flags are a signed offset.
3008 // For a non-virtual base, this is the offset in the object of the base
3009 // subobject. For a virtual base, this is the offset in the virtual table of
3010 // the virtual base offset for the virtual base referenced (negative).
3011 CharUnits Offset;
3012 if (Base.isVirtual())
3013 Offset =
3014 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3015 else {
3016 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3017 Offset = Layout.getBaseClassOffset(BaseDecl);
3018 };
3019
3020 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3021
3022 // The low-order byte of __offset_flags contains flags, as given by the
3023 // masks from the enumeration __offset_flags_masks.
3024 if (Base.isVirtual())
3025 OffsetFlags |= BCTI_Virtual;
3026 if (Base.getAccessSpecifier() == AS_public)
3027 OffsetFlags |= BCTI_Public;
3028
3029 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3030 }
3031}
3032
3033/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3034/// used for pointer types.
3035void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3036 Qualifiers Quals;
3037 QualType UnqualifiedPointeeTy =
3038 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3039
3040 // Itanium C++ ABI 2.9.5p7:
3041 // __flags is a flag word describing the cv-qualification and other
3042 // attributes of the type pointed to
3043 unsigned Flags = ComputeQualifierFlags(Quals);
3044
3045 // Itanium C++ ABI 2.9.5p7:
3046 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3047 // incomplete class type, the incomplete target type flag is set.
3048 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3049 Flags |= PTI_Incomplete;
3050
3051 llvm::Type *UnsignedIntLTy =
3052 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3053 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3054
3055 // Itanium C++ ABI 2.9.5p7:
3056 // __pointee is a pointer to the std::type_info derivation for the
3057 // unqualified type being pointed to.
3058 llvm::Constant *PointeeTypeInfo =
3059 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3060 Fields.push_back(PointeeTypeInfo);
3061}
3062
3063/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3064/// struct, used for member pointer types.
3065void
3066ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3067 QualType PointeeTy = Ty->getPointeeType();
3068
3069 Qualifiers Quals;
3070 QualType UnqualifiedPointeeTy =
3071 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3072
3073 // Itanium C++ ABI 2.9.5p7:
3074 // __flags is a flag word describing the cv-qualification and other
3075 // attributes of the type pointed to.
3076 unsigned Flags = ComputeQualifierFlags(Quals);
3077
3078 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3079
3080 // Itanium C++ ABI 2.9.5p7:
3081 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3082 // incomplete class type, the incomplete target type flag is set.
3083 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3084 Flags |= PTI_Incomplete;
3085
3086 if (IsIncompleteClassType(ClassType))
3087 Flags |= PTI_ContainingClassIncomplete;
3088
3089 llvm::Type *UnsignedIntLTy =
3090 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3091 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3092
3093 // Itanium C++ ABI 2.9.5p7:
3094 // __pointee is a pointer to the std::type_info derivation for the
3095 // unqualified type being pointed to.
3096 llvm::Constant *PointeeTypeInfo =
3097 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3098 Fields.push_back(PointeeTypeInfo);
3099
3100 // Itanium C++ ABI 2.9.5p9:
3101 // __context is a pointer to an abi::__class_type_info corresponding to the
3102 // class type containing the member pointed to
3103 // (e.g., the "A" in "int A::*").
3104 Fields.push_back(
3105 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3106}
3107
David Majnemer443250f2015-03-17 20:35:00 +00003108llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003109 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3110}
3111
3112void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3113 QualType PointerType = getContext().getPointerType(Type);
3114 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3115 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3116 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3117 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3118}
3119
3120void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3121 QualType FundamentalTypes[] = {
3122 getContext().VoidTy, getContext().NullPtrTy,
3123 getContext().BoolTy, getContext().WCharTy,
3124 getContext().CharTy, getContext().UnsignedCharTy,
3125 getContext().SignedCharTy, getContext().ShortTy,
3126 getContext().UnsignedShortTy, getContext().IntTy,
3127 getContext().UnsignedIntTy, getContext().LongTy,
3128 getContext().UnsignedLongTy, getContext().LongLongTy,
3129 getContext().UnsignedLongLongTy, getContext().HalfTy,
3130 getContext().FloatTy, getContext().DoubleTy,
3131 getContext().LongDoubleTy, getContext().Char16Ty,
3132 getContext().Char32Ty,
3133 };
3134 for (const QualType &FundamentalType : FundamentalTypes)
3135 EmitFundamentalRTTIDescriptor(FundamentalType);
3136}
3137
3138/// What sort of uniqueness rules should we use for the RTTI for the
3139/// given type?
3140ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3141 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3142 if (shouldRTTIBeUnique())
3143 return RUK_Unique;
3144
3145 // It's only necessary for linkonce_odr or weak_odr linkage.
3146 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3147 Linkage != llvm::GlobalValue::WeakODRLinkage)
3148 return RUK_Unique;
3149
3150 // It's only necessary with default visibility.
3151 if (CanTy->getVisibility() != DefaultVisibility)
3152 return RUK_Unique;
3153
3154 // If we're not required to publish this symbol, hide it.
3155 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3156 return RUK_NonUniqueHidden;
3157
3158 // If we're required to publish this symbol, as we might be under an
3159 // explicit instantiation, leave it with default visibility but
3160 // enable string-comparisons.
3161 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3162 return RUK_NonUniqueVisible;
3163}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003164
Rafael Espindola1e4df922014-09-16 15:18:21 +00003165// Find out how to codegen the complete destructor and constructor
3166namespace {
3167enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3168}
3169static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3170 const CXXMethodDecl *MD) {
3171 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3172 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003173
Rafael Espindola1e4df922014-09-16 15:18:21 +00003174 // The complete and base structors are not equivalent if there are any virtual
3175 // bases, so emit separate functions.
3176 if (MD->getParent()->getNumVBases())
3177 return StructorCodegen::Emit;
3178
3179 GlobalDecl AliasDecl;
3180 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3181 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3182 } else {
3183 const auto *CD = cast<CXXConstructorDecl>(MD);
3184 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3185 }
3186 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3187
3188 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3189 return StructorCodegen::RAUW;
3190
3191 // FIXME: Should we allow available_externally aliases?
3192 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3193 return StructorCodegen::RAUW;
3194
Rafael Espindola0806f982014-09-16 20:19:43 +00003195 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3196 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3197 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3198 return StructorCodegen::COMDAT;
3199 return StructorCodegen::Emit;
3200 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003201
3202 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003203}
3204
Rafael Espindola1e4df922014-09-16 15:18:21 +00003205static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3206 GlobalDecl AliasDecl,
3207 GlobalDecl TargetDecl) {
3208 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3209
3210 StringRef MangledName = CGM.getMangledName(AliasDecl);
3211 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3212 if (Entry && !Entry->isDeclaration())
3213 return;
3214
3215 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3216 llvm::PointerType *AliasType = Aliasee->getType();
3217
3218 // Create the alias with no name.
3219 auto *Alias = llvm::GlobalAlias::create(
3220 AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule());
3221
3222 // Switch any previous uses to the alias.
3223 if (Entry) {
3224 assert(Entry->getType() == AliasType &&
3225 "declaration exists with different type");
3226 Alias->takeName(Entry);
3227 Entry->replaceAllUsesWith(Alias);
3228 Entry->eraseFromParent();
3229 } else {
3230 Alias->setName(MangledName);
3231 }
3232
3233 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003234 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003235}
3236
3237void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3238 StructorType Type) {
3239 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3240 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3241
3242 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3243
3244 if (Type == StructorType::Complete) {
3245 GlobalDecl CompleteDecl;
3246 GlobalDecl BaseDecl;
3247 if (CD) {
3248 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3249 BaseDecl = GlobalDecl(CD, Ctor_Base);
3250 } else {
3251 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3252 BaseDecl = GlobalDecl(DD, Dtor_Base);
3253 }
3254
3255 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3256 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3257 return;
3258 }
3259
3260 if (CGType == StructorCodegen::RAUW) {
3261 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3262 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3263 CGM.addReplacement(MangledName, Aliasee);
3264 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003265 }
3266 }
3267
3268 // The base destructor is equivalent to the base destructor of its
3269 // base class if there is exactly one non-virtual base class with a
3270 // non-trivial destructor, there are no fields with a non-trivial
3271 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003272 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3273 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003274 return;
3275
Rafael Espindola1e4df922014-09-16 15:18:21 +00003276 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003277
Rafael Espindola1e4df922014-09-16 15:18:21 +00003278 if (CGType == StructorCodegen::COMDAT) {
3279 SmallString<256> Buffer;
3280 llvm::raw_svector_ostream Out(Buffer);
3281 if (DD)
3282 getMangleContext().mangleCXXDtorComdat(DD, Out);
3283 else
3284 getMangleContext().mangleCXXCtorComdat(CD, Out);
3285 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3286 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003287 } else {
3288 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003289 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003290}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003291
3292static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3293 // void *__cxa_begin_catch(void*);
3294 llvm::FunctionType *FTy = llvm::FunctionType::get(
3295 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3296
3297 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3298}
3299
3300static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3301 // void __cxa_end_catch();
3302 llvm::FunctionType *FTy =
3303 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3304
3305 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3306}
3307
3308static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3309 // void *__cxa_get_exception_ptr(void*);
3310 llvm::FunctionType *FTy = llvm::FunctionType::get(
3311 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3312
3313 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3314}
3315
3316namespace {
3317 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3318 /// exception type lets us state definitively that the thrown exception
3319 /// type does not have a destructor. In particular:
3320 /// - Catch-alls tell us nothing, so we have to conservatively
3321 /// assume that the thrown exception might have a destructor.
3322 /// - Catches by reference behave according to their base types.
3323 /// - Catches of non-record types will only trigger for exceptions
3324 /// of non-record types, which never have destructors.
3325 /// - Catches of record types can trigger for arbitrary subclasses
3326 /// of the caught type, so we have to assume the actual thrown
3327 /// exception type might have a throwing destructor, even if the
3328 /// caught type's destructor is trivial or nothrow.
3329 struct CallEndCatch : EHScopeStack::Cleanup {
3330 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3331 bool MightThrow;
3332
3333 void Emit(CodeGenFunction &CGF, Flags flags) override {
3334 if (!MightThrow) {
3335 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3336 return;
3337 }
3338
3339 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3340 }
3341 };
3342}
3343
3344/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3345/// __cxa_end_catch.
3346///
3347/// \param EndMightThrow - true if __cxa_end_catch might throw
3348static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3349 llvm::Value *Exn,
3350 bool EndMightThrow) {
3351 llvm::CallInst *call =
3352 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3353
3354 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3355
3356 return call;
3357}
3358
3359/// A "special initializer" callback for initializing a catch
3360/// parameter during catch initialization.
3361static void InitCatchParam(CodeGenFunction &CGF,
3362 const VarDecl &CatchParam,
3363 llvm::Value *ParamAddr,
3364 SourceLocation Loc) {
3365 // Load the exception from where the landing pad saved it.
3366 llvm::Value *Exn = CGF.getExceptionFromSlot();
3367
3368 CanQualType CatchType =
3369 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3370 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3371
3372 // If we're catching by reference, we can just cast the object
3373 // pointer to the appropriate pointer.
3374 if (isa<ReferenceType>(CatchType)) {
3375 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3376 bool EndCatchMightThrow = CaughtType->isRecordType();
3377
3378 // __cxa_begin_catch returns the adjusted object pointer.
3379 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3380
3381 // We have no way to tell the personality function that we're
3382 // catching by reference, so if we're catching a pointer,
3383 // __cxa_begin_catch will actually return that pointer by value.
3384 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3385 QualType PointeeType = PT->getPointeeType();
3386
3387 // When catching by reference, generally we should just ignore
3388 // this by-value pointer and use the exception object instead.
3389 if (!PointeeType->isRecordType()) {
3390
3391 // Exn points to the struct _Unwind_Exception header, which
3392 // we have to skip past in order to reach the exception data.
3393 unsigned HeaderSize =
3394 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3395 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3396
3397 // However, if we're catching a pointer-to-record type that won't
3398 // work, because the personality function might have adjusted
3399 // the pointer. There's actually no way for us to fully satisfy
3400 // the language/ABI contract here: we can't use Exn because it
3401 // might have the wrong adjustment, but we can't use the by-value
3402 // pointer because it's off by a level of abstraction.
3403 //
3404 // The current solution is to dump the adjusted pointer into an
3405 // alloca, which breaks language semantics (because changing the
3406 // pointer doesn't change the exception) but at least works.
3407 // The better solution would be to filter out non-exact matches
3408 // and rethrow them, but this is tricky because the rethrow
3409 // really needs to be catchable by other sites at this landing
3410 // pad. The best solution is to fix the personality function.
3411 } else {
3412 // Pull the pointer for the reference type off.
3413 llvm::Type *PtrTy =
3414 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3415
3416 // Create the temporary and write the adjusted pointer into it.
3417 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3418 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3419 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3420
3421 // Bind the reference to the temporary.
3422 AdjustedExn = ExnPtrTmp;
3423 }
3424 }
3425
3426 llvm::Value *ExnCast =
3427 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3428 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3429 return;
3430 }
3431
3432 // Scalars and complexes.
3433 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3434 if (TEK != TEK_Aggregate) {
3435 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3436
3437 // If the catch type is a pointer type, __cxa_begin_catch returns
3438 // the pointer by value.
3439 if (CatchType->hasPointerRepresentation()) {
3440 llvm::Value *CastExn =
3441 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3442
3443 switch (CatchType.getQualifiers().getObjCLifetime()) {
3444 case Qualifiers::OCL_Strong:
3445 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3446 // fallthrough
3447
3448 case Qualifiers::OCL_None:
3449 case Qualifiers::OCL_ExplicitNone:
3450 case Qualifiers::OCL_Autoreleasing:
3451 CGF.Builder.CreateStore(CastExn, ParamAddr);
3452 return;
3453
3454 case Qualifiers::OCL_Weak:
3455 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3456 return;
3457 }
3458 llvm_unreachable("bad ownership qualifier!");
3459 }
3460
3461 // Otherwise, it returns a pointer into the exception object.
3462
3463 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3464 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3465
3466 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3467 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3468 CGF.getContext().getDeclAlign(&CatchParam));
3469 switch (TEK) {
3470 case TEK_Complex:
3471 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3472 /*init*/ true);
3473 return;
3474 case TEK_Scalar: {
3475 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3476 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3477 return;
3478 }
3479 case TEK_Aggregate:
3480 llvm_unreachable("evaluation kind filtered out!");
3481 }
3482 llvm_unreachable("bad evaluation kind");
3483 }
3484
3485 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3486
3487 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3488
3489 // Check for a copy expression. If we don't have a copy expression,
3490 // that means a trivial copy is okay.
3491 const Expr *copyExpr = CatchParam.getInit();
3492 if (!copyExpr) {
3493 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3494 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3495 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3496 return;
3497 }
3498
3499 // We have to call __cxa_get_exception_ptr to get the adjusted
3500 // pointer before copying.
3501 llvm::CallInst *rawAdjustedExn =
3502 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3503
3504 // Cast that to the appropriate type.
3505 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3506
3507 // The copy expression is defined in terms of an OpaqueValueExpr.
3508 // Find it and map it to the adjusted expression.
3509 CodeGenFunction::OpaqueValueMapping
3510 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3511 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3512
3513 // Call the copy ctor in a terminate scope.
3514 CGF.EHStack.pushTerminate();
3515
3516 // Perform the copy construction.
3517 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3518 CGF.EmitAggExpr(copyExpr,
3519 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3520 AggValueSlot::IsNotDestructed,
3521 AggValueSlot::DoesNotNeedGCBarriers,
3522 AggValueSlot::IsNotAliased));
3523
3524 // Leave the terminate scope.
3525 CGF.EHStack.popTerminate();
3526
3527 // Undo the opaque value mapping.
3528 opaque.pop();
3529
3530 // Finally we can call __cxa_begin_catch.
3531 CallBeginCatch(CGF, Exn, true);
3532}
3533
3534/// Begins a catch statement by initializing the catch variable and
3535/// calling __cxa_begin_catch.
3536void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3537 const CXXCatchStmt *S) {
3538 // We have to be very careful with the ordering of cleanups here:
3539 // C++ [except.throw]p4:
3540 // The destruction [of the exception temporary] occurs
3541 // immediately after the destruction of the object declared in
3542 // the exception-declaration in the handler.
3543 //
3544 // So the precise ordering is:
3545 // 1. Construct catch variable.
3546 // 2. __cxa_begin_catch
3547 // 3. Enter __cxa_end_catch cleanup
3548 // 4. Enter dtor cleanup
3549 //
3550 // We do this by using a slightly abnormal initialization process.
3551 // Delegation sequence:
3552 // - ExitCXXTryStmt opens a RunCleanupsScope
3553 // - EmitAutoVarAlloca creates the variable and debug info
3554 // - InitCatchParam initializes the variable from the exception
3555 // - CallBeginCatch calls __cxa_begin_catch
3556 // - CallBeginCatch enters the __cxa_end_catch cleanup
3557 // - EmitAutoVarCleanups enters the variable destructor cleanup
3558 // - EmitCXXTryStmt emits the code for the catch body
3559 // - EmitCXXTryStmt close the RunCleanupsScope
3560
3561 VarDecl *CatchParam = S->getExceptionDecl();
3562 if (!CatchParam) {
3563 llvm::Value *Exn = CGF.getExceptionFromSlot();
3564 CallBeginCatch(CGF, Exn, true);
3565 return;
3566 }
3567
3568 // Emit the local.
3569 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3570 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3571 CGF.EmitAutoVarCleanups(var);
3572}
3573
3574/// Get or define the following function:
3575/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3576/// This code is used only in C++.
3577static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3578 llvm::FunctionType *fnTy =
3579 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3580 llvm::Constant *fnRef =
3581 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3582
3583 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3584 if (fn && fn->empty()) {
3585 fn->setDoesNotThrow();
3586 fn->setDoesNotReturn();
3587
3588 // What we really want is to massively penalize inlining without
3589 // forbidding it completely. The difference between that and
3590 // 'noinline' is negligible.
3591 fn->addFnAttr(llvm::Attribute::NoInline);
3592
3593 // Allow this function to be shared across translation units, but
3594 // we don't want it to turn into an exported symbol.
3595 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3596 fn->setVisibility(llvm::Function::HiddenVisibility);
3597 if (CGM.supportsCOMDAT())
3598 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
3599
3600 // Set up the function.
3601 llvm::BasicBlock *entry =
3602 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3603 CGBuilderTy builder(entry);
3604
3605 // Pull the exception pointer out of the parameter list.
3606 llvm::Value *exn = &*fn->arg_begin();
3607
3608 // Call __cxa_begin_catch(exn).
3609 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3610 catchCall->setDoesNotThrow();
3611 catchCall->setCallingConv(CGM.getRuntimeCC());
3612
3613 // Call std::terminate().
3614 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
3615 termCall->setDoesNotThrow();
3616 termCall->setDoesNotReturn();
3617 termCall->setCallingConv(CGM.getRuntimeCC());
3618
3619 // std::terminate cannot return.
3620 builder.CreateUnreachable();
3621 }
3622
3623 return fnRef;
3624}
3625
3626llvm::CallInst *
3627ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3628 llvm::Value *Exn) {
3629 // In C++, we want to call __cxa_begin_catch() before terminating.
3630 if (Exn) {
3631 assert(CGF.CGM.getLangOpts().CPlusPlus);
3632 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3633 }
3634 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3635}