blob: 58786fe2ce0ef6d58ff7454de54f93c9318f8e89 [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 *
David Majnemer37b417f2015-03-29 21:55:10 +0000130 getAddrOfCXXCatchHandlerType(QualType Ty,
131 QualType CatchHandlerType) override {
David Majnemer443250f2015-03-17 20:35:00 +0000132 return getAddrOfRTTIDescriptor(Ty);
133 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000134
David Majnemer1162d252014-06-22 19:05:33 +0000135 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
136 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
137 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
138 llvm::Value *ThisPtr,
139 llvm::Type *StdTypeInfoPtrTy) override;
140
141 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
142 QualType SrcRecordTy) override;
143
144 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
145 QualType SrcRecordTy, QualType DestTy,
146 QualType DestRecordTy,
147 llvm::BasicBlock *CastEnd) override;
148
149 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
150 QualType SrcRecordTy,
151 QualType DestTy) override;
152
153 bool EmitBadCastCall(CodeGenFunction &CGF) override;
154
Craig Topper4f12f102014-03-12 06:41:41 +0000155 llvm::Value *
156 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
157 const CXXRecordDecl *ClassDecl,
158 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000159
Craig Topper4f12f102014-03-12 06:41:41 +0000160 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000161
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000162 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
163 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000164
Reid Klecknere7de47e2013-07-22 13:51:44 +0000165 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000166 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000167 // Itanium does not emit any destructor variant as an inline thunk.
168 // Delegating may occur as an optimization, but all variants are either
169 // emitted with external linkage or as linkonce if they are inline and used.
170 return false;
171 }
172
Craig Topper4f12f102014-03-12 06:41:41 +0000173 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000174
Reid Kleckner89077a12013-12-17 19:46:40 +0000175 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000176 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000177
Craig Topper4f12f102014-03-12 06:41:41 +0000178 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000179
Reid Kleckner89077a12013-12-17 19:46:40 +0000180 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
181 const CXXConstructorDecl *D,
182 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000183 bool Delegating,
184 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000185
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000186 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
187 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000188 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000189
Craig Topper4f12f102014-03-12 06:41:41 +0000190 void emitVTableDefinitions(CodeGenVTables &CGVT,
191 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000192
193 llvm::Value *getVTableAddressPointInStructor(
194 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
195 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000196 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000197
198 llvm::Constant *
199 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000200 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000201
202 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000203 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000204
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000205 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000206 llvm::Value *This,
207 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000208
David Majnemer0c0b6d92014-10-31 20:09:12 +0000209 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
210 const CXXDestructorDecl *Dtor,
211 CXXDtorType DtorType,
212 llvm::Value *This,
213 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000214
Craig Topper4f12f102014-03-12 06:41:41 +0000215 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000216
Hans Wennborgc94391d2014-06-06 20:04:01 +0000217 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
218 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000219 // Allow inlining of thunks by emitting them with available_externally
220 // linkage together with vtables when needed.
221 if (ForVTable)
222 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
223 }
224
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000225 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000226 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000227
228 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000229 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000230
David Majnemer196ac332014-09-11 23:05:02 +0000231 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
232 FunctionArgList &Args) const override {
233 assert(!Args.empty() && "expected the arglist to not be empty!");
234 return Args.size() - 1;
235 }
236
Craig Topper4f12f102014-03-12 06:41:41 +0000237 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
238 StringRef GetDeletedVirtualCallName() override
239 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000240
Craig Topper4f12f102014-03-12 06:41:41 +0000241 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000242 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
243 llvm::Value *NewPtr,
244 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000245 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000246 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000247 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
248 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000249 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000250
John McCallcdf7ef52010-11-06 09:44:32 +0000251 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000252 llvm::GlobalVariable *DeclPtr,
253 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000254 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000255 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000256
257 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000258 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000259 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000260 CodeGenModule &CGM,
261 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
262 CXXThreadLocals,
263 ArrayRef<llvm::Function *> CXXThreadLocalInits,
264 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
265
266 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000267 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
268 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000269
Craig Topper4f12f102014-03-12 06:41:41 +0000270 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000271
272 /**************************** RTTI Uniqueness ******************************/
273
274protected:
275 /// Returns true if the ABI requires RTTI type_info objects to be unique
276 /// across a program.
277 virtual bool shouldRTTIBeUnique() const { return true; }
278
279public:
280 /// What sort of unique-RTTI behavior should we use?
281 enum RTTIUniquenessKind {
282 /// We are guaranteeing, or need to guarantee, that the RTTI string
283 /// is unique.
284 RUK_Unique,
285
286 /// We are not guaranteeing uniqueness for the RTTI string, so we
287 /// can demote to hidden visibility but must use string comparisons.
288 RUK_NonUniqueHidden,
289
290 /// We are not guaranteeing uniqueness for the RTTI string, so we
291 /// have to use string comparisons, but we also have to emit it with
292 /// non-hidden visibility.
293 RUK_NonUniqueVisible
294 };
295
296 /// Return the required visibility status for the given type and linkage in
297 /// the current ABI.
298 RTTIUniquenessKind
299 classifyRTTIUniqueness(QualType CanTy,
300 llvm::GlobalValue::LinkageTypes Linkage) const;
301 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000302
303 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000304};
John McCall86353412010-08-21 22:46:04 +0000305
306class ARMCXXABI : public ItaniumCXXABI {
307public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000308 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
309 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
310 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000311
Craig Topper4f12f102014-03-12 06:41:41 +0000312 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000313 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
314 isa<CXXDestructorDecl>(GD.getDecl()) &&
315 GD.getDtorType() != Dtor_Deleting));
316 }
John McCall5d865c322010-08-31 07:33:07 +0000317
Craig Topper4f12f102014-03-12 06:41:41 +0000318 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
319 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000320
Craig Topper4f12f102014-03-12 06:41:41 +0000321 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000322 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
323 llvm::Value *NewPtr,
324 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000325 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000326 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000327 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000328 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000329};
Tim Northovera2ee4332014-03-29 15:09:45 +0000330
331class iOS64CXXABI : public ARMCXXABI {
332public:
333 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000334
335 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000336 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000337};
Charles Davis4e786dd2010-05-25 19:52:27 +0000338}
339
Charles Davis53c59df2010-08-16 03:33:14 +0000340CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000341 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000342 // For IR-generation purposes, there's no significant difference
343 // between the ARM and iOS ABIs.
344 case TargetCXXABI::GenericARM:
345 case TargetCXXABI::iOS:
346 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000347
Tim Northovera2ee4332014-03-29 15:09:45 +0000348 case TargetCXXABI::iOS64:
349 return new iOS64CXXABI(CGM);
350
Tim Northover9bb857a2013-01-31 12:13:10 +0000351 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
352 // include the other 32-bit ARM oddities: constructor/destructor return values
353 // and array cookies.
354 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000355 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
356 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000357
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000358 case TargetCXXABI::GenericMIPS:
359 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
360
John McCall57625922013-01-25 23:36:14 +0000361 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000362 if (CGM.getContext().getTargetInfo().getTriple().getArch()
363 == llvm::Triple::le32) {
364 // For PNaCl, use ARM-style method pointers so that PNaCl code
365 // does not assume anything about the alignment of function
366 // pointers.
367 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
368 /* UseARMGuardVarABI = */ false);
369 }
John McCall57625922013-01-25 23:36:14 +0000370 return new ItaniumCXXABI(CGM);
371
372 case TargetCXXABI::Microsoft:
373 llvm_unreachable("Microsoft ABI is not Itanium-based");
374 }
375 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000376}
377
Chris Lattnera5f58b02011-07-09 17:41:47 +0000378llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000379ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
380 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000381 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000382 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000383}
384
John McCalld9c6c0b2010-08-22 00:59:17 +0000385/// In the Itanium and ARM ABIs, method pointers have the form:
386/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
387///
388/// In the Itanium ABI:
389/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
390/// - the this-adjustment is (memptr.adj)
391/// - the virtual offset is (memptr.ptr - 1)
392///
393/// In the ARM ABI:
394/// - method pointers are virtual if (memptr.adj & 1) is nonzero
395/// - the this-adjustment is (memptr.adj >> 1)
396/// - the virtual offset is (memptr.ptr)
397/// ARM uses 'adj' for the virtual flag because Thumb functions
398/// may be only single-byte aligned.
399///
400/// If the member is virtual, the adjusted 'this' pointer points
401/// to a vtable pointer from which the virtual offset is applied.
402///
403/// If the member is non-virtual, memptr.ptr is the address of
404/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000405llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
406 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
407 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000408 CGBuilderTy &Builder = CGF.Builder;
409
410 const FunctionProtoType *FPT =
411 MPT->getPointeeType()->getAs<FunctionProtoType>();
412 const CXXRecordDecl *RD =
413 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
414
Chris Lattner2192fe52011-07-18 04:24:23 +0000415 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000416 CGM.getTypes().GetFunctionType(
417 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000418
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000419 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000420
John McCalld9c6c0b2010-08-22 00:59:17 +0000421 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
422 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
423 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
424
John McCalla1dee5302010-08-22 10:59:02 +0000425 // Extract memptr.adj, which is in the second field.
426 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000427
428 // Compute the true adjustment.
429 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000430 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000431 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000432
433 // Apply the adjustment and cast back to the original struct type
434 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000435 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
436 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
437 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000438
439 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000440 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000441
442 // If the LSB in the function pointer is 1, the function pointer points to
443 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000444 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000445 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000446 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
447 else
448 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
449 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000450 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
451
452 // In the virtual path, the adjustment left 'This' pointing to the
453 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000454 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000455 CGF.EmitBlock(FnVirtual);
456
457 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000458 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000459 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000460
461 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000462 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000463 if (!UseARMMethodPtrABI)
464 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000465 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000466
467 // Load the virtual function to call.
468 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000469 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000470 CGF.EmitBranch(FnEnd);
471
472 // In the non-virtual path, the function pointer is actually a
473 // function pointer.
474 CGF.EmitBlock(FnNonVirtual);
475 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000476 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000477
478 // We're done.
479 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000480 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000481 Callee->addIncoming(VirtualFn, FnVirtual);
482 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
483 return Callee;
484}
John McCalla8bbb822010-08-22 03:04:22 +0000485
John McCallc134eb52010-08-31 21:07:20 +0000486/// Compute an l-value by applying the given pointer-to-member to a
487/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000488llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
489 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
490 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000491 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000492
493 CGBuilderTy &Builder = CGF.Builder;
494
Micah Villmowea2fea22012-10-25 15:39:14 +0000495 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000496
497 // Cast to char*.
498 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
499
500 // Apply the offset, which we assume is non-null.
501 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
502
503 // Cast the address to the appropriate pointer type, adopting the
504 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000505 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000506 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000507 return Builder.CreateBitCast(Addr, PType);
508}
509
John McCallc62bb392012-02-15 01:22:51 +0000510/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
511/// conversion.
512///
513/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000514///
515/// Obligatory offset/adjustment diagram:
516/// <-- offset --> <-- adjustment -->
517/// |--------------------------|----------------------|--------------------|
518/// ^Derived address point ^Base address point ^Member address point
519///
520/// So when converting a base member pointer to a derived member pointer,
521/// we add the offset to the adjustment because the address point has
522/// decreased; and conversely, when converting a derived MP to a base MP
523/// we subtract the offset from the adjustment because the address point
524/// has increased.
525///
526/// The standard forbids (at compile time) conversion to and from
527/// virtual bases, which is why we don't have to consider them here.
528///
529/// The standard forbids (at run time) casting a derived MP to a base
530/// MP when the derived MP does not point to a member of the base.
531/// This is why -1 is a reasonable choice for null data member
532/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000533llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000534ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
535 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000536 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000537 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000538 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
539 E->getCastKind() == CK_ReinterpretMemberPointer);
540
541 // Under Itanium, reinterprets don't require any additional processing.
542 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
543
544 // Use constant emission if we can.
545 if (isa<llvm::Constant>(src))
546 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
547
548 llvm::Constant *adj = getMemberPointerAdjustment(E);
549 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000550
551 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000552 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000553
John McCallc62bb392012-02-15 01:22:51 +0000554 const MemberPointerType *destTy =
555 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000556
John McCall7a9aac22010-08-23 01:21:21 +0000557 // For member data pointers, this is just a matter of adding the
558 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000559 if (destTy->isMemberDataPointer()) {
560 llvm::Value *dst;
561 if (isDerivedToBase)
562 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000563 else
John McCallc62bb392012-02-15 01:22:51 +0000564 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000565
566 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000567 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
568 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
569 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000570 }
571
John McCalla1dee5302010-08-22 10:59:02 +0000572 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000573 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000574 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
575 offset <<= 1;
576 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000577 }
578
John McCallc62bb392012-02-15 01:22:51 +0000579 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
580 llvm::Value *dstAdj;
581 if (isDerivedToBase)
582 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000583 else
John McCallc62bb392012-02-15 01:22:51 +0000584 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000585
John McCallc62bb392012-02-15 01:22:51 +0000586 return Builder.CreateInsertValue(src, dstAdj, 1);
587}
588
589llvm::Constant *
590ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
591 llvm::Constant *src) {
592 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
593 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
594 E->getCastKind() == CK_ReinterpretMemberPointer);
595
596 // Under Itanium, reinterprets don't require any additional processing.
597 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
598
599 // If the adjustment is trivial, we don't need to do anything.
600 llvm::Constant *adj = getMemberPointerAdjustment(E);
601 if (!adj) return src;
602
603 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
604
605 const MemberPointerType *destTy =
606 E->getType()->castAs<MemberPointerType>();
607
608 // For member data pointers, this is just a matter of adding the
609 // offset if the source is non-null.
610 if (destTy->isMemberDataPointer()) {
611 // null maps to null.
612 if (src->isAllOnesValue()) return src;
613
614 if (isDerivedToBase)
615 return llvm::ConstantExpr::getNSWSub(src, adj);
616 else
617 return llvm::ConstantExpr::getNSWAdd(src, adj);
618 }
619
620 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000621 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000622 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
623 offset <<= 1;
624 adj = llvm::ConstantInt::get(adj->getType(), offset);
625 }
626
627 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
628 llvm::Constant *dstAdj;
629 if (isDerivedToBase)
630 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
631 else
632 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
633
634 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000635}
John McCall84fa5102010-08-22 04:16:24 +0000636
637llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000638ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000639 // Itanium C++ ABI 2.3:
640 // A NULL pointer is represented as -1.
641 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000642 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000643
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000644 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000645 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000646 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000647}
648
John McCallf3a88602011-02-03 08:15:49 +0000649llvm::Constant *
650ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
651 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000652 // Itanium C++ ABI 2.3:
653 // A pointer to data member is an offset from the base address of
654 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000655 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000656}
657
John McCall2979fe02011-04-12 00:42:48 +0000658llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000659 return BuildMemberPointer(MD, CharUnits::Zero());
660}
661
662llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
663 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000664 assert(MD->isInstance() && "Member function must not be static!");
665 MD = MD->getCanonicalDecl();
666
667 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000668
669 // Get the function pointer (or index if this is a virtual function).
670 llvm::Constant *MemPtr[2];
671 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000672 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000673
Ken Dyckdf016282011-04-09 01:30:02 +0000674 const ASTContext &Context = getContext();
675 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000676 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000677 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000678
Mark Seabornedf0d382013-07-24 16:25:13 +0000679 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000680 // ARM C++ ABI 3.2.1:
681 // This ABI specifies that adj contains twice the this
682 // adjustment, plus 1 if the member function is virtual. The
683 // least significant bit of adj then makes exactly the same
684 // discrimination as the least significant bit of ptr does for
685 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000686 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
687 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000688 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000689 } else {
690 // Itanium C++ ABI 2.3:
691 // For a virtual function, [the pointer field] is 1 plus the
692 // virtual table offset (in bytes) of the function,
693 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000694 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
695 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000696 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000697 }
698 } else {
John McCall2979fe02011-04-12 00:42:48 +0000699 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000700 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000701 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000702 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000703 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000704 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000705 } else {
John McCall2979fe02011-04-12 00:42:48 +0000706 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
707 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000708 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000709 }
John McCall2979fe02011-04-12 00:42:48 +0000710 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000711
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000712 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000713 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
714 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000715 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000716 }
John McCall1c456c82010-08-22 06:43:33 +0000717
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000718 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000719}
720
Richard Smithdafff942012-01-14 04:30:29 +0000721llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
722 QualType MPType) {
723 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
724 const ValueDecl *MPD = MP.getMemberPointerDecl();
725 if (!MPD)
726 return EmitNullMemberPointer(MPT);
727
Reid Kleckner452abac2013-05-09 21:01:17 +0000728 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000729
730 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
731 return BuildMemberPointer(MD, ThisAdjustment);
732
733 CharUnits FieldOffset =
734 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
735 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
736}
737
John McCall131d97d2010-08-22 08:30:07 +0000738/// The comparison algorithm is pretty easy: the member pointers are
739/// the same if they're either bitwise identical *or* both null.
740///
741/// ARM is different here only because null-ness is more complicated.
742llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000743ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
744 llvm::Value *L,
745 llvm::Value *R,
746 const MemberPointerType *MPT,
747 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000748 CGBuilderTy &Builder = CGF.Builder;
749
John McCall131d97d2010-08-22 08:30:07 +0000750 llvm::ICmpInst::Predicate Eq;
751 llvm::Instruction::BinaryOps And, Or;
752 if (Inequality) {
753 Eq = llvm::ICmpInst::ICMP_NE;
754 And = llvm::Instruction::Or;
755 Or = llvm::Instruction::And;
756 } else {
757 Eq = llvm::ICmpInst::ICMP_EQ;
758 And = llvm::Instruction::And;
759 Or = llvm::Instruction::Or;
760 }
761
John McCall7a9aac22010-08-23 01:21:21 +0000762 // Member data pointers are easy because there's a unique null
763 // value, so it just comes down to bitwise equality.
764 if (MPT->isMemberDataPointer())
765 return Builder.CreateICmp(Eq, L, R);
766
767 // For member function pointers, the tautologies are more complex.
768 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000769 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000770 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000771 // (L == R) <==> (L.ptr == R.ptr &&
772 // (L.adj == R.adj ||
773 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000774 // The inequality tautologies have exactly the same structure, except
775 // applying De Morgan's laws.
776
777 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
778 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
779
John McCall131d97d2010-08-22 08:30:07 +0000780 // This condition tests whether L.ptr == R.ptr. This must always be
781 // true for equality to hold.
782 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
783
784 // This condition, together with the assumption that L.ptr == R.ptr,
785 // tests whether the pointers are both null. ARM imposes an extra
786 // condition.
787 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
788 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
789
790 // This condition tests whether L.adj == R.adj. If this isn't
791 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000792 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
793 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000794 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
795
796 // Null member function pointers on ARM clear the low bit of Adj,
797 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000798 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000799 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
800
801 // Compute (l.adj | r.adj) & 1 and test it against zero.
802 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
803 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
804 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
805 "cmp.or.adj");
806 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
807 }
808
809 // Tie together all our conditions.
810 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
811 Result = Builder.CreateBinOp(And, PtrEq, Result,
812 Inequality ? "memptr.ne" : "memptr.eq");
813 return Result;
814}
815
816llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000817ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
818 llvm::Value *MemPtr,
819 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000820 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000821
822 /// For member data pointers, this is just a check against -1.
823 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000824 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000825 llvm::Value *NegativeOne =
826 llvm::Constant::getAllOnesValue(MemPtr->getType());
827 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
828 }
John McCall131d97d2010-08-22 08:30:07 +0000829
Daniel Dunbar914bc412011-04-19 23:10:47 +0000830 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000831 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000832
833 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
834 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
835
Daniel Dunbar914bc412011-04-19 23:10:47 +0000836 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
837 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000838 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000839 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000840 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000841 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000842 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
843 "memptr.isvirtual");
844 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000845 }
846
847 return Result;
848}
John McCall1c456c82010-08-22 06:43:33 +0000849
Reid Kleckner40ca9132014-05-13 22:05:45 +0000850bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
851 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
852 if (!RD)
853 return false;
854
Reid Klecknerd355ca72014-05-15 01:26:32 +0000855 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
856 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
857 // special members.
858 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000859 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
860 return true;
861 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000862 return false;
863}
864
John McCall614dbdc2010-08-22 21:01:12 +0000865/// The Itanium ABI requires non-zero initialization only for data
866/// member pointers, for which '0' is a valid offset.
867bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000868 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000869}
John McCall5d865c322010-08-31 07:33:07 +0000870
John McCall82fb8922012-09-25 10:10:39 +0000871/// The Itanium ABI always places an offset to the complete object
872/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000873void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
874 const CXXDeleteExpr *DE,
875 llvm::Value *Ptr,
876 QualType ElementType,
877 const CXXDestructorDecl *Dtor) {
878 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000879 if (UseGlobalDelete) {
880 // Derive the complete-object pointer, which is what we need
881 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000882
David Majnemer0c0b6d92014-10-31 20:09:12 +0000883 // Grab the vtable pointer as an intptr_t*.
884 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000885
David Majnemer0c0b6d92014-10-31 20:09:12 +0000886 // Track back to entry -2 and pull out the offset there.
887 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
888 VTable, -2, "complete-offset.ptr");
889 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
890 Offset->setAlignment(CGF.PointerAlignInBytes);
891
892 // Apply the offset.
893 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
894 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
895
896 // If we're supposed to call the global delete, make sure we do so
897 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000898 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
899 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000900 }
901
902 // FIXME: Provide a source location here even though there's no
903 // CXXMemberCallExpr for dtor call.
904 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
905 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
906
907 if (UseGlobalDelete)
908 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000909}
910
David Majnemer442d0a22014-11-25 07:20:20 +0000911void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
912 // void __cxa_rethrow();
913
914 llvm::FunctionType *FTy =
915 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
916
917 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
918
919 if (isNoReturn)
920 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
921 else
922 CGF.EmitRuntimeCallOrInvoke(Fn);
923}
924
David Majnemer7c237072015-03-05 00:46:22 +0000925static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
926 // void *__cxa_allocate_exception(size_t thrown_size);
927
928 llvm::FunctionType *FTy =
929 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
930
931 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
932}
933
934static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
935 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
936 // void (*dest) (void *));
937
938 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
939 llvm::FunctionType *FTy =
940 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
941
942 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
943}
944
945void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
946 QualType ThrowType = E->getSubExpr()->getType();
947 // Now allocate the exception object.
948 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
949 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
950
951 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
952 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
953 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
954
955 CGF.EmitAnyExprToExn(E->getSubExpr(), ExceptionPtr);
956
957 // Now throw the exception.
958 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
959 /*ForEH=*/true);
960
961 // The address of the destructor. If the exception type has a
962 // trivial destructor (or isn't a record), we just pass null.
963 llvm::Constant *Dtor = nullptr;
964 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
965 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
966 if (!Record->hasTrivialDestructor()) {
967 CXXDestructorDecl *DtorD = Record->getDestructor();
968 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
969 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
970 }
971 }
972 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
973
974 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
975 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
976}
977
David Majnemer1162d252014-06-22 19:05:33 +0000978static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
979 // void *__dynamic_cast(const void *sub,
980 // const abi::__class_type_info *src,
981 // const abi::__class_type_info *dst,
982 // std::ptrdiff_t src2dst_offset);
983
984 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
985 llvm::Type *PtrDiffTy =
986 CGF.ConvertType(CGF.getContext().getPointerDiffType());
987
988 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
989
990 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
991
992 // Mark the function as nounwind readonly.
993 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
994 llvm::Attribute::ReadOnly };
995 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
996 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
997
998 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
999}
1000
1001static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1002 // void __cxa_bad_cast();
1003 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1004 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1005}
1006
1007/// \brief Compute the src2dst_offset hint as described in the
1008/// Itanium C++ ABI [2.9.7]
1009static CharUnits computeOffsetHint(ASTContext &Context,
1010 const CXXRecordDecl *Src,
1011 const CXXRecordDecl *Dst) {
1012 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1013 /*DetectVirtual=*/false);
1014
1015 // If Dst is not derived from Src we can skip the whole computation below and
1016 // return that Src is not a public base of Dst. Record all inheritance paths.
1017 if (!Dst->isDerivedFrom(Src, Paths))
1018 return CharUnits::fromQuantity(-2ULL);
1019
1020 unsigned NumPublicPaths = 0;
1021 CharUnits Offset;
1022
1023 // Now walk all possible inheritance paths.
1024 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
1025 ++I) {
1026 if (I->Access != AS_public) // Ignore non-public inheritance.
1027 continue;
1028
1029 ++NumPublicPaths;
1030
1031 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
1032 // If the path contains a virtual base class we can't give any hint.
1033 // -1: no hint.
1034 if (J->Base->isVirtual())
1035 return CharUnits::fromQuantity(-1ULL);
1036
1037 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1038 continue;
1039
1040 // Accumulate the base class offsets.
1041 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
1042 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
1043 }
1044 }
1045
1046 // -2: Src is not a public base of Dst.
1047 if (NumPublicPaths == 0)
1048 return CharUnits::fromQuantity(-2ULL);
1049
1050 // -3: Src is a multiple public base type but never a virtual base type.
1051 if (NumPublicPaths > 1)
1052 return CharUnits::fromQuantity(-3ULL);
1053
1054 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1055 // Return the offset of Src from the origin of Dst.
1056 return Offset;
1057}
1058
1059static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1060 // void __cxa_bad_typeid();
1061 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1062
1063 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1064}
1065
1066bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1067 QualType SrcRecordTy) {
1068 return IsDeref;
1069}
1070
1071void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1072 llvm::Value *Fn = getBadTypeidFn(CGF);
1073 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1074 CGF.Builder.CreateUnreachable();
1075}
1076
1077llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1078 QualType SrcRecordTy,
1079 llvm::Value *ThisPtr,
1080 llvm::Type *StdTypeInfoPtrTy) {
1081 llvm::Value *Value =
1082 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1083
1084 // Load the type info.
1085 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1086 return CGF.Builder.CreateLoad(Value);
1087}
1088
1089bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1090 QualType SrcRecordTy) {
1091 return SrcIsPtr;
1092}
1093
1094llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1095 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1096 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1097 llvm::Type *PtrDiffLTy =
1098 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1099 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1100
1101 llvm::Value *SrcRTTI =
1102 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1103 llvm::Value *DestRTTI =
1104 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1105
1106 // Compute the offset hint.
1107 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1108 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1109 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1110 PtrDiffLTy,
1111 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1112
1113 // Emit the call to __dynamic_cast.
1114 Value = CGF.EmitCastToVoidPtr(Value);
1115
1116 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1117 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1118 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1119
1120 /// C++ [expr.dynamic.cast]p9:
1121 /// A failed cast to reference type throws std::bad_cast
1122 if (DestTy->isReferenceType()) {
1123 llvm::BasicBlock *BadCastBlock =
1124 CGF.createBasicBlock("dynamic_cast.bad_cast");
1125
1126 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1127 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1128
1129 CGF.EmitBlock(BadCastBlock);
1130 EmitBadCastCall(CGF);
1131 }
1132
1133 return Value;
1134}
1135
1136llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1137 llvm::Value *Value,
1138 QualType SrcRecordTy,
1139 QualType DestTy) {
1140 llvm::Type *PtrDiffLTy =
1141 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1142 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1143
1144 // Get the vtable pointer.
1145 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1146
1147 // Get the offset-to-top from the vtable.
1148 llvm::Value *OffsetToTop =
1149 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1150 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1151
1152 // Finally, add the offset to the pointer.
1153 Value = CGF.EmitCastToVoidPtr(Value);
1154 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1155
1156 return CGF.Builder.CreateBitCast(Value, DestLTy);
1157}
1158
1159bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1160 llvm::Value *Fn = getBadCastFn(CGF);
1161 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1162 CGF.Builder.CreateUnreachable();
1163 return true;
1164}
1165
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001166llvm::Value *
1167ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1168 llvm::Value *This,
1169 const CXXRecordDecl *ClassDecl,
1170 const CXXRecordDecl *BaseClassDecl) {
1171 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1172 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001173 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1174 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001175
1176 llvm::Value *VBaseOffsetPtr =
1177 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1178 "vbase.offset.ptr");
1179 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1180 CGM.PtrDiffTy->getPointerTo());
1181
1182 llvm::Value *VBaseOffset =
1183 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1184
1185 return VBaseOffset;
1186}
1187
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001188void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1189 // Just make sure we're in sync with TargetCXXABI.
1190 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1191
Rafael Espindolac3cde362013-12-09 14:51:17 +00001192 // The constructor used for constructing this as a base class;
1193 // ignores virtual bases.
1194 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1195
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001196 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001197 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001198 if (!D->getParent()->isAbstract()) {
1199 // We don't need to emit the complete ctor if the class is abstract.
1200 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1201 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001202}
1203
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001204void
1205ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1206 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001207 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001208
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001209 // All parameters are already in place except VTT, which goes after 'this'.
1210 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001211
1212 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001213 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1214 ArgTys.insert(ArgTys.begin() + 1,
1215 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001216}
1217
Reid Klecknere7de47e2013-07-22 13:51:44 +00001218void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001219 // The destructor used for destructing this as a base class; ignores
1220 // virtual bases.
1221 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001222
1223 // The destructor used for destructing this as a most-derived class;
1224 // call the base destructor and then destructs any virtual bases.
1225 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1226
Rafael Espindolac3cde362013-12-09 14:51:17 +00001227 // The destructor in a virtual table is always a 'deleting'
1228 // destructor, which calls the complete destructor and then uses the
1229 // appropriate operator delete.
1230 if (D->isVirtual())
1231 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001232}
1233
Reid Kleckner89077a12013-12-17 19:46:40 +00001234void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1235 QualType &ResTy,
1236 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001237 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001238 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001239
1240 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001241 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001242 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001243
1244 // FIXME: avoid the fake decl
1245 QualType T = Context.getPointerType(Context.VoidPtrTy);
1246 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001247 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001248 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001249 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001250 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001251 }
1252}
1253
John McCall5d865c322010-08-31 07:33:07 +00001254void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1255 /// Initialize the 'this' slot.
1256 EmitThisParam(CGF);
1257
1258 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001259 if (getStructorImplicitParamDecl(CGF)) {
1260 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1261 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001262 }
John McCall5d865c322010-08-31 07:33:07 +00001263
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001264 /// If this is a function that the ABI specifies returns 'this', initialize
1265 /// the return slot to 'this' at the start of the function.
1266 ///
1267 /// Unlike the setting of return types, this is done within the ABI
1268 /// implementation instead of by clients of CGCXXABI because:
1269 /// 1) getThisValue is currently protected
1270 /// 2) in theory, an ABI could implement 'this' returns some other way;
1271 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001272 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001273 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001274}
1275
Reid Kleckner89077a12013-12-17 19:46:40 +00001276unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1277 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1278 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1279 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1280 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001281
Reid Kleckner89077a12013-12-17 19:46:40 +00001282 // Insert the implicit 'vtt' argument as the second argument.
1283 llvm::Value *VTT =
1284 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1285 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1286 Args.insert(Args.begin() + 1,
1287 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1288 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001289}
1290
1291void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1292 const CXXDestructorDecl *DD,
1293 CXXDtorType Type, bool ForVirtualBase,
1294 bool Delegating, llvm::Value *This) {
1295 GlobalDecl GD(DD, Type);
1296 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1297 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1298
Craig Topper8a13c412014-05-21 05:09:00 +00001299 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001300 if (getContext().getLangOpts().AppleKext)
1301 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1302
1303 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001304 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001305
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001306 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1307 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001308}
1309
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001310void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1311 const CXXRecordDecl *RD) {
1312 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1313 if (VTable->hasInitializer())
1314 return;
1315
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001316 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001317 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1318 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001319 llvm::Constant *RTTI =
1320 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001321
1322 // Create and set the initializer.
1323 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1324 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001325 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001326 VTable->setInitializer(Init);
1327
1328 // Set the correct linkage.
1329 VTable->setLinkage(Linkage);
1330
Derek Schuff2312bd32015-05-08 16:47:21 +00001331 CGM.maybeSetTrivialComdat(*VTable);
Rafael Espindolacb92c192015-01-15 23:18:01 +00001332
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) {
David Blaikiee3b172a2015-04-02 18:55:21 +00001390 auto *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001391
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
David Blaikiee3b172a2015-04-02 18:55:21 +00001401 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1402 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001403}
1404
1405llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1406 CharUnits VPtrOffset) {
1407 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1408
1409 llvm::GlobalVariable *&VTable = VTables[RD];
1410 if (VTable)
1411 return VTable;
1412
1413 // Queue up this v-table for possible deferred emission.
1414 CGM.addDeferredVTable(RD);
1415
1416 SmallString<256> OutName;
1417 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001418 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001419 Out.flush();
1420 StringRef Name = OutName.str();
1421
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001422 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001423 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1424 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1425
1426 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1427 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1428 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001429
1430 if (RD->hasAttr<DLLImportAttr>())
1431 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1432 else if (RD->hasAttr<DLLExportAttr>())
1433 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1434
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001435 return VTable;
1436}
1437
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001438llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1439 GlobalDecl GD,
1440 llvm::Value *This,
1441 llvm::Type *Ty) {
1442 GD = GD.getCanonicalDecl();
1443 Ty = Ty->getPointerTo()->getPointerTo();
1444 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1445
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00001446 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
1447 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001448
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001449 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001450 llvm::Value *VFuncPtr =
1451 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1452 return CGF.Builder.CreateLoad(VFuncPtr);
1453}
1454
David Majnemer0c0b6d92014-10-31 20:09:12 +00001455llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1456 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1457 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001458 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001459 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1460
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001461 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1462 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001463 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001464 llvm::Value *Callee =
1465 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001466
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001467 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1468 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001469 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001470}
1471
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001472void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001473 CodeGenVTables &VTables = CGM.getVTables();
1474 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001475 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001476}
1477
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001478static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1479 llvm::Value *Ptr,
1480 int64_t NonVirtualAdjustment,
1481 int64_t VirtualAdjustment,
1482 bool IsReturnAdjustment) {
1483 if (!NonVirtualAdjustment && !VirtualAdjustment)
1484 return Ptr;
1485
1486 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1487 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1488
1489 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1490 // Perform the non-virtual adjustment for a base-to-derived cast.
1491 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1492 }
1493
1494 if (VirtualAdjustment) {
1495 llvm::Type *PtrDiffTy =
1496 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1497
1498 // Perform the virtual adjustment.
1499 llvm::Value *VTablePtrPtr =
1500 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1501
1502 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1503
1504 llvm::Value *OffsetPtr =
1505 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1506
1507 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1508
1509 // Load the adjustment offset from the vtable.
1510 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1511
1512 // Adjust our pointer.
1513 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1514 }
1515
1516 if (NonVirtualAdjustment && IsReturnAdjustment) {
1517 // Perform the non-virtual adjustment for a derived-to-base cast.
1518 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1519 }
1520
1521 // Cast back to the original type.
1522 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1523}
1524
1525llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1526 llvm::Value *This,
1527 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001528 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1529 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001530 /*IsReturnAdjustment=*/false);
1531}
1532
1533llvm::Value *
1534ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1535 const ReturnAdjustment &RA) {
1536 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1537 RA.Virtual.Itanium.VBaseOffsetOffset,
1538 /*IsReturnAdjustment=*/true);
1539}
1540
John McCall5d865c322010-08-31 07:33:07 +00001541void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1542 RValue RV, QualType ResultType) {
1543 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1544 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1545
1546 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001547 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001548 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1549 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1550 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1551}
John McCall8ed55a52010-09-02 09:58:18 +00001552
1553/************************** Array allocation cookies **************************/
1554
John McCallb91cd662012-05-01 05:23:51 +00001555CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1556 // The array cookie is a size_t; pad that up to the element alignment.
1557 // The cookie is actually right-justified in that space.
1558 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1559 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001560}
1561
1562llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1563 llvm::Value *NewPtr,
1564 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001565 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001566 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001567 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001568
Micah Villmowea2fea22012-10-25 15:39:14 +00001569 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001570
John McCall9bca9232010-09-02 10:25:57 +00001571 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001572 QualType SizeTy = Ctx.getSizeType();
1573 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1574
1575 // The size of the cookie.
1576 CharUnits CookieSize =
1577 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001578 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001579
1580 // Compute an offset to the cookie.
1581 llvm::Value *CookiePtr = NewPtr;
1582 CharUnits CookieOffset = CookieSize - SizeSize;
1583 if (!CookieOffset.isZero())
1584 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1585 CookieOffset.getQuantity());
1586
1587 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001588 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1589 llvm::Value *NumElementsPtr =
1590 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1591 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001592 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001593 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001594 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001595 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1596 llvm::FunctionType *FTy =
1597 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1598 llvm::Constant *F =
1599 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1600 CGF.Builder.CreateCall(F, NumElementsPtr);
1601 }
John McCall8ed55a52010-09-02 09:58:18 +00001602
1603 // Finally, compute a pointer to the actual data buffer by skipping
1604 // over the cookie completely.
1605 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1606 CookieSize.getQuantity());
1607}
1608
John McCallb91cd662012-05-01 05:23:51 +00001609llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1610 llvm::Value *allocPtr,
1611 CharUnits cookieSize) {
1612 // The element size is right-justified in the cookie.
1613 llvm::Value *numElementsPtr = allocPtr;
1614 CharUnits numElementsOffset =
1615 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1616 if (!numElementsOffset.isZero())
1617 numElementsPtr =
1618 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1619 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001620
Micah Villmowea2fea22012-10-25 15:39:14 +00001621 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001622 numElementsPtr =
1623 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001624 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001625 return CGF.Builder.CreateLoad(numElementsPtr);
1626 // In asan mode emit a function call instead of a regular load and let the
1627 // run-time deal with it: if the shadow is properly poisoned return the
1628 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1629 // We can't simply ignore this load using nosanitize metadata because
1630 // the metadata may be lost.
1631 llvm::FunctionType *FTy =
1632 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1633 llvm::Constant *F =
1634 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1635 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001636}
1637
John McCallb91cd662012-05-01 05:23:51 +00001638CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001639 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001640 // struct array_cookie {
1641 // std::size_t element_size; // element_size != 0
1642 // std::size_t element_count;
1643 // };
John McCallc19c7062013-01-25 23:36:19 +00001644 // But the base ABI doesn't give anything an alignment greater than
1645 // 8, so we can dismiss this as typical ABI-author blindness to
1646 // actual language complexity and round up to the element alignment.
1647 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1648 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001649}
1650
1651llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001652 llvm::Value *newPtr,
1653 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001654 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001655 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001656 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001657
John McCallc19c7062013-01-25 23:36:19 +00001658 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1659 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001660
1661 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001662 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001663
1664 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001665 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1666 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1667 getContext().getTypeSizeInChars(elementType).getQuantity());
1668 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001669
1670 // The second element is the element count.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001671 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.SizeTy, cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00001672 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001673
1674 // Finally, compute a pointer to the actual data buffer by skipping
1675 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001676 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1677 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1678 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001679}
1680
John McCallb91cd662012-05-01 05:23:51 +00001681llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1682 llvm::Value *allocPtr,
1683 CharUnits cookieSize) {
1684 // The number of elements is at offset sizeof(size_t) relative to
1685 // the allocated pointer.
1686 llvm::Value *numElementsPtr
1687 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001688
Micah Villmowea2fea22012-10-25 15:39:14 +00001689 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001690 numElementsPtr =
1691 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1692 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001693}
1694
John McCall68ff0372010-09-08 01:44:27 +00001695/*********************** Static local initialization **************************/
1696
1697static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001698 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001699 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001700 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001701 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001702 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001703 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001704 llvm::AttributeSet::get(CGM.getLLVMContext(),
1705 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001706 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001707}
1708
1709static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001710 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001711 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001712 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001713 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001714 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001715 llvm::AttributeSet::get(CGM.getLLVMContext(),
1716 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001717 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001718}
1719
1720static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001721 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001722 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001723 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001724 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001725 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001726 llvm::AttributeSet::get(CGM.getLLVMContext(),
1727 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001728 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001729}
1730
1731namespace {
1732 struct CallGuardAbort : EHScopeStack::Cleanup {
1733 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001734 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001735
Craig Topper4f12f102014-03-12 06:41:41 +00001736 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001737 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1738 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001739 }
1740 };
1741}
1742
1743/// The ARM code here follows the Itanium code closely enough that we
1744/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001745void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1746 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001747 llvm::GlobalVariable *var,
1748 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001749 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001750
Richard Smithdbf74ba2013-04-14 23:01:42 +00001751 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001752 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001753 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1754 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001755
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001756 // If we have a global variable with internal linkage and thread-safe statics
1757 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001758 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1759
1760 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001761 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001762 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001763 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001764 // Guard variables are 64 bits in the generic ABI and size width on ARM
1765 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001766 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001767 }
John McCallb88a5662012-03-30 21:00:39 +00001768 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001769
John McCallb88a5662012-03-30 21:00:39 +00001770 // Create the guard variable if we don't already have it (as we
1771 // might if we're double-emitting this function body).
1772 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1773 if (!guard) {
1774 // Mangle the name for the guard.
1775 SmallString<256> guardName;
1776 {
1777 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001778 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001779 out.flush();
1780 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001781
John McCallb88a5662012-03-30 21:00:39 +00001782 // Create the guard variable with a zero-initializer.
1783 // Just absorb linkage and visibility from the guarded variable.
1784 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1785 false, var->getLinkage(),
1786 llvm::ConstantInt::get(guardTy, 0),
1787 guardName.str());
1788 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001789 // If the variable is thread-local, so is its guard variable.
1790 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001791
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001792 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1793 // as the associated data object
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001794 llvm::Comdat *C = var->getComdat();
1795 if (!D.isLocalVarDecl() && C) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001796 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001797 CGF.CurFn->setComdat(C);
Derek Schuff2312bd32015-05-08 16:47:21 +00001798 } else {
1799 CGM.maybeSetTrivialComdat(*guard);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001800 }
1801
John McCallb88a5662012-03-30 21:00:39 +00001802 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1803 }
John McCall87590e62012-03-30 07:09:50 +00001804
John McCall68ff0372010-09-08 01:44:27 +00001805 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001806 //
John McCall68ff0372010-09-08 01:44:27 +00001807 // Itanium C++ ABI 3.3.2:
1808 // The following is pseudo-code showing how these functions can be used:
1809 // if (obj_guard.first_byte == 0) {
1810 // if ( __cxa_guard_acquire (&obj_guard) ) {
1811 // try {
1812 // ... initialize the object ...;
1813 // } catch (...) {
1814 // __cxa_guard_abort (&obj_guard);
1815 // throw;
1816 // }
1817 // ... queue object destructor with __cxa_atexit() ...;
1818 // __cxa_guard_release (&obj_guard);
1819 // }
1820 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001821
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001822 // Load the first byte of the guard variable.
1823 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001824 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001825 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001826
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001827 // Itanium ABI:
1828 // An implementation supporting thread-safety on multiprocessor
1829 // systems must also guarantee that references to the initialized
1830 // object do not occur before the load of the initialization flag.
1831 //
1832 // In LLVM, we do this by marking the load Acquire.
1833 if (threadsafe)
1834 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001835
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001836 // For ARM, we should only check the first bit, rather than the entire byte:
1837 //
1838 // ARM C++ ABI 3.2.3.1:
1839 // To support the potential use of initialization guard variables
1840 // as semaphores that are the target of ARM SWP and LDREX/STREX
1841 // synchronizing instructions we define a static initialization
1842 // guard variable to be a 4-byte aligned, 4-byte word with the
1843 // following inline access protocol.
1844 // #define INITIALIZED 1
1845 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1846 // if (__cxa_guard_acquire(&obj_guard))
1847 // ...
1848 // }
1849 //
1850 // and similarly for ARM64:
1851 //
1852 // ARM64 C++ ABI 3.2.2:
1853 // This ABI instead only specifies the value bit 0 of the static guard
1854 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1855 // variable is not initialized and 1 when it is.
1856 llvm::Value *V =
1857 (UseARMGuardVarABI && !useInt8GuardVariable)
1858 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1859 : LI;
1860 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001861
1862 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1863 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1864
1865 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001866 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001867
1868 CGF.EmitBlock(InitCheckBlock);
1869
1870 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001871 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001872 // Call __cxa_guard_acquire.
1873 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001874 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001875
1876 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1877
1878 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1879 InitBlock, EndBlock);
1880
1881 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001882 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001883
1884 CGF.EmitBlock(InitBlock);
1885 }
1886
1887 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001888 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001889
John McCall5aa52592011-06-17 07:33:57 +00001890 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001891 // Pop the guard-abort cleanup if we pushed one.
1892 CGF.PopCleanupBlock();
1893
1894 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001895 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001896 } else {
John McCallb88a5662012-03-30 21:00:39 +00001897 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001898 }
1899
1900 CGF.EmitBlock(EndBlock);
1901}
John McCallc84ed6a2012-05-01 06:13:13 +00001902
1903/// Register a global destructor using __cxa_atexit.
1904static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1905 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001906 llvm::Constant *addr,
1907 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001908 const char *Name = "__cxa_atexit";
1909 if (TLS) {
1910 const llvm::Triple &T = CGF.getTarget().getTriple();
1911 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1912 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001913
John McCallc84ed6a2012-05-01 06:13:13 +00001914 // We're assuming that the destructor function is something we can
1915 // reasonably call with the default CC. Go ahead and cast it to the
1916 // right prototype.
1917 llvm::Type *dtorTy =
1918 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1919
1920 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1921 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1922 llvm::FunctionType *atexitTy =
1923 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1924
1925 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001926 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001927 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1928 fn->setDoesNotThrow();
1929
1930 // Create a variable that binds the atexit to this shared object.
1931 llvm::Constant *handle =
1932 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1933
1934 llvm::Value *args[] = {
1935 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1936 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1937 handle
1938 };
John McCall882987f2013-02-28 19:01:20 +00001939 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001940}
1941
1942/// Register a global destructor as best as we know how.
1943void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001944 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001945 llvm::Constant *dtor,
1946 llvm::Constant *addr) {
1947 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001948 if (CGM.getCodeGenOpts().CXAAtExit)
1949 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1950
1951 if (D.getTLSKind())
1952 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001953
1954 // In Apple kexts, we want to add a global destructor entry.
1955 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001956 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001957 // Generate a global destructor entry.
1958 return CGM.AddCXXDtorEntry(dtor, addr);
1959 }
1960
David Blaikieebe87e12013-08-27 23:57:18 +00001961 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001962}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001963
David Majnemer9b21c332014-07-11 20:28:10 +00001964static bool isThreadWrapperReplaceable(const VarDecl *VD,
1965 CodeGen::CodeGenModule &CGM) {
1966 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1967 // OS X prefers to have references to thread local variables to go through
1968 // the thread wrapper instead of directly referencing the backing variable.
1969 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1970 CGM.getTarget().getTriple().isMacOSX();
1971}
1972
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001973/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001974/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001975/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001976static llvm::GlobalValue::LinkageTypes
1977getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1978 llvm::GlobalValue::LinkageTypes VarLinkage =
1979 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1980
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001981 // For internal linkage variables, we don't need an external or weak wrapper.
1982 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1983 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001984
David Majnemer9b21c332014-07-11 20:28:10 +00001985 // If the thread wrapper is replaceable, give it appropriate linkage.
1986 if (isThreadWrapperReplaceable(VD, CGM)) {
1987 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1988 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1989 return llvm::GlobalVariable::WeakAnyLinkage;
1990 return VarLinkage;
1991 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001992 return llvm::GlobalValue::WeakODRLinkage;
1993}
1994
1995llvm::Function *
1996ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00001997 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001998 // Mangle the name for the thread_local wrapper function.
1999 SmallString<256> WrapperName;
2000 {
2001 llvm::raw_svector_ostream Out(WrapperName);
2002 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
2003 Out.flush();
2004 }
2005
Alexander Musmanf94c3182014-09-26 06:28:25 +00002006 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002007 return cast<llvm::Function>(V);
2008
Alexander Musmanf94c3182014-09-26 06:28:25 +00002009 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002010 if (VD->getType()->isReferenceType())
2011 RetTy = RetTy->getPointerElementType();
2012
2013 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002014 llvm::Function *Wrapper =
2015 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2016 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002017 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002018 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002019 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002020 return Wrapper;
2021}
2022
2023void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002024 CodeGenModule &CGM,
2025 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2026 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2027 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2028 llvm::Function *InitFunc = nullptr;
2029 if (!CXXThreadLocalInits.empty()) {
2030 // Generate a guarded initialization function.
2031 llvm::FunctionType *FTy =
2032 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2033 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002034 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002035 /*TLS=*/true);
2036 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2037 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2038 llvm::GlobalVariable::InternalLinkage,
2039 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2040 Guard->setThreadLocal(true);
2041 CodeGenFunction(CGM)
2042 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2043 }
2044 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
2045 const VarDecl *VD = CXXThreadLocals[I].first;
2046 llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002047
David Majnemer9b21c332014-07-11 20:28:10 +00002048 // Some targets require that all access to thread local variables go through
2049 // the thread wrapper. This means that we cannot attempt to create a thread
2050 // wrapper or a thread helper.
2051 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2052 continue;
2053
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002054 // Mangle the name for the thread_local initialization function.
2055 SmallString<256> InitFnName;
2056 {
2057 llvm::raw_svector_ostream Out(InitFnName);
2058 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
2059 Out.flush();
2060 }
2061
2062 // If we have a definition for the variable, emit the initialization
2063 // function as an alias to the global Init function (if any). Otherwise,
2064 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002065 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002066 bool InitIsInitFunc = false;
2067 if (VD->hasDefinition()) {
2068 InitIsInitFunc = true;
2069 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002070 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2071 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002072 } else {
2073 // Emit a weak global function referring to the initialization function.
2074 // This function will not exist if the TU defining the thread_local
2075 // variable in question does not need any dynamic initialization for
2076 // its thread_local variables.
2077 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2078 Init = llvm::Function::Create(
2079 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2080 &CGM.getModule());
2081 }
2082
2083 if (Init)
2084 Init->setVisibility(Var->getVisibility());
2085
2086 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2087 llvm::LLVMContext &Context = CGM.getModule().getContext();
2088 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2089 CGBuilderTy Builder(Entry);
2090 if (InitIsInitFunc) {
2091 if (Init)
2092 Builder.CreateCall(Init);
2093 } else {
2094 // Don't know whether we have an init function. Call it if it exists.
2095 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2096 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2097 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2098 Builder.CreateCondBr(Have, InitBB, ExitBB);
2099
2100 Builder.SetInsertPoint(InitBB);
2101 Builder.CreateCall(Init);
2102 Builder.CreateBr(ExitBB);
2103
2104 Builder.SetInsertPoint(ExitBB);
2105 }
2106
2107 // For a reference, the result of the wrapper function is a pointer to
2108 // the referenced object.
2109 llvm::Value *Val = Var;
2110 if (VD->getType()->isReferenceType()) {
2111 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2112 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2113 Val = LI;
2114 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002115 if (Val->getType() != Wrapper->getReturnType())
2116 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2117 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002118 Builder.CreateRet(Val);
2119 }
2120}
2121
Richard Smith0f383742014-03-26 22:48:22 +00002122LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2123 const VarDecl *VD,
2124 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002125 QualType T = VD->getType();
2126 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2127 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002128 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002129
2130 Val = CGF.Builder.CreateCall(Wrapper);
2131
2132 LValue LV;
2133 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002134 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002135 else
Richard Smith0f383742014-03-26 22:48:22 +00002136 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002137 // FIXME: need setObjCGCLValueClass?
2138 return LV;
2139}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002140
2141/// Return whether the given global decl needs a VTT parameter, which it does
2142/// if it's a base constructor or destructor with virtual bases.
2143bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2144 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2145
2146 // We don't have any virtual bases, just return early.
2147 if (!MD->getParent()->getNumVBases())
2148 return false;
2149
2150 // Check if we have a base constructor.
2151 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2152 return true;
2153
2154 // Check if we have a base destructor.
2155 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2156 return true;
2157
2158 return false;
2159}
David Majnemere2cb8d12014-07-07 06:20:47 +00002160
2161namespace {
2162class ItaniumRTTIBuilder {
2163 CodeGenModule &CGM; // Per-module state.
2164 llvm::LLVMContext &VMContext;
2165 const ItaniumCXXABI &CXXABI; // Per-module state.
2166
2167 /// Fields - The fields of the RTTI descriptor currently being built.
2168 SmallVector<llvm::Constant *, 16> Fields;
2169
2170 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2171 llvm::GlobalVariable *
2172 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2173
2174 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2175 /// descriptor of the given type.
2176 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2177
2178 /// BuildVTablePointer - Build the vtable pointer for the given type.
2179 void BuildVTablePointer(const Type *Ty);
2180
2181 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2182 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2183 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2184
2185 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2186 /// classes with bases that do not satisfy the abi::__si_class_type_info
2187 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2188 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2189
2190 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2191 /// for pointer types.
2192 void BuildPointerTypeInfo(QualType PointeeTy);
2193
2194 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2195 /// type_info for an object type.
2196 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2197
2198 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2199 /// struct, used for member pointer types.
2200 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2201
2202public:
2203 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2204 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2205
2206 // Pointer type info flags.
2207 enum {
2208 /// PTI_Const - Type has const qualifier.
2209 PTI_Const = 0x1,
2210
2211 /// PTI_Volatile - Type has volatile qualifier.
2212 PTI_Volatile = 0x2,
2213
2214 /// PTI_Restrict - Type has restrict qualifier.
2215 PTI_Restrict = 0x4,
2216
2217 /// PTI_Incomplete - Type is incomplete.
2218 PTI_Incomplete = 0x8,
2219
2220 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2221 /// (in pointer to member).
2222 PTI_ContainingClassIncomplete = 0x10
2223 };
2224
2225 // VMI type info flags.
2226 enum {
2227 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2228 VMI_NonDiamondRepeat = 0x1,
2229
2230 /// VMI_DiamondShaped - Class is diamond shaped.
2231 VMI_DiamondShaped = 0x2
2232 };
2233
2234 // Base class type info flags.
2235 enum {
2236 /// BCTI_Virtual - Base class is virtual.
2237 BCTI_Virtual = 0x1,
2238
2239 /// BCTI_Public - Base class is public.
2240 BCTI_Public = 0x2
2241 };
2242
2243 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2244 ///
2245 /// \param Force - true to force the creation of this RTTI value
2246 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2247};
2248}
2249
2250llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2251 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2252 SmallString<256> OutName;
2253 llvm::raw_svector_ostream Out(OutName);
2254 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2255 Out.flush();
2256 StringRef Name = OutName.str();
2257
2258 // We know that the mangled name of the type starts at index 4 of the
2259 // mangled name of the typename, so we can just index into it in order to
2260 // get the mangled name of the type.
2261 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2262 Name.substr(4));
2263
2264 llvm::GlobalVariable *GV =
2265 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2266
2267 GV->setInitializer(Init);
2268
2269 return GV;
2270}
2271
2272llvm::Constant *
2273ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2274 // Mangle the RTTI name.
2275 SmallString<256> OutName;
2276 llvm::raw_svector_ostream Out(OutName);
2277 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2278 Out.flush();
2279 StringRef Name = OutName.str();
2280
2281 // Look for an existing global.
2282 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2283
2284 if (!GV) {
2285 // Create a new global variable.
2286 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2287 /*Constant=*/true,
2288 llvm::GlobalValue::ExternalLinkage, nullptr,
2289 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002290 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2291 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2292 if (RD->hasAttr<DLLImportAttr>())
2293 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2294 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002295 }
2296
2297 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2298}
2299
2300/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2301/// info for that type is defined in the standard library.
2302static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2303 // Itanium C++ ABI 2.9.2:
2304 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2305 // the run-time support library. Specifically, the run-time support
2306 // library should contain type_info objects for the types X, X* and
2307 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2308 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2309 // long, unsigned long, long long, unsigned long long, float, double,
2310 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2311 // half-precision floating point types.
2312 switch (Ty->getKind()) {
2313 case BuiltinType::Void:
2314 case BuiltinType::NullPtr:
2315 case BuiltinType::Bool:
2316 case BuiltinType::WChar_S:
2317 case BuiltinType::WChar_U:
2318 case BuiltinType::Char_U:
2319 case BuiltinType::Char_S:
2320 case BuiltinType::UChar:
2321 case BuiltinType::SChar:
2322 case BuiltinType::Short:
2323 case BuiltinType::UShort:
2324 case BuiltinType::Int:
2325 case BuiltinType::UInt:
2326 case BuiltinType::Long:
2327 case BuiltinType::ULong:
2328 case BuiltinType::LongLong:
2329 case BuiltinType::ULongLong:
2330 case BuiltinType::Half:
2331 case BuiltinType::Float:
2332 case BuiltinType::Double:
2333 case BuiltinType::LongDouble:
2334 case BuiltinType::Char16:
2335 case BuiltinType::Char32:
2336 case BuiltinType::Int128:
2337 case BuiltinType::UInt128:
2338 case BuiltinType::OCLImage1d:
2339 case BuiltinType::OCLImage1dArray:
2340 case BuiltinType::OCLImage1dBuffer:
2341 case BuiltinType::OCLImage2d:
2342 case BuiltinType::OCLImage2dArray:
2343 case BuiltinType::OCLImage3d:
2344 case BuiltinType::OCLSampler:
2345 case BuiltinType::OCLEvent:
2346 return true;
2347
2348 case BuiltinType::Dependent:
2349#define BUILTIN_TYPE(Id, SingletonId)
2350#define PLACEHOLDER_TYPE(Id, SingletonId) \
2351 case BuiltinType::Id:
2352#include "clang/AST/BuiltinTypes.def"
2353 llvm_unreachable("asking for RRTI for a placeholder type!");
2354
2355 case BuiltinType::ObjCId:
2356 case BuiltinType::ObjCClass:
2357 case BuiltinType::ObjCSel:
2358 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2359 }
2360
2361 llvm_unreachable("Invalid BuiltinType Kind!");
2362}
2363
2364static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2365 QualType PointeeTy = PointerTy->getPointeeType();
2366 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2367 if (!BuiltinTy)
2368 return false;
2369
2370 // Check the qualifiers.
2371 Qualifiers Quals = PointeeTy.getQualifiers();
2372 Quals.removeConst();
2373
2374 if (!Quals.empty())
2375 return false;
2376
2377 return TypeInfoIsInStandardLibrary(BuiltinTy);
2378}
2379
2380/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2381/// information for the given type exists in the standard library.
2382static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2383 // Type info for builtin types is defined in the standard library.
2384 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2385 return TypeInfoIsInStandardLibrary(BuiltinTy);
2386
2387 // Type info for some pointer types to builtin types is defined in the
2388 // standard library.
2389 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2390 return TypeInfoIsInStandardLibrary(PointerTy);
2391
2392 return false;
2393}
2394
2395/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2396/// the given type exists somewhere else, and that we should not emit the type
2397/// information in this translation unit. Assumes that it is not a
2398/// standard-library type.
2399static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2400 QualType Ty) {
2401 ASTContext &Context = CGM.getContext();
2402
2403 // If RTTI is disabled, assume it might be disabled in the
2404 // translation unit that defines any potential key function, too.
2405 if (!Context.getLangOpts().RTTI) return false;
2406
2407 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2408 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2409 if (!RD->hasDefinition())
2410 return false;
2411
2412 if (!RD->isDynamicClass())
2413 return false;
2414
2415 // FIXME: this may need to be reconsidered if the key function
2416 // changes.
David Majnemer1fb1a042014-11-07 07:26:38 +00002417 if (CGM.getVTables().isVTableExternal(RD))
2418 return true;
2419
2420 if (RD->hasAttr<DLLImportAttr>())
2421 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002422 }
2423
2424 return false;
2425}
2426
2427/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2428static bool IsIncompleteClassType(const RecordType *RecordTy) {
2429 return !RecordTy->getDecl()->isCompleteDefinition();
2430}
2431
2432/// ContainsIncompleteClassType - Returns whether the given type contains an
2433/// incomplete class type. This is true if
2434///
2435/// * The given type is an incomplete class type.
2436/// * The given type is a pointer type whose pointee type contains an
2437/// incomplete class type.
2438/// * The given type is a member pointer type whose class is an incomplete
2439/// class type.
2440/// * The given type is a member pointer type whoise pointee type contains an
2441/// incomplete class type.
2442/// is an indirect or direct pointer to an incomplete class type.
2443static bool ContainsIncompleteClassType(QualType Ty) {
2444 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2445 if (IsIncompleteClassType(RecordTy))
2446 return true;
2447 }
2448
2449 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2450 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2451
2452 if (const MemberPointerType *MemberPointerTy =
2453 dyn_cast<MemberPointerType>(Ty)) {
2454 // Check if the class type is incomplete.
2455 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2456 if (IsIncompleteClassType(ClassType))
2457 return true;
2458
2459 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2460 }
2461
2462 return false;
2463}
2464
2465// CanUseSingleInheritance - Return whether the given record decl has a "single,
2466// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2467// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2468static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2469 // Check the number of bases.
2470 if (RD->getNumBases() != 1)
2471 return false;
2472
2473 // Get the base.
2474 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2475
2476 // Check that the base is not virtual.
2477 if (Base->isVirtual())
2478 return false;
2479
2480 // Check that the base is public.
2481 if (Base->getAccessSpecifier() != AS_public)
2482 return false;
2483
2484 // Check that the class is dynamic iff the base is.
2485 const CXXRecordDecl *BaseDecl =
2486 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2487 if (!BaseDecl->isEmpty() &&
2488 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2489 return false;
2490
2491 return true;
2492}
2493
2494void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2495 // abi::__class_type_info.
2496 static const char * const ClassTypeInfo =
2497 "_ZTVN10__cxxabiv117__class_type_infoE";
2498 // abi::__si_class_type_info.
2499 static const char * const SIClassTypeInfo =
2500 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2501 // abi::__vmi_class_type_info.
2502 static const char * const VMIClassTypeInfo =
2503 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2504
2505 const char *VTableName = nullptr;
2506
2507 switch (Ty->getTypeClass()) {
2508#define TYPE(Class, Base)
2509#define ABSTRACT_TYPE(Class, Base)
2510#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2511#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2512#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2513#include "clang/AST/TypeNodes.def"
2514 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2515
2516 case Type::LValueReference:
2517 case Type::RValueReference:
2518 llvm_unreachable("References shouldn't get here");
2519
2520 case Type::Auto:
2521 llvm_unreachable("Undeduced auto type shouldn't get here");
2522
2523 case Type::Builtin:
2524 // GCC treats vector and complex types as fundamental types.
2525 case Type::Vector:
2526 case Type::ExtVector:
2527 case Type::Complex:
2528 case Type::Atomic:
2529 // FIXME: GCC treats block pointers as fundamental types?!
2530 case Type::BlockPointer:
2531 // abi::__fundamental_type_info.
2532 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2533 break;
2534
2535 case Type::ConstantArray:
2536 case Type::IncompleteArray:
2537 case Type::VariableArray:
2538 // abi::__array_type_info.
2539 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2540 break;
2541
2542 case Type::FunctionNoProto:
2543 case Type::FunctionProto:
2544 // abi::__function_type_info.
2545 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2546 break;
2547
2548 case Type::Enum:
2549 // abi::__enum_type_info.
2550 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2551 break;
2552
2553 case Type::Record: {
2554 const CXXRecordDecl *RD =
2555 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2556
2557 if (!RD->hasDefinition() || !RD->getNumBases()) {
2558 VTableName = ClassTypeInfo;
2559 } else if (CanUseSingleInheritance(RD)) {
2560 VTableName = SIClassTypeInfo;
2561 } else {
2562 VTableName = VMIClassTypeInfo;
2563 }
2564
2565 break;
2566 }
2567
2568 case Type::ObjCObject:
2569 // Ignore protocol qualifiers.
2570 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2571
2572 // Handle id and Class.
2573 if (isa<BuiltinType>(Ty)) {
2574 VTableName = ClassTypeInfo;
2575 break;
2576 }
2577
2578 assert(isa<ObjCInterfaceType>(Ty));
2579 // Fall through.
2580
2581 case Type::ObjCInterface:
2582 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2583 VTableName = SIClassTypeInfo;
2584 } else {
2585 VTableName = ClassTypeInfo;
2586 }
2587 break;
2588
2589 case Type::ObjCObjectPointer:
2590 case Type::Pointer:
2591 // abi::__pointer_type_info.
2592 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2593 break;
2594
2595 case Type::MemberPointer:
2596 // abi::__pointer_to_member_type_info.
2597 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2598 break;
2599 }
2600
2601 llvm::Constant *VTable =
2602 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2603
2604 llvm::Type *PtrDiffTy =
2605 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2606
2607 // The vtable address point is 2.
2608 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002609 VTable =
2610 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002611 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2612
2613 Fields.push_back(VTable);
2614}
2615
2616/// \brief Return the linkage that the type info and type info name constants
2617/// should have for the given type.
2618static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2619 QualType Ty) {
2620 // Itanium C++ ABI 2.9.5p7:
2621 // In addition, it and all of the intermediate abi::__pointer_type_info
2622 // structs in the chain down to the abi::__class_type_info for the
2623 // incomplete class type must be prevented from resolving to the
2624 // corresponding type_info structs for the complete class type, possibly
2625 // by making them local static objects. Finally, a dummy class RTTI is
2626 // generated for the incomplete type that will not resolve to the final
2627 // complete class RTTI (because the latter need not exist), possibly by
2628 // making it a local static object.
2629 if (ContainsIncompleteClassType(Ty))
2630 return llvm::GlobalValue::InternalLinkage;
2631
2632 switch (Ty->getLinkage()) {
2633 case NoLinkage:
2634 case InternalLinkage:
2635 case UniqueExternalLinkage:
2636 return llvm::GlobalValue::InternalLinkage;
2637
2638 case VisibleNoLinkage:
2639 case ExternalLinkage:
2640 if (!CGM.getLangOpts().RTTI) {
2641 // RTTI is not enabled, which means that this type info struct is going
2642 // to be used for exception handling. Give it linkonce_odr linkage.
2643 return llvm::GlobalValue::LinkOnceODRLinkage;
2644 }
2645
2646 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2647 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2648 if (RD->hasAttr<WeakAttr>())
2649 return llvm::GlobalValue::WeakODRLinkage;
2650 if (RD->isDynamicClass())
2651 return CGM.getVTableLinkage(RD);
2652 }
2653
2654 return llvm::GlobalValue::LinkOnceODRLinkage;
2655 }
2656
2657 llvm_unreachable("Invalid linkage!");
2658}
2659
2660llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2661 // We want to operate on the canonical type.
2662 Ty = CGM.getContext().getCanonicalType(Ty);
2663
2664 // Check if we've already emitted an RTTI descriptor for this type.
2665 SmallString<256> OutName;
2666 llvm::raw_svector_ostream Out(OutName);
2667 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2668 Out.flush();
2669 StringRef Name = OutName.str();
2670
2671 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2672 if (OldGV && !OldGV->isDeclaration()) {
2673 assert(!OldGV->hasAvailableExternallyLinkage() &&
2674 "available_externally typeinfos not yet implemented");
2675
2676 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2677 }
2678
2679 // Check if there is already an external RTTI descriptor for this type.
2680 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2681 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2682 return GetAddrOfExternalRTTIDescriptor(Ty);
2683
2684 // Emit the standard library with external linkage.
2685 llvm::GlobalVariable::LinkageTypes Linkage;
2686 if (IsStdLib)
2687 Linkage = llvm::GlobalValue::ExternalLinkage;
2688 else
2689 Linkage = getTypeInfoLinkage(CGM, Ty);
2690
2691 // Add the vtable pointer.
2692 BuildVTablePointer(cast<Type>(Ty));
2693
2694 // And the name.
2695 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2696 llvm::Constant *TypeNameField;
2697
2698 // If we're supposed to demote the visibility, be sure to set a flag
2699 // to use a string comparison for type_info comparisons.
2700 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2701 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2702 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2703 // The flag is the sign bit, which on ARM64 is defined to be clear
2704 // for global pointers. This is very ARM64-specific.
2705 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2706 llvm::Constant *flag =
2707 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2708 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2709 TypeNameField =
2710 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2711 } else {
2712 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2713 }
2714 Fields.push_back(TypeNameField);
2715
2716 switch (Ty->getTypeClass()) {
2717#define TYPE(Class, Base)
2718#define ABSTRACT_TYPE(Class, Base)
2719#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2720#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2721#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2722#include "clang/AST/TypeNodes.def"
2723 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2724
2725 // GCC treats vector types as fundamental types.
2726 case Type::Builtin:
2727 case Type::Vector:
2728 case Type::ExtVector:
2729 case Type::Complex:
2730 case Type::BlockPointer:
2731 // Itanium C++ ABI 2.9.5p4:
2732 // abi::__fundamental_type_info adds no data members to std::type_info.
2733 break;
2734
2735 case Type::LValueReference:
2736 case Type::RValueReference:
2737 llvm_unreachable("References shouldn't get here");
2738
2739 case Type::Auto:
2740 llvm_unreachable("Undeduced auto type shouldn't get here");
2741
2742 case Type::ConstantArray:
2743 case Type::IncompleteArray:
2744 case Type::VariableArray:
2745 // Itanium C++ ABI 2.9.5p5:
2746 // abi::__array_type_info adds no data members to std::type_info.
2747 break;
2748
2749 case Type::FunctionNoProto:
2750 case Type::FunctionProto:
2751 // Itanium C++ ABI 2.9.5p5:
2752 // abi::__function_type_info adds no data members to std::type_info.
2753 break;
2754
2755 case Type::Enum:
2756 // Itanium C++ ABI 2.9.5p5:
2757 // abi::__enum_type_info adds no data members to std::type_info.
2758 break;
2759
2760 case Type::Record: {
2761 const CXXRecordDecl *RD =
2762 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2763 if (!RD->hasDefinition() || !RD->getNumBases()) {
2764 // We don't need to emit any fields.
2765 break;
2766 }
2767
2768 if (CanUseSingleInheritance(RD))
2769 BuildSIClassTypeInfo(RD);
2770 else
2771 BuildVMIClassTypeInfo(RD);
2772
2773 break;
2774 }
2775
2776 case Type::ObjCObject:
2777 case Type::ObjCInterface:
2778 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2779 break;
2780
2781 case Type::ObjCObjectPointer:
2782 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2783 break;
2784
2785 case Type::Pointer:
2786 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2787 break;
2788
2789 case Type::MemberPointer:
2790 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2791 break;
2792
2793 case Type::Atomic:
2794 // No fields, at least for the moment.
2795 break;
2796 }
2797
2798 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2799
Rafael Espindolacb92c192015-01-15 23:18:01 +00002800 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002801 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002802 new llvm::GlobalVariable(M, Init->getType(),
2803 /*Constant=*/true, Linkage, Init, Name);
2804
Derek Schuff2312bd32015-05-08 16:47:21 +00002805 CGM.maybeSetTrivialComdat(*GV);
David Majnemere2cb8d12014-07-07 06:20:47 +00002806
2807 // If there's already an old global variable, replace it with the new one.
2808 if (OldGV) {
2809 GV->takeName(OldGV);
2810 llvm::Constant *NewPtr =
2811 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2812 OldGV->replaceAllUsesWith(NewPtr);
2813 OldGV->eraseFromParent();
2814 }
2815
2816 // The Itanium ABI specifies that type_info objects must be globally
2817 // unique, with one exception: if the type is an incomplete class
2818 // type or a (possibly indirect) pointer to one. That exception
2819 // affects the general case of comparing type_info objects produced
2820 // by the typeid operator, which is why the comparison operators on
2821 // std::type_info generally use the type_info name pointers instead
2822 // of the object addresses. However, the language's built-in uses
2823 // of RTTI generally require class types to be complete, even when
2824 // manipulating pointers to those class types. This allows the
2825 // implementation of dynamic_cast to rely on address equality tests,
2826 // which is much faster.
2827
2828 // All of this is to say that it's important that both the type_info
2829 // object and the type_info name be uniqued when weakly emitted.
2830
2831 // Give the type_info object and name the formal visibility of the
2832 // type itself.
2833 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2834 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2835 // If the linkage is local, only default visibility makes sense.
2836 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2837 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2838 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2839 else
2840 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2841 TypeName->setVisibility(llvmVisibility);
2842 GV->setVisibility(llvmVisibility);
2843
2844 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2845}
2846
2847/// ComputeQualifierFlags - Compute the pointer type info flags from the
2848/// given qualifier.
2849static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2850 unsigned Flags = 0;
2851
2852 if (Quals.hasConst())
2853 Flags |= ItaniumRTTIBuilder::PTI_Const;
2854 if (Quals.hasVolatile())
2855 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2856 if (Quals.hasRestrict())
2857 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2858
2859 return Flags;
2860}
2861
2862/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2863/// for the given Objective-C object type.
2864void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2865 // Drop qualifiers.
2866 const Type *T = OT->getBaseType().getTypePtr();
2867 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2868
2869 // The builtin types are abi::__class_type_infos and don't require
2870 // extra fields.
2871 if (isa<BuiltinType>(T)) return;
2872
2873 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2874 ObjCInterfaceDecl *Super = Class->getSuperClass();
2875
2876 // Root classes are also __class_type_info.
2877 if (!Super) return;
2878
2879 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2880
2881 // Everything else is single inheritance.
2882 llvm::Constant *BaseTypeInfo =
2883 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2884 Fields.push_back(BaseTypeInfo);
2885}
2886
2887/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2888/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2889void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2890 // Itanium C++ ABI 2.9.5p6b:
2891 // It adds to abi::__class_type_info a single member pointing to the
2892 // type_info structure for the base type,
2893 llvm::Constant *BaseTypeInfo =
2894 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2895 Fields.push_back(BaseTypeInfo);
2896}
2897
2898namespace {
2899 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2900 /// a class hierarchy.
2901 struct SeenBases {
2902 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2903 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2904 };
2905}
2906
2907/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2908/// abi::__vmi_class_type_info.
2909///
2910static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2911 SeenBases &Bases) {
2912
2913 unsigned Flags = 0;
2914
2915 const CXXRecordDecl *BaseDecl =
2916 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2917
2918 if (Base->isVirtual()) {
2919 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002920 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002921 // If this virtual base has been seen before, then the class is diamond
2922 // shaped.
2923 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2924 } else {
2925 if (Bases.NonVirtualBases.count(BaseDecl))
2926 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2927 }
2928 } else {
2929 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002930 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002931 // If this non-virtual base has been seen before, then the class has non-
2932 // diamond shaped repeated inheritance.
2933 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2934 } else {
2935 if (Bases.VirtualBases.count(BaseDecl))
2936 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2937 }
2938 }
2939
2940 // Walk all bases.
2941 for (const auto &I : BaseDecl->bases())
2942 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2943
2944 return Flags;
2945}
2946
2947static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2948 unsigned Flags = 0;
2949 SeenBases Bases;
2950
2951 // Walk all bases.
2952 for (const auto &I : RD->bases())
2953 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2954
2955 return Flags;
2956}
2957
2958/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2959/// classes with bases that do not satisfy the abi::__si_class_type_info
2960/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2961void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2962 llvm::Type *UnsignedIntLTy =
2963 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2964
2965 // Itanium C++ ABI 2.9.5p6c:
2966 // __flags is a word with flags describing details about the class
2967 // structure, which may be referenced by using the __flags_masks
2968 // enumeration. These flags refer to both direct and indirect bases.
2969 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2970 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2971
2972 // Itanium C++ ABI 2.9.5p6c:
2973 // __base_count is a word with the number of direct proper base class
2974 // descriptions that follow.
2975 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2976
2977 if (!RD->getNumBases())
2978 return;
2979
2980 llvm::Type *LongLTy =
2981 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2982
2983 // Now add the base class descriptions.
2984
2985 // Itanium C++ ABI 2.9.5p6c:
2986 // __base_info[] is an array of base class descriptions -- one for every
2987 // direct proper base. Each description is of the type:
2988 //
2989 // struct abi::__base_class_type_info {
2990 // public:
2991 // const __class_type_info *__base_type;
2992 // long __offset_flags;
2993 //
2994 // enum __offset_flags_masks {
2995 // __virtual_mask = 0x1,
2996 // __public_mask = 0x2,
2997 // __offset_shift = 8
2998 // };
2999 // };
3000 for (const auto &Base : RD->bases()) {
3001 // The __base_type member points to the RTTI for the base type.
3002 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3003
3004 const CXXRecordDecl *BaseDecl =
3005 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3006
3007 int64_t OffsetFlags = 0;
3008
3009 // All but the lower 8 bits of __offset_flags are a signed offset.
3010 // For a non-virtual base, this is the offset in the object of the base
3011 // subobject. For a virtual base, this is the offset in the virtual table of
3012 // the virtual base offset for the virtual base referenced (negative).
3013 CharUnits Offset;
3014 if (Base.isVirtual())
3015 Offset =
3016 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3017 else {
3018 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3019 Offset = Layout.getBaseClassOffset(BaseDecl);
3020 };
3021
3022 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3023
3024 // The low-order byte of __offset_flags contains flags, as given by the
3025 // masks from the enumeration __offset_flags_masks.
3026 if (Base.isVirtual())
3027 OffsetFlags |= BCTI_Virtual;
3028 if (Base.getAccessSpecifier() == AS_public)
3029 OffsetFlags |= BCTI_Public;
3030
3031 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3032 }
3033}
3034
3035/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3036/// used for pointer types.
3037void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3038 Qualifiers Quals;
3039 QualType UnqualifiedPointeeTy =
3040 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3041
3042 // Itanium C++ ABI 2.9.5p7:
3043 // __flags is a flag word describing the cv-qualification and other
3044 // attributes of the type pointed to
3045 unsigned Flags = ComputeQualifierFlags(Quals);
3046
3047 // Itanium C++ ABI 2.9.5p7:
3048 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3049 // incomplete class type, the incomplete target type flag is set.
3050 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3051 Flags |= PTI_Incomplete;
3052
3053 llvm::Type *UnsignedIntLTy =
3054 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3055 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3056
3057 // Itanium C++ ABI 2.9.5p7:
3058 // __pointee is a pointer to the std::type_info derivation for the
3059 // unqualified type being pointed to.
3060 llvm::Constant *PointeeTypeInfo =
3061 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3062 Fields.push_back(PointeeTypeInfo);
3063}
3064
3065/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3066/// struct, used for member pointer types.
3067void
3068ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3069 QualType PointeeTy = Ty->getPointeeType();
3070
3071 Qualifiers Quals;
3072 QualType UnqualifiedPointeeTy =
3073 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3074
3075 // Itanium C++ ABI 2.9.5p7:
3076 // __flags is a flag word describing the cv-qualification and other
3077 // attributes of the type pointed to.
3078 unsigned Flags = ComputeQualifierFlags(Quals);
3079
3080 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3081
3082 // Itanium C++ ABI 2.9.5p7:
3083 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3084 // incomplete class type, the incomplete target type flag is set.
3085 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3086 Flags |= PTI_Incomplete;
3087
3088 if (IsIncompleteClassType(ClassType))
3089 Flags |= PTI_ContainingClassIncomplete;
3090
3091 llvm::Type *UnsignedIntLTy =
3092 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3093 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3094
3095 // Itanium C++ ABI 2.9.5p7:
3096 // __pointee is a pointer to the std::type_info derivation for the
3097 // unqualified type being pointed to.
3098 llvm::Constant *PointeeTypeInfo =
3099 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3100 Fields.push_back(PointeeTypeInfo);
3101
3102 // Itanium C++ ABI 2.9.5p9:
3103 // __context is a pointer to an abi::__class_type_info corresponding to the
3104 // class type containing the member pointed to
3105 // (e.g., the "A" in "int A::*").
3106 Fields.push_back(
3107 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3108}
3109
David Majnemer443250f2015-03-17 20:35:00 +00003110llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003111 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3112}
3113
3114void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3115 QualType PointerType = getContext().getPointerType(Type);
3116 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3117 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3118 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3119 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3120}
3121
3122void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3123 QualType FundamentalTypes[] = {
3124 getContext().VoidTy, getContext().NullPtrTy,
3125 getContext().BoolTy, getContext().WCharTy,
3126 getContext().CharTy, getContext().UnsignedCharTy,
3127 getContext().SignedCharTy, getContext().ShortTy,
3128 getContext().UnsignedShortTy, getContext().IntTy,
3129 getContext().UnsignedIntTy, getContext().LongTy,
3130 getContext().UnsignedLongTy, getContext().LongLongTy,
3131 getContext().UnsignedLongLongTy, getContext().HalfTy,
3132 getContext().FloatTy, getContext().DoubleTy,
3133 getContext().LongDoubleTy, getContext().Char16Ty,
3134 getContext().Char32Ty,
3135 };
3136 for (const QualType &FundamentalType : FundamentalTypes)
3137 EmitFundamentalRTTIDescriptor(FundamentalType);
3138}
3139
3140/// What sort of uniqueness rules should we use for the RTTI for the
3141/// given type?
3142ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3143 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3144 if (shouldRTTIBeUnique())
3145 return RUK_Unique;
3146
3147 // It's only necessary for linkonce_odr or weak_odr linkage.
3148 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3149 Linkage != llvm::GlobalValue::WeakODRLinkage)
3150 return RUK_Unique;
3151
3152 // It's only necessary with default visibility.
3153 if (CanTy->getVisibility() != DefaultVisibility)
3154 return RUK_Unique;
3155
3156 // If we're not required to publish this symbol, hide it.
3157 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3158 return RUK_NonUniqueHidden;
3159
3160 // If we're required to publish this symbol, as we might be under an
3161 // explicit instantiation, leave it with default visibility but
3162 // enable string-comparisons.
3163 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3164 return RUK_NonUniqueVisible;
3165}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003166
Rafael Espindola1e4df922014-09-16 15:18:21 +00003167// Find out how to codegen the complete destructor and constructor
3168namespace {
3169enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3170}
3171static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3172 const CXXMethodDecl *MD) {
3173 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3174 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003175
Rafael Espindola1e4df922014-09-16 15:18:21 +00003176 // The complete and base structors are not equivalent if there are any virtual
3177 // bases, so emit separate functions.
3178 if (MD->getParent()->getNumVBases())
3179 return StructorCodegen::Emit;
3180
3181 GlobalDecl AliasDecl;
3182 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3183 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3184 } else {
3185 const auto *CD = cast<CXXConstructorDecl>(MD);
3186 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3187 }
3188 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3189
3190 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3191 return StructorCodegen::RAUW;
3192
3193 // FIXME: Should we allow available_externally aliases?
3194 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3195 return StructorCodegen::RAUW;
3196
Rafael Espindola0806f982014-09-16 20:19:43 +00003197 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3198 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3199 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3200 return StructorCodegen::COMDAT;
3201 return StructorCodegen::Emit;
3202 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003203
3204 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003205}
3206
Rafael Espindola1e4df922014-09-16 15:18:21 +00003207static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3208 GlobalDecl AliasDecl,
3209 GlobalDecl TargetDecl) {
3210 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3211
3212 StringRef MangledName = CGM.getMangledName(AliasDecl);
3213 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3214 if (Entry && !Entry->isDeclaration())
3215 return;
3216
3217 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3218 llvm::PointerType *AliasType = Aliasee->getType();
3219
3220 // Create the alias with no name.
David Blaikie881b2342015-04-29 21:22:47 +00003221 auto *Alias = llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee,
3222 &CGM.getModule());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003223
3224 // Switch any previous uses to the alias.
3225 if (Entry) {
3226 assert(Entry->getType() == AliasType &&
3227 "declaration exists with different type");
3228 Alias->takeName(Entry);
3229 Entry->replaceAllUsesWith(Alias);
3230 Entry->eraseFromParent();
3231 } else {
3232 Alias->setName(MangledName);
3233 }
3234
3235 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003236 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003237}
3238
3239void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3240 StructorType Type) {
3241 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3242 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3243
3244 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3245
3246 if (Type == StructorType::Complete) {
3247 GlobalDecl CompleteDecl;
3248 GlobalDecl BaseDecl;
3249 if (CD) {
3250 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3251 BaseDecl = GlobalDecl(CD, Ctor_Base);
3252 } else {
3253 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3254 BaseDecl = GlobalDecl(DD, Dtor_Base);
3255 }
3256
3257 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3258 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3259 return;
3260 }
3261
3262 if (CGType == StructorCodegen::RAUW) {
3263 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3264 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3265 CGM.addReplacement(MangledName, Aliasee);
3266 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003267 }
3268 }
3269
3270 // The base destructor is equivalent to the base destructor of its
3271 // base class if there is exactly one non-virtual base class with a
3272 // non-trivial destructor, there are no fields with a non-trivial
3273 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003274 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3275 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003276 return;
3277
Rafael Espindola1e4df922014-09-16 15:18:21 +00003278 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003279
Rafael Espindola1e4df922014-09-16 15:18:21 +00003280 if (CGType == StructorCodegen::COMDAT) {
3281 SmallString<256> Buffer;
3282 llvm::raw_svector_ostream Out(Buffer);
3283 if (DD)
3284 getMangleContext().mangleCXXDtorComdat(DD, Out);
3285 else
3286 getMangleContext().mangleCXXCtorComdat(CD, Out);
3287 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3288 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003289 } else {
3290 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003291 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003292}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003293
3294static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3295 // void *__cxa_begin_catch(void*);
3296 llvm::FunctionType *FTy = llvm::FunctionType::get(
3297 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3298
3299 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3300}
3301
3302static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3303 // void __cxa_end_catch();
3304 llvm::FunctionType *FTy =
3305 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3306
3307 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3308}
3309
3310static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3311 // void *__cxa_get_exception_ptr(void*);
3312 llvm::FunctionType *FTy = llvm::FunctionType::get(
3313 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3314
3315 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3316}
3317
3318namespace {
3319 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3320 /// exception type lets us state definitively that the thrown exception
3321 /// type does not have a destructor. In particular:
3322 /// - Catch-alls tell us nothing, so we have to conservatively
3323 /// assume that the thrown exception might have a destructor.
3324 /// - Catches by reference behave according to their base types.
3325 /// - Catches of non-record types will only trigger for exceptions
3326 /// of non-record types, which never have destructors.
3327 /// - Catches of record types can trigger for arbitrary subclasses
3328 /// of the caught type, so we have to assume the actual thrown
3329 /// exception type might have a throwing destructor, even if the
3330 /// caught type's destructor is trivial or nothrow.
3331 struct CallEndCatch : EHScopeStack::Cleanup {
3332 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3333 bool MightThrow;
3334
3335 void Emit(CodeGenFunction &CGF, Flags flags) override {
3336 if (!MightThrow) {
3337 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3338 return;
3339 }
3340
3341 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3342 }
3343 };
3344}
3345
3346/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3347/// __cxa_end_catch.
3348///
3349/// \param EndMightThrow - true if __cxa_end_catch might throw
3350static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3351 llvm::Value *Exn,
3352 bool EndMightThrow) {
3353 llvm::CallInst *call =
3354 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3355
3356 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3357
3358 return call;
3359}
3360
3361/// A "special initializer" callback for initializing a catch
3362/// parameter during catch initialization.
3363static void InitCatchParam(CodeGenFunction &CGF,
3364 const VarDecl &CatchParam,
3365 llvm::Value *ParamAddr,
3366 SourceLocation Loc) {
3367 // Load the exception from where the landing pad saved it.
3368 llvm::Value *Exn = CGF.getExceptionFromSlot();
3369
3370 CanQualType CatchType =
3371 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3372 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3373
3374 // If we're catching by reference, we can just cast the object
3375 // pointer to the appropriate pointer.
3376 if (isa<ReferenceType>(CatchType)) {
3377 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3378 bool EndCatchMightThrow = CaughtType->isRecordType();
3379
3380 // __cxa_begin_catch returns the adjusted object pointer.
3381 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3382
3383 // We have no way to tell the personality function that we're
3384 // catching by reference, so if we're catching a pointer,
3385 // __cxa_begin_catch will actually return that pointer by value.
3386 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3387 QualType PointeeType = PT->getPointeeType();
3388
3389 // When catching by reference, generally we should just ignore
3390 // this by-value pointer and use the exception object instead.
3391 if (!PointeeType->isRecordType()) {
3392
3393 // Exn points to the struct _Unwind_Exception header, which
3394 // we have to skip past in order to reach the exception data.
3395 unsigned HeaderSize =
3396 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3397 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3398
3399 // However, if we're catching a pointer-to-record type that won't
3400 // work, because the personality function might have adjusted
3401 // the pointer. There's actually no way for us to fully satisfy
3402 // the language/ABI contract here: we can't use Exn because it
3403 // might have the wrong adjustment, but we can't use the by-value
3404 // pointer because it's off by a level of abstraction.
3405 //
3406 // The current solution is to dump the adjusted pointer into an
3407 // alloca, which breaks language semantics (because changing the
3408 // pointer doesn't change the exception) but at least works.
3409 // The better solution would be to filter out non-exact matches
3410 // and rethrow them, but this is tricky because the rethrow
3411 // really needs to be catchable by other sites at this landing
3412 // pad. The best solution is to fix the personality function.
3413 } else {
3414 // Pull the pointer for the reference type off.
3415 llvm::Type *PtrTy =
3416 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3417
3418 // Create the temporary and write the adjusted pointer into it.
3419 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3420 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3421 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3422
3423 // Bind the reference to the temporary.
3424 AdjustedExn = ExnPtrTmp;
3425 }
3426 }
3427
3428 llvm::Value *ExnCast =
3429 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3430 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3431 return;
3432 }
3433
3434 // Scalars and complexes.
3435 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3436 if (TEK != TEK_Aggregate) {
3437 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3438
3439 // If the catch type is a pointer type, __cxa_begin_catch returns
3440 // the pointer by value.
3441 if (CatchType->hasPointerRepresentation()) {
3442 llvm::Value *CastExn =
3443 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3444
3445 switch (CatchType.getQualifiers().getObjCLifetime()) {
3446 case Qualifiers::OCL_Strong:
3447 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3448 // fallthrough
3449
3450 case Qualifiers::OCL_None:
3451 case Qualifiers::OCL_ExplicitNone:
3452 case Qualifiers::OCL_Autoreleasing:
3453 CGF.Builder.CreateStore(CastExn, ParamAddr);
3454 return;
3455
3456 case Qualifiers::OCL_Weak:
3457 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3458 return;
3459 }
3460 llvm_unreachable("bad ownership qualifier!");
3461 }
3462
3463 // Otherwise, it returns a pointer into the exception object.
3464
3465 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3466 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3467
3468 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3469 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3470 CGF.getContext().getDeclAlign(&CatchParam));
3471 switch (TEK) {
3472 case TEK_Complex:
3473 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3474 /*init*/ true);
3475 return;
3476 case TEK_Scalar: {
3477 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3478 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3479 return;
3480 }
3481 case TEK_Aggregate:
3482 llvm_unreachable("evaluation kind filtered out!");
3483 }
3484 llvm_unreachable("bad evaluation kind");
3485 }
3486
3487 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3488
3489 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3490
3491 // Check for a copy expression. If we don't have a copy expression,
3492 // that means a trivial copy is okay.
3493 const Expr *copyExpr = CatchParam.getInit();
3494 if (!copyExpr) {
3495 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3496 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3497 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3498 return;
3499 }
3500
3501 // We have to call __cxa_get_exception_ptr to get the adjusted
3502 // pointer before copying.
3503 llvm::CallInst *rawAdjustedExn =
3504 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3505
3506 // Cast that to the appropriate type.
3507 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3508
3509 // The copy expression is defined in terms of an OpaqueValueExpr.
3510 // Find it and map it to the adjusted expression.
3511 CodeGenFunction::OpaqueValueMapping
3512 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3513 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3514
3515 // Call the copy ctor in a terminate scope.
3516 CGF.EHStack.pushTerminate();
3517
3518 // Perform the copy construction.
3519 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3520 CGF.EmitAggExpr(copyExpr,
3521 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3522 AggValueSlot::IsNotDestructed,
3523 AggValueSlot::DoesNotNeedGCBarriers,
3524 AggValueSlot::IsNotAliased));
3525
3526 // Leave the terminate scope.
3527 CGF.EHStack.popTerminate();
3528
3529 // Undo the opaque value mapping.
3530 opaque.pop();
3531
3532 // Finally we can call __cxa_begin_catch.
3533 CallBeginCatch(CGF, Exn, true);
3534}
3535
3536/// Begins a catch statement by initializing the catch variable and
3537/// calling __cxa_begin_catch.
3538void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3539 const CXXCatchStmt *S) {
3540 // We have to be very careful with the ordering of cleanups here:
3541 // C++ [except.throw]p4:
3542 // The destruction [of the exception temporary] occurs
3543 // immediately after the destruction of the object declared in
3544 // the exception-declaration in the handler.
3545 //
3546 // So the precise ordering is:
3547 // 1. Construct catch variable.
3548 // 2. __cxa_begin_catch
3549 // 3. Enter __cxa_end_catch cleanup
3550 // 4. Enter dtor cleanup
3551 //
3552 // We do this by using a slightly abnormal initialization process.
3553 // Delegation sequence:
3554 // - ExitCXXTryStmt opens a RunCleanupsScope
3555 // - EmitAutoVarAlloca creates the variable and debug info
3556 // - InitCatchParam initializes the variable from the exception
3557 // - CallBeginCatch calls __cxa_begin_catch
3558 // - CallBeginCatch enters the __cxa_end_catch cleanup
3559 // - EmitAutoVarCleanups enters the variable destructor cleanup
3560 // - EmitCXXTryStmt emits the code for the catch body
3561 // - EmitCXXTryStmt close the RunCleanupsScope
3562
3563 VarDecl *CatchParam = S->getExceptionDecl();
3564 if (!CatchParam) {
3565 llvm::Value *Exn = CGF.getExceptionFromSlot();
3566 CallBeginCatch(CGF, Exn, true);
3567 return;
3568 }
3569
3570 // Emit the local.
3571 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3572 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3573 CGF.EmitAutoVarCleanups(var);
3574}
3575
3576/// Get or define the following function:
3577/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3578/// This code is used only in C++.
3579static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3580 llvm::FunctionType *fnTy =
3581 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3582 llvm::Constant *fnRef =
3583 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3584
3585 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3586 if (fn && fn->empty()) {
3587 fn->setDoesNotThrow();
3588 fn->setDoesNotReturn();
3589
3590 // What we really want is to massively penalize inlining without
3591 // forbidding it completely. The difference between that and
3592 // 'noinline' is negligible.
3593 fn->addFnAttr(llvm::Attribute::NoInline);
3594
3595 // Allow this function to be shared across translation units, but
3596 // we don't want it to turn into an exported symbol.
3597 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3598 fn->setVisibility(llvm::Function::HiddenVisibility);
Derek Schuff2312bd32015-05-08 16:47:21 +00003599 CGM.maybeSetTrivialComdat(*fn);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003600
3601 // Set up the function.
3602 llvm::BasicBlock *entry =
3603 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3604 CGBuilderTy builder(entry);
3605
3606 // Pull the exception pointer out of the parameter list.
3607 llvm::Value *exn = &*fn->arg_begin();
3608
3609 // Call __cxa_begin_catch(exn).
3610 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3611 catchCall->setDoesNotThrow();
3612 catchCall->setCallingConv(CGM.getRuntimeCC());
3613
3614 // Call std::terminate().
3615 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
3616 termCall->setDoesNotThrow();
3617 termCall->setDoesNotReturn();
3618 termCall->setCallingConv(CGM.getRuntimeCC());
3619
3620 // std::terminate cannot return.
3621 builder.CreateUnreachable();
3622 }
3623
3624 return fnRef;
3625}
3626
3627llvm::CallInst *
3628ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3629 llvm::Value *Exn) {
3630 // In C++, we want to call __cxa_begin_catch() before terminating.
3631 if (Exn) {
3632 assert(CGF.CGM.getLangOpts().CPlusPlus);
3633 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3634 }
3635 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3636}