blob: 2fb6a5ec41f32792fba316d3d41d4bedf3a7a81c [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 Majnemerad803d42015-03-15 07:10:01 +0000128 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty, bool ForEH) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000129
David Majnemer1162d252014-06-22 19:05:33 +0000130 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
131 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
132 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
133 llvm::Value *ThisPtr,
134 llvm::Type *StdTypeInfoPtrTy) override;
135
136 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
137 QualType SrcRecordTy) override;
138
139 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
140 QualType SrcRecordTy, QualType DestTy,
141 QualType DestRecordTy,
142 llvm::BasicBlock *CastEnd) override;
143
144 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
145 QualType SrcRecordTy,
146 QualType DestTy) override;
147
148 bool EmitBadCastCall(CodeGenFunction &CGF) override;
149
Craig Topper4f12f102014-03-12 06:41:41 +0000150 llvm::Value *
151 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
152 const CXXRecordDecl *ClassDecl,
153 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000154
Craig Topper4f12f102014-03-12 06:41:41 +0000155 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000156
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000157 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
158 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000159
Reid Klecknere7de47e2013-07-22 13:51:44 +0000160 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000161 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000162 // Itanium does not emit any destructor variant as an inline thunk.
163 // Delegating may occur as an optimization, but all variants are either
164 // emitted with external linkage or as linkonce if they are inline and used.
165 return false;
166 }
167
Craig Topper4f12f102014-03-12 06:41:41 +0000168 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000169
Reid Kleckner89077a12013-12-17 19:46:40 +0000170 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000171 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000172
Craig Topper4f12f102014-03-12 06:41:41 +0000173 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000174
Reid Kleckner89077a12013-12-17 19:46:40 +0000175 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
176 const CXXConstructorDecl *D,
177 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000178 bool Delegating,
179 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000180
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000181 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
182 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000183 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000184
Craig Topper4f12f102014-03-12 06:41:41 +0000185 void emitVTableDefinitions(CodeGenVTables &CGVT,
186 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000187
188 llvm::Value *getVTableAddressPointInStructor(
189 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
190 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000191 bool &NeedsVirtualOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000192
193 llvm::Constant *
194 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000195 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000196
197 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000198 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000199
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000200 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000201 llvm::Value *This,
202 llvm::Type *Ty) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000203
David Majnemer0c0b6d92014-10-31 20:09:12 +0000204 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
205 const CXXDestructorDecl *Dtor,
206 CXXDtorType DtorType,
207 llvm::Value *This,
208 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000209
Craig Topper4f12f102014-03-12 06:41:41 +0000210 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000211
Hans Wennborgc94391d2014-06-06 20:04:01 +0000212 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
213 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000214 // Allow inlining of thunks by emitting them with available_externally
215 // linkage together with vtables when needed.
216 if (ForVTable)
217 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
218 }
219
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000220 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000221 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000222
223 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000224 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000225
David Majnemer196ac332014-09-11 23:05:02 +0000226 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
227 FunctionArgList &Args) const override {
228 assert(!Args.empty() && "expected the arglist to not be empty!");
229 return Args.size() - 1;
230 }
231
Craig Topper4f12f102014-03-12 06:41:41 +0000232 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
233 StringRef GetDeletedVirtualCallName() override
234 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000235
Craig Topper4f12f102014-03-12 06:41:41 +0000236 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000237 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
238 llvm::Value *NewPtr,
239 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000240 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000241 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000242 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
243 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000244 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000245
John McCallcdf7ef52010-11-06 09:44:32 +0000246 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000247 llvm::GlobalVariable *DeclPtr,
248 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000249 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000250 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000251
252 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000253 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000254 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000255 CodeGenModule &CGM,
256 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
257 CXXThreadLocals,
258 ArrayRef<llvm::Function *> CXXThreadLocalInits,
259 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
260
261 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000262 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
263 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000264
Craig Topper4f12f102014-03-12 06:41:41 +0000265 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000266
267 /**************************** RTTI Uniqueness ******************************/
268
269protected:
270 /// Returns true if the ABI requires RTTI type_info objects to be unique
271 /// across a program.
272 virtual bool shouldRTTIBeUnique() const { return true; }
273
274public:
275 /// What sort of unique-RTTI behavior should we use?
276 enum RTTIUniquenessKind {
277 /// We are guaranteeing, or need to guarantee, that the RTTI string
278 /// is unique.
279 RUK_Unique,
280
281 /// We are not guaranteeing uniqueness for the RTTI string, so we
282 /// can demote to hidden visibility but must use string comparisons.
283 RUK_NonUniqueHidden,
284
285 /// We are not guaranteeing uniqueness for the RTTI string, so we
286 /// have to use string comparisons, but we also have to emit it with
287 /// non-hidden visibility.
288 RUK_NonUniqueVisible
289 };
290
291 /// Return the required visibility status for the given type and linkage in
292 /// the current ABI.
293 RTTIUniquenessKind
294 classifyRTTIUniqueness(QualType CanTy,
295 llvm::GlobalValue::LinkageTypes Linkage) const;
296 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000297
298 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Charles Davis4e786dd2010-05-25 19:52:27 +0000299};
John McCall86353412010-08-21 22:46:04 +0000300
301class ARMCXXABI : public ItaniumCXXABI {
302public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000303 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
304 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
305 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000306
Craig Topper4f12f102014-03-12 06:41:41 +0000307 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000308 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
309 isa<CXXDestructorDecl>(GD.getDecl()) &&
310 GD.getDtorType() != Dtor_Deleting));
311 }
John McCall5d865c322010-08-31 07:33:07 +0000312
Craig Topper4f12f102014-03-12 06:41:41 +0000313 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
314 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000315
Craig Topper4f12f102014-03-12 06:41:41 +0000316 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000317 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
318 llvm::Value *NewPtr,
319 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000320 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000321 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000322 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000323 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000324};
Tim Northovera2ee4332014-03-29 15:09:45 +0000325
326class iOS64CXXABI : public ARMCXXABI {
327public:
328 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000329
330 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000331 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000332};
Charles Davis4e786dd2010-05-25 19:52:27 +0000333}
334
Charles Davis53c59df2010-08-16 03:33:14 +0000335CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000336 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000337 // For IR-generation purposes, there's no significant difference
338 // between the ARM and iOS ABIs.
339 case TargetCXXABI::GenericARM:
340 case TargetCXXABI::iOS:
341 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000342
Tim Northovera2ee4332014-03-29 15:09:45 +0000343 case TargetCXXABI::iOS64:
344 return new iOS64CXXABI(CGM);
345
Tim Northover9bb857a2013-01-31 12:13:10 +0000346 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
347 // include the other 32-bit ARM oddities: constructor/destructor return values
348 // and array cookies.
349 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000350 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
351 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000352
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000353 case TargetCXXABI::GenericMIPS:
354 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
355
John McCall57625922013-01-25 23:36:14 +0000356 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000357 if (CGM.getContext().getTargetInfo().getTriple().getArch()
358 == llvm::Triple::le32) {
359 // For PNaCl, use ARM-style method pointers so that PNaCl code
360 // does not assume anything about the alignment of function
361 // pointers.
362 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
363 /* UseARMGuardVarABI = */ false);
364 }
John McCall57625922013-01-25 23:36:14 +0000365 return new ItaniumCXXABI(CGM);
366
367 case TargetCXXABI::Microsoft:
368 llvm_unreachable("Microsoft ABI is not Itanium-based");
369 }
370 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000371}
372
Chris Lattnera5f58b02011-07-09 17:41:47 +0000373llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000374ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
375 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000376 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000377 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000378}
379
John McCalld9c6c0b2010-08-22 00:59:17 +0000380/// In the Itanium and ARM ABIs, method pointers have the form:
381/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
382///
383/// In the Itanium ABI:
384/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
385/// - the this-adjustment is (memptr.adj)
386/// - the virtual offset is (memptr.ptr - 1)
387///
388/// In the ARM ABI:
389/// - method pointers are virtual if (memptr.adj & 1) is nonzero
390/// - the this-adjustment is (memptr.adj >> 1)
391/// - the virtual offset is (memptr.ptr)
392/// ARM uses 'adj' for the virtual flag because Thumb functions
393/// may be only single-byte aligned.
394///
395/// If the member is virtual, the adjusted 'this' pointer points
396/// to a vtable pointer from which the virtual offset is applied.
397///
398/// If the member is non-virtual, memptr.ptr is the address of
399/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000400llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
401 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
402 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000403 CGBuilderTy &Builder = CGF.Builder;
404
405 const FunctionProtoType *FPT =
406 MPT->getPointeeType()->getAs<FunctionProtoType>();
407 const CXXRecordDecl *RD =
408 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
409
Chris Lattner2192fe52011-07-18 04:24:23 +0000410 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000411 CGM.getTypes().GetFunctionType(
412 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000413
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000414 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000415
John McCalld9c6c0b2010-08-22 00:59:17 +0000416 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
417 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
418 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
419
John McCalla1dee5302010-08-22 10:59:02 +0000420 // Extract memptr.adj, which is in the second field.
421 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000422
423 // Compute the true adjustment.
424 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000425 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000426 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000427
428 // Apply the adjustment and cast back to the original struct type
429 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000430 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
431 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
432 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000433
434 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000435 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000436
437 // If the LSB in the function pointer is 1, the function pointer points to
438 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000439 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000440 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000441 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
442 else
443 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
444 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000445 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
446
447 // In the virtual path, the adjustment left 'This' pointing to the
448 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000449 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000450 CGF.EmitBlock(FnVirtual);
451
452 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000453 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000454 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000455
456 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000457 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000458 if (!UseARMMethodPtrABI)
459 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000460 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000461
462 // Load the virtual function to call.
463 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000464 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000465 CGF.EmitBranch(FnEnd);
466
467 // In the non-virtual path, the function pointer is actually a
468 // function pointer.
469 CGF.EmitBlock(FnNonVirtual);
470 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000471 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000472
473 // We're done.
474 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000475 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000476 Callee->addIncoming(VirtualFn, FnVirtual);
477 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
478 return Callee;
479}
John McCalla8bbb822010-08-22 03:04:22 +0000480
John McCallc134eb52010-08-31 21:07:20 +0000481/// Compute an l-value by applying the given pointer-to-member to a
482/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000483llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
484 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
485 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000486 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000487
488 CGBuilderTy &Builder = CGF.Builder;
489
Micah Villmowea2fea22012-10-25 15:39:14 +0000490 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000491
492 // Cast to char*.
493 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
494
495 // Apply the offset, which we assume is non-null.
496 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
497
498 // Cast the address to the appropriate pointer type, adopting the
499 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000500 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000501 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000502 return Builder.CreateBitCast(Addr, PType);
503}
504
John McCallc62bb392012-02-15 01:22:51 +0000505/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
506/// conversion.
507///
508/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000509///
510/// Obligatory offset/adjustment diagram:
511/// <-- offset --> <-- adjustment -->
512/// |--------------------------|----------------------|--------------------|
513/// ^Derived address point ^Base address point ^Member address point
514///
515/// So when converting a base member pointer to a derived member pointer,
516/// we add the offset to the adjustment because the address point has
517/// decreased; and conversely, when converting a derived MP to a base MP
518/// we subtract the offset from the adjustment because the address point
519/// has increased.
520///
521/// The standard forbids (at compile time) conversion to and from
522/// virtual bases, which is why we don't have to consider them here.
523///
524/// The standard forbids (at run time) casting a derived MP to a base
525/// MP when the derived MP does not point to a member of the base.
526/// This is why -1 is a reasonable choice for null data member
527/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000528llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000529ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
530 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000531 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000532 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000533 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
534 E->getCastKind() == CK_ReinterpretMemberPointer);
535
536 // Under Itanium, reinterprets don't require any additional processing.
537 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
538
539 // Use constant emission if we can.
540 if (isa<llvm::Constant>(src))
541 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
542
543 llvm::Constant *adj = getMemberPointerAdjustment(E);
544 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000545
546 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000547 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000548
John McCallc62bb392012-02-15 01:22:51 +0000549 const MemberPointerType *destTy =
550 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000551
John McCall7a9aac22010-08-23 01:21:21 +0000552 // For member data pointers, this is just a matter of adding the
553 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000554 if (destTy->isMemberDataPointer()) {
555 llvm::Value *dst;
556 if (isDerivedToBase)
557 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000558 else
John McCallc62bb392012-02-15 01:22:51 +0000559 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000560
561 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000562 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
563 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
564 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000565 }
566
John McCalla1dee5302010-08-22 10:59:02 +0000567 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000568 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000569 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
570 offset <<= 1;
571 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000572 }
573
John McCallc62bb392012-02-15 01:22:51 +0000574 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
575 llvm::Value *dstAdj;
576 if (isDerivedToBase)
577 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000578 else
John McCallc62bb392012-02-15 01:22:51 +0000579 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000580
John McCallc62bb392012-02-15 01:22:51 +0000581 return Builder.CreateInsertValue(src, dstAdj, 1);
582}
583
584llvm::Constant *
585ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
586 llvm::Constant *src) {
587 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
588 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
589 E->getCastKind() == CK_ReinterpretMemberPointer);
590
591 // Under Itanium, reinterprets don't require any additional processing.
592 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
593
594 // If the adjustment is trivial, we don't need to do anything.
595 llvm::Constant *adj = getMemberPointerAdjustment(E);
596 if (!adj) return src;
597
598 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
599
600 const MemberPointerType *destTy =
601 E->getType()->castAs<MemberPointerType>();
602
603 // For member data pointers, this is just a matter of adding the
604 // offset if the source is non-null.
605 if (destTy->isMemberDataPointer()) {
606 // null maps to null.
607 if (src->isAllOnesValue()) return src;
608
609 if (isDerivedToBase)
610 return llvm::ConstantExpr::getNSWSub(src, adj);
611 else
612 return llvm::ConstantExpr::getNSWAdd(src, adj);
613 }
614
615 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000616 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000617 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
618 offset <<= 1;
619 adj = llvm::ConstantInt::get(adj->getType(), offset);
620 }
621
622 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
623 llvm::Constant *dstAdj;
624 if (isDerivedToBase)
625 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
626 else
627 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
628
629 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000630}
John McCall84fa5102010-08-22 04:16:24 +0000631
632llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000633ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000634 // Itanium C++ ABI 2.3:
635 // A NULL pointer is represented as -1.
636 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000637 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000638
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000639 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000640 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000641 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000642}
643
John McCallf3a88602011-02-03 08:15:49 +0000644llvm::Constant *
645ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
646 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000647 // Itanium C++ ABI 2.3:
648 // A pointer to data member is an offset from the base address of
649 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000650 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000651}
652
John McCall2979fe02011-04-12 00:42:48 +0000653llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000654 return BuildMemberPointer(MD, CharUnits::Zero());
655}
656
657llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
658 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000659 assert(MD->isInstance() && "Member function must not be static!");
660 MD = MD->getCanonicalDecl();
661
662 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000663
664 // Get the function pointer (or index if this is a virtual function).
665 llvm::Constant *MemPtr[2];
666 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000667 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000668
Ken Dyckdf016282011-04-09 01:30:02 +0000669 const ASTContext &Context = getContext();
670 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000671 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000672 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000673
Mark Seabornedf0d382013-07-24 16:25:13 +0000674 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000675 // ARM C++ ABI 3.2.1:
676 // This ABI specifies that adj contains twice the this
677 // adjustment, plus 1 if the member function is virtual. The
678 // least significant bit of adj then makes exactly the same
679 // discrimination as the least significant bit of ptr does for
680 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000681 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
682 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000683 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000684 } else {
685 // Itanium C++ ABI 2.3:
686 // For a virtual function, [the pointer field] is 1 plus the
687 // virtual table offset (in bytes) of the function,
688 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000689 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
690 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000691 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000692 }
693 } else {
John McCall2979fe02011-04-12 00:42:48 +0000694 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000695 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000696 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000697 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000698 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000699 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000700 } else {
John McCall2979fe02011-04-12 00:42:48 +0000701 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
702 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000703 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000704 }
John McCall2979fe02011-04-12 00:42:48 +0000705 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000706
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000707 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000708 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
709 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000710 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000711 }
John McCall1c456c82010-08-22 06:43:33 +0000712
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000713 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000714}
715
Richard Smithdafff942012-01-14 04:30:29 +0000716llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
717 QualType MPType) {
718 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
719 const ValueDecl *MPD = MP.getMemberPointerDecl();
720 if (!MPD)
721 return EmitNullMemberPointer(MPT);
722
Reid Kleckner452abac2013-05-09 21:01:17 +0000723 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000724
725 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
726 return BuildMemberPointer(MD, ThisAdjustment);
727
728 CharUnits FieldOffset =
729 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
730 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
731}
732
John McCall131d97d2010-08-22 08:30:07 +0000733/// The comparison algorithm is pretty easy: the member pointers are
734/// the same if they're either bitwise identical *or* both null.
735///
736/// ARM is different here only because null-ness is more complicated.
737llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000738ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
739 llvm::Value *L,
740 llvm::Value *R,
741 const MemberPointerType *MPT,
742 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000743 CGBuilderTy &Builder = CGF.Builder;
744
John McCall131d97d2010-08-22 08:30:07 +0000745 llvm::ICmpInst::Predicate Eq;
746 llvm::Instruction::BinaryOps And, Or;
747 if (Inequality) {
748 Eq = llvm::ICmpInst::ICMP_NE;
749 And = llvm::Instruction::Or;
750 Or = llvm::Instruction::And;
751 } else {
752 Eq = llvm::ICmpInst::ICMP_EQ;
753 And = llvm::Instruction::And;
754 Or = llvm::Instruction::Or;
755 }
756
John McCall7a9aac22010-08-23 01:21:21 +0000757 // Member data pointers are easy because there's a unique null
758 // value, so it just comes down to bitwise equality.
759 if (MPT->isMemberDataPointer())
760 return Builder.CreateICmp(Eq, L, R);
761
762 // For member function pointers, the tautologies are more complex.
763 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000764 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000765 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000766 // (L == R) <==> (L.ptr == R.ptr &&
767 // (L.adj == R.adj ||
768 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000769 // The inequality tautologies have exactly the same structure, except
770 // applying De Morgan's laws.
771
772 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
773 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
774
John McCall131d97d2010-08-22 08:30:07 +0000775 // This condition tests whether L.ptr == R.ptr. This must always be
776 // true for equality to hold.
777 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
778
779 // This condition, together with the assumption that L.ptr == R.ptr,
780 // tests whether the pointers are both null. ARM imposes an extra
781 // condition.
782 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
783 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
784
785 // This condition tests whether L.adj == R.adj. If this isn't
786 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000787 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
788 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000789 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
790
791 // Null member function pointers on ARM clear the low bit of Adj,
792 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000793 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000794 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
795
796 // Compute (l.adj | r.adj) & 1 and test it against zero.
797 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
798 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
799 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
800 "cmp.or.adj");
801 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
802 }
803
804 // Tie together all our conditions.
805 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
806 Result = Builder.CreateBinOp(And, PtrEq, Result,
807 Inequality ? "memptr.ne" : "memptr.eq");
808 return Result;
809}
810
811llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000812ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
813 llvm::Value *MemPtr,
814 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000815 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000816
817 /// For member data pointers, this is just a check against -1.
818 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000819 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000820 llvm::Value *NegativeOne =
821 llvm::Constant::getAllOnesValue(MemPtr->getType());
822 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
823 }
John McCall131d97d2010-08-22 08:30:07 +0000824
Daniel Dunbar914bc412011-04-19 23:10:47 +0000825 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000826 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000827
828 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
829 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
830
Daniel Dunbar914bc412011-04-19 23:10:47 +0000831 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
832 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000833 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000834 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000835 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000836 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000837 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
838 "memptr.isvirtual");
839 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000840 }
841
842 return Result;
843}
John McCall1c456c82010-08-22 06:43:33 +0000844
Reid Kleckner40ca9132014-05-13 22:05:45 +0000845bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
846 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
847 if (!RD)
848 return false;
849
Reid Klecknerd355ca72014-05-15 01:26:32 +0000850 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
851 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
852 // special members.
853 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000854 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
855 return true;
856 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000857 return false;
858}
859
John McCall614dbdc2010-08-22 21:01:12 +0000860/// The Itanium ABI requires non-zero initialization only for data
861/// member pointers, for which '0' is a valid offset.
862bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
863 return MPT->getPointeeType()->isFunctionType();
John McCall84fa5102010-08-22 04:16:24 +0000864}
John McCall5d865c322010-08-31 07:33:07 +0000865
John McCall82fb8922012-09-25 10:10:39 +0000866/// The Itanium ABI always places an offset to the complete object
867/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000868void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
869 const CXXDeleteExpr *DE,
870 llvm::Value *Ptr,
871 QualType ElementType,
872 const CXXDestructorDecl *Dtor) {
873 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000874 if (UseGlobalDelete) {
875 // Derive the complete-object pointer, which is what we need
876 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000877
David Majnemer0c0b6d92014-10-31 20:09:12 +0000878 // Grab the vtable pointer as an intptr_t*.
879 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000880
David Majnemer0c0b6d92014-10-31 20:09:12 +0000881 // Track back to entry -2 and pull out the offset there.
882 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
883 VTable, -2, "complete-offset.ptr");
884 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
885 Offset->setAlignment(CGF.PointerAlignInBytes);
886
887 // Apply the offset.
888 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
889 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
890
891 // If we're supposed to call the global delete, make sure we do so
892 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000893 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
894 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000895 }
896
897 // FIXME: Provide a source location here even though there's no
898 // CXXMemberCallExpr for dtor call.
899 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
900 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
901
902 if (UseGlobalDelete)
903 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000904}
905
David Majnemer442d0a22014-11-25 07:20:20 +0000906void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
907 // void __cxa_rethrow();
908
909 llvm::FunctionType *FTy =
910 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
911
912 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
913
914 if (isNoReturn)
915 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
916 else
917 CGF.EmitRuntimeCallOrInvoke(Fn);
918}
919
David Majnemer7c237072015-03-05 00:46:22 +0000920static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
921 // void *__cxa_allocate_exception(size_t thrown_size);
922
923 llvm::FunctionType *FTy =
924 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
925
926 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
927}
928
929static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
930 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
931 // void (*dest) (void *));
932
933 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
934 llvm::FunctionType *FTy =
935 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
936
937 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
938}
939
940void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
941 QualType ThrowType = E->getSubExpr()->getType();
942 // Now allocate the exception object.
943 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
944 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
945
946 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
947 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
948 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
949
950 CGF.EmitAnyExprToExn(E->getSubExpr(), ExceptionPtr);
951
952 // Now throw the exception.
953 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
954 /*ForEH=*/true);
955
956 // The address of the destructor. If the exception type has a
957 // trivial destructor (or isn't a record), we just pass null.
958 llvm::Constant *Dtor = nullptr;
959 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
960 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
961 if (!Record->hasTrivialDestructor()) {
962 CXXDestructorDecl *DtorD = Record->getDestructor();
963 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
964 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
965 }
966 }
967 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
968
969 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
970 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
971}
972
David Majnemer1162d252014-06-22 19:05:33 +0000973static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
974 // void *__dynamic_cast(const void *sub,
975 // const abi::__class_type_info *src,
976 // const abi::__class_type_info *dst,
977 // std::ptrdiff_t src2dst_offset);
978
979 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
980 llvm::Type *PtrDiffTy =
981 CGF.ConvertType(CGF.getContext().getPointerDiffType());
982
983 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
984
985 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
986
987 // Mark the function as nounwind readonly.
988 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
989 llvm::Attribute::ReadOnly };
990 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
991 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
992
993 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
994}
995
996static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
997 // void __cxa_bad_cast();
998 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
999 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1000}
1001
1002/// \brief Compute the src2dst_offset hint as described in the
1003/// Itanium C++ ABI [2.9.7]
1004static CharUnits computeOffsetHint(ASTContext &Context,
1005 const CXXRecordDecl *Src,
1006 const CXXRecordDecl *Dst) {
1007 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1008 /*DetectVirtual=*/false);
1009
1010 // If Dst is not derived from Src we can skip the whole computation below and
1011 // return that Src is not a public base of Dst. Record all inheritance paths.
1012 if (!Dst->isDerivedFrom(Src, Paths))
1013 return CharUnits::fromQuantity(-2ULL);
1014
1015 unsigned NumPublicPaths = 0;
1016 CharUnits Offset;
1017
1018 // Now walk all possible inheritance paths.
1019 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
1020 ++I) {
1021 if (I->Access != AS_public) // Ignore non-public inheritance.
1022 continue;
1023
1024 ++NumPublicPaths;
1025
1026 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
1027 // If the path contains a virtual base class we can't give any hint.
1028 // -1: no hint.
1029 if (J->Base->isVirtual())
1030 return CharUnits::fromQuantity(-1ULL);
1031
1032 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1033 continue;
1034
1035 // Accumulate the base class offsets.
1036 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
1037 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
1038 }
1039 }
1040
1041 // -2: Src is not a public base of Dst.
1042 if (NumPublicPaths == 0)
1043 return CharUnits::fromQuantity(-2ULL);
1044
1045 // -3: Src is a multiple public base type but never a virtual base type.
1046 if (NumPublicPaths > 1)
1047 return CharUnits::fromQuantity(-3ULL);
1048
1049 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1050 // Return the offset of Src from the origin of Dst.
1051 return Offset;
1052}
1053
1054static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1055 // void __cxa_bad_typeid();
1056 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1057
1058 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1059}
1060
1061bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1062 QualType SrcRecordTy) {
1063 return IsDeref;
1064}
1065
1066void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1067 llvm::Value *Fn = getBadTypeidFn(CGF);
1068 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1069 CGF.Builder.CreateUnreachable();
1070}
1071
1072llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1073 QualType SrcRecordTy,
1074 llvm::Value *ThisPtr,
1075 llvm::Type *StdTypeInfoPtrTy) {
1076 llvm::Value *Value =
1077 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1078
1079 // Load the type info.
1080 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1081 return CGF.Builder.CreateLoad(Value);
1082}
1083
1084bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1085 QualType SrcRecordTy) {
1086 return SrcIsPtr;
1087}
1088
1089llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1090 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1091 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1092 llvm::Type *PtrDiffLTy =
1093 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1094 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1095
1096 llvm::Value *SrcRTTI =
1097 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1098 llvm::Value *DestRTTI =
1099 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1100
1101 // Compute the offset hint.
1102 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1103 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1104 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1105 PtrDiffLTy,
1106 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1107
1108 // Emit the call to __dynamic_cast.
1109 Value = CGF.EmitCastToVoidPtr(Value);
1110
1111 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1112 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1113 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1114
1115 /// C++ [expr.dynamic.cast]p9:
1116 /// A failed cast to reference type throws std::bad_cast
1117 if (DestTy->isReferenceType()) {
1118 llvm::BasicBlock *BadCastBlock =
1119 CGF.createBasicBlock("dynamic_cast.bad_cast");
1120
1121 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1122 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1123
1124 CGF.EmitBlock(BadCastBlock);
1125 EmitBadCastCall(CGF);
1126 }
1127
1128 return Value;
1129}
1130
1131llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1132 llvm::Value *Value,
1133 QualType SrcRecordTy,
1134 QualType DestTy) {
1135 llvm::Type *PtrDiffLTy =
1136 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1137 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1138
1139 // Get the vtable pointer.
1140 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1141
1142 // Get the offset-to-top from the vtable.
1143 llvm::Value *OffsetToTop =
1144 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1145 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1146
1147 // Finally, add the offset to the pointer.
1148 Value = CGF.EmitCastToVoidPtr(Value);
1149 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1150
1151 return CGF.Builder.CreateBitCast(Value, DestLTy);
1152}
1153
1154bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1155 llvm::Value *Fn = getBadCastFn(CGF);
1156 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1157 CGF.Builder.CreateUnreachable();
1158 return true;
1159}
1160
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001161llvm::Value *
1162ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1163 llvm::Value *This,
1164 const CXXRecordDecl *ClassDecl,
1165 const CXXRecordDecl *BaseClassDecl) {
1166 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1167 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001168 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1169 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001170
1171 llvm::Value *VBaseOffsetPtr =
1172 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1173 "vbase.offset.ptr");
1174 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1175 CGM.PtrDiffTy->getPointerTo());
1176
1177 llvm::Value *VBaseOffset =
1178 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1179
1180 return VBaseOffset;
1181}
1182
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001183void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1184 // Just make sure we're in sync with TargetCXXABI.
1185 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1186
Rafael Espindolac3cde362013-12-09 14:51:17 +00001187 // The constructor used for constructing this as a base class;
1188 // ignores virtual bases.
1189 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1190
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001191 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001192 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001193 if (!D->getParent()->isAbstract()) {
1194 // We don't need to emit the complete ctor if the class is abstract.
1195 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1196 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001197}
1198
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001199void
1200ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1201 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001202 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001203
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001204 // All parameters are already in place except VTT, which goes after 'this'.
1205 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001206
1207 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001208 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1209 ArgTys.insert(ArgTys.begin() + 1,
1210 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001211}
1212
Reid Klecknere7de47e2013-07-22 13:51:44 +00001213void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001214 // The destructor used for destructing this as a base class; ignores
1215 // virtual bases.
1216 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001217
1218 // The destructor used for destructing this as a most-derived class;
1219 // call the base destructor and then destructs any virtual bases.
1220 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1221
Rafael Espindolac3cde362013-12-09 14:51:17 +00001222 // The destructor in a virtual table is always a 'deleting'
1223 // destructor, which calls the complete destructor and then uses the
1224 // appropriate operator delete.
1225 if (D->isVirtual())
1226 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001227}
1228
Reid Kleckner89077a12013-12-17 19:46:40 +00001229void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1230 QualType &ResTy,
1231 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001232 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001233 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001234
1235 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001236 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001237 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001238
1239 // FIXME: avoid the fake decl
1240 QualType T = Context.getPointerType(Context.VoidPtrTy);
1241 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001242 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001243 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001244 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001245 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001246 }
1247}
1248
John McCall5d865c322010-08-31 07:33:07 +00001249void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1250 /// Initialize the 'this' slot.
1251 EmitThisParam(CGF);
1252
1253 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001254 if (getStructorImplicitParamDecl(CGF)) {
1255 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1256 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001257 }
John McCall5d865c322010-08-31 07:33:07 +00001258
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001259 /// If this is a function that the ABI specifies returns 'this', initialize
1260 /// the return slot to 'this' at the start of the function.
1261 ///
1262 /// Unlike the setting of return types, this is done within the ABI
1263 /// implementation instead of by clients of CGCXXABI because:
1264 /// 1) getThisValue is currently protected
1265 /// 2) in theory, an ABI could implement 'this' returns some other way;
1266 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001267 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001268 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001269}
1270
Reid Kleckner89077a12013-12-17 19:46:40 +00001271unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1272 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1273 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1274 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1275 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001276
Reid Kleckner89077a12013-12-17 19:46:40 +00001277 // Insert the implicit 'vtt' argument as the second argument.
1278 llvm::Value *VTT =
1279 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1280 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1281 Args.insert(Args.begin() + 1,
1282 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1283 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001284}
1285
1286void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1287 const CXXDestructorDecl *DD,
1288 CXXDtorType Type, bool ForVirtualBase,
1289 bool Delegating, llvm::Value *This) {
1290 GlobalDecl GD(DD, Type);
1291 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1292 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1293
Craig Topper8a13c412014-05-21 05:09:00 +00001294 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001295 if (getContext().getLangOpts().AppleKext)
1296 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1297
1298 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001299 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001300
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001301 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1302 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001303}
1304
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001305void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1306 const CXXRecordDecl *RD) {
1307 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1308 if (VTable->hasInitializer())
1309 return;
1310
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001311 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001312 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1313 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001314 llvm::Constant *RTTI =
1315 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001316
1317 // Create and set the initializer.
1318 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1319 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001320 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001321 VTable->setInitializer(Init);
1322
1323 // Set the correct linkage.
1324 VTable->setLinkage(Linkage);
1325
Rafael Espindolacb92c192015-01-15 23:18:01 +00001326 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1327 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
1328
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001329 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001330 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001331
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001332 // Use pointer alignment for the vtable. Otherwise we would align them based
1333 // on the size of the initializer which doesn't make sense as only single
1334 // values are read.
1335 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1336 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1337
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001338 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1339 // we will emit the typeinfo for the fundamental types. This is the
1340 // same behaviour as GCC.
1341 const DeclContext *DC = RD->getDeclContext();
1342 if (RD->getIdentifier() &&
1343 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1344 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1345 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1346 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001347 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001348
1349 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001350}
1351
1352llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1353 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1354 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1355 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1356 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1357
1358 llvm::Value *VTableAddressPoint;
1359 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1360 // Get the secondary vpointer index.
1361 uint64_t VirtualPointerIndex =
1362 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1363
1364 /// Load the VTT.
1365 llvm::Value *VTT = CGF.LoadCXXVTT();
1366 if (VirtualPointerIndex)
1367 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1368
1369 // And load the address point from the VTT.
1370 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1371 } else {
1372 llvm::Constant *VTable =
1373 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001374 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1375 .getVTableLayout(VTableClass)
1376 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001377 VTableAddressPoint =
1378 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1379 }
1380
1381 return VTableAddressPoint;
1382}
1383
1384llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1385 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1386 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1387
1388 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001389 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1390 .getVTableLayout(VTableClass)
1391 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001392 llvm::Value *Indices[] = {
1393 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1394 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1395 };
1396
1397 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1398}
1399
1400llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1401 CharUnits VPtrOffset) {
1402 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1403
1404 llvm::GlobalVariable *&VTable = VTables[RD];
1405 if (VTable)
1406 return VTable;
1407
1408 // Queue up this v-table for possible deferred emission.
1409 CGM.addDeferredVTable(RD);
1410
1411 SmallString<256> OutName;
1412 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001413 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001414 Out.flush();
1415 StringRef Name = OutName.str();
1416
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001417 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001418 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1419 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1420
1421 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1422 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1423 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001424
1425 if (RD->hasAttr<DLLImportAttr>())
1426 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1427 else if (RD->hasAttr<DLLExportAttr>())
1428 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1429
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001430 return VTable;
1431}
1432
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001433llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1434 GlobalDecl GD,
1435 llvm::Value *This,
1436 llvm::Type *Ty) {
1437 GD = GD.getCanonicalDecl();
1438 Ty = Ty->getPointerTo()->getPointerTo();
1439 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1440
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001441 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable);
1442
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001443 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001444 llvm::Value *VFuncPtr =
1445 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1446 return CGF.Builder.CreateLoad(VFuncPtr);
1447}
1448
David Majnemer0c0b6d92014-10-31 20:09:12 +00001449llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1450 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1451 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001452 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001453 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1454
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001455 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1456 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001457 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001458 llvm::Value *Callee =
1459 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001460
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001461 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1462 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001463 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001464}
1465
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001466void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001467 CodeGenVTables &VTables = CGM.getVTables();
1468 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001469 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001470}
1471
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001472static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1473 llvm::Value *Ptr,
1474 int64_t NonVirtualAdjustment,
1475 int64_t VirtualAdjustment,
1476 bool IsReturnAdjustment) {
1477 if (!NonVirtualAdjustment && !VirtualAdjustment)
1478 return Ptr;
1479
1480 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1481 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1482
1483 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1484 // Perform the non-virtual adjustment for a base-to-derived cast.
1485 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1486 }
1487
1488 if (VirtualAdjustment) {
1489 llvm::Type *PtrDiffTy =
1490 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1491
1492 // Perform the virtual adjustment.
1493 llvm::Value *VTablePtrPtr =
1494 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1495
1496 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1497
1498 llvm::Value *OffsetPtr =
1499 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1500
1501 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1502
1503 // Load the adjustment offset from the vtable.
1504 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1505
1506 // Adjust our pointer.
1507 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1508 }
1509
1510 if (NonVirtualAdjustment && IsReturnAdjustment) {
1511 // Perform the non-virtual adjustment for a derived-to-base cast.
1512 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1513 }
1514
1515 // Cast back to the original type.
1516 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1517}
1518
1519llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1520 llvm::Value *This,
1521 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001522 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1523 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001524 /*IsReturnAdjustment=*/false);
1525}
1526
1527llvm::Value *
1528ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1529 const ReturnAdjustment &RA) {
1530 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1531 RA.Virtual.Itanium.VBaseOffsetOffset,
1532 /*IsReturnAdjustment=*/true);
1533}
1534
John McCall5d865c322010-08-31 07:33:07 +00001535void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1536 RValue RV, QualType ResultType) {
1537 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1538 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1539
1540 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001541 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001542 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1543 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1544 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1545}
John McCall8ed55a52010-09-02 09:58:18 +00001546
1547/************************** Array allocation cookies **************************/
1548
John McCallb91cd662012-05-01 05:23:51 +00001549CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1550 // The array cookie is a size_t; pad that up to the element alignment.
1551 // The cookie is actually right-justified in that space.
1552 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1553 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001554}
1555
1556llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1557 llvm::Value *NewPtr,
1558 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001559 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001560 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001561 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001562
Micah Villmowea2fea22012-10-25 15:39:14 +00001563 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001564
John McCall9bca9232010-09-02 10:25:57 +00001565 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001566 QualType SizeTy = Ctx.getSizeType();
1567 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1568
1569 // The size of the cookie.
1570 CharUnits CookieSize =
1571 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001572 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001573
1574 // Compute an offset to the cookie.
1575 llvm::Value *CookiePtr = NewPtr;
1576 CharUnits CookieOffset = CookieSize - SizeSize;
1577 if (!CookieOffset.isZero())
1578 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1579 CookieOffset.getQuantity());
1580
1581 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001582 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1583 llvm::Value *NumElementsPtr =
1584 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1585 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001586 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001587 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001588 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001589 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1590 llvm::FunctionType *FTy =
1591 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1592 llvm::Constant *F =
1593 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1594 CGF.Builder.CreateCall(F, NumElementsPtr);
1595 }
John McCall8ed55a52010-09-02 09:58:18 +00001596
1597 // Finally, compute a pointer to the actual data buffer by skipping
1598 // over the cookie completely.
1599 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1600 CookieSize.getQuantity());
1601}
1602
John McCallb91cd662012-05-01 05:23:51 +00001603llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1604 llvm::Value *allocPtr,
1605 CharUnits cookieSize) {
1606 // The element size is right-justified in the cookie.
1607 llvm::Value *numElementsPtr = allocPtr;
1608 CharUnits numElementsOffset =
1609 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1610 if (!numElementsOffset.isZero())
1611 numElementsPtr =
1612 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1613 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001614
Micah Villmowea2fea22012-10-25 15:39:14 +00001615 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001616 numElementsPtr =
1617 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001618 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001619 return CGF.Builder.CreateLoad(numElementsPtr);
1620 // In asan mode emit a function call instead of a regular load and let the
1621 // run-time deal with it: if the shadow is properly poisoned return the
1622 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1623 // We can't simply ignore this load using nosanitize metadata because
1624 // the metadata may be lost.
1625 llvm::FunctionType *FTy =
1626 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1627 llvm::Constant *F =
1628 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1629 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001630}
1631
John McCallb91cd662012-05-01 05:23:51 +00001632CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001633 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001634 // struct array_cookie {
1635 // std::size_t element_size; // element_size != 0
1636 // std::size_t element_count;
1637 // };
John McCallc19c7062013-01-25 23:36:19 +00001638 // But the base ABI doesn't give anything an alignment greater than
1639 // 8, so we can dismiss this as typical ABI-author blindness to
1640 // actual language complexity and round up to the element alignment.
1641 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1642 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001643}
1644
1645llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001646 llvm::Value *newPtr,
1647 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001648 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001649 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001650 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001651
John McCallc19c7062013-01-25 23:36:19 +00001652 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1653 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001654
1655 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001656 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001657
1658 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001659 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1660 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1661 getContext().getTypeSizeInChars(elementType).getQuantity());
1662 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001663
1664 // The second element is the element count.
John McCallc19c7062013-01-25 23:36:19 +00001665 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1666 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001667
1668 // Finally, compute a pointer to the actual data buffer by skipping
1669 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001670 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1671 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1672 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001673}
1674
John McCallb91cd662012-05-01 05:23:51 +00001675llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1676 llvm::Value *allocPtr,
1677 CharUnits cookieSize) {
1678 // The number of elements is at offset sizeof(size_t) relative to
1679 // the allocated pointer.
1680 llvm::Value *numElementsPtr
1681 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001682
Micah Villmowea2fea22012-10-25 15:39:14 +00001683 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001684 numElementsPtr =
1685 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1686 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001687}
1688
John McCall68ff0372010-09-08 01:44:27 +00001689/*********************** Static local initialization **************************/
1690
1691static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001692 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001693 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001694 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001695 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001696 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001697 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001698 llvm::AttributeSet::get(CGM.getLLVMContext(),
1699 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001700 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001701}
1702
1703static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001704 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001705 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001706 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001707 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001708 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001709 llvm::AttributeSet::get(CGM.getLLVMContext(),
1710 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001711 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001712}
1713
1714static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001715 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001716 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001717 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001718 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001719 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001720 llvm::AttributeSet::get(CGM.getLLVMContext(),
1721 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001722 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001723}
1724
1725namespace {
1726 struct CallGuardAbort : EHScopeStack::Cleanup {
1727 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001728 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001729
Craig Topper4f12f102014-03-12 06:41:41 +00001730 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001731 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1732 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001733 }
1734 };
1735}
1736
1737/// The ARM code here follows the Itanium code closely enough that we
1738/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001739void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1740 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001741 llvm::GlobalVariable *var,
1742 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001743 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001744
Richard Smithdbf74ba2013-04-14 23:01:42 +00001745 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001746 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001747 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1748 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001749
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001750 // If we have a global variable with internal linkage and thread-safe statics
1751 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001752 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1753
1754 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001755 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001756 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001757 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001758 // Guard variables are 64 bits in the generic ABI and size width on ARM
1759 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001760 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001761 }
John McCallb88a5662012-03-30 21:00:39 +00001762 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001763
John McCallb88a5662012-03-30 21:00:39 +00001764 // Create the guard variable if we don't already have it (as we
1765 // might if we're double-emitting this function body).
1766 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1767 if (!guard) {
1768 // Mangle the name for the guard.
1769 SmallString<256> guardName;
1770 {
1771 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001772 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001773 out.flush();
1774 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001775
John McCallb88a5662012-03-30 21:00:39 +00001776 // Create the guard variable with a zero-initializer.
1777 // Just absorb linkage and visibility from the guarded variable.
1778 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1779 false, var->getLinkage(),
1780 llvm::ConstantInt::get(guardTy, 0),
1781 guardName.str());
1782 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001783 // If the variable is thread-local, so is its guard variable.
1784 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001785
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001786 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1787 // as the associated data object
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001788 llvm::Comdat *C = var->getComdat();
1789 if (!D.isLocalVarDecl() && C) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001790 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001791 CGF.CurFn->setComdat(C);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001792 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1793 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001794 }
1795
John McCallb88a5662012-03-30 21:00:39 +00001796 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1797 }
John McCall87590e62012-03-30 07:09:50 +00001798
John McCall68ff0372010-09-08 01:44:27 +00001799 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001800 //
John McCall68ff0372010-09-08 01:44:27 +00001801 // Itanium C++ ABI 3.3.2:
1802 // The following is pseudo-code showing how these functions can be used:
1803 // if (obj_guard.first_byte == 0) {
1804 // if ( __cxa_guard_acquire (&obj_guard) ) {
1805 // try {
1806 // ... initialize the object ...;
1807 // } catch (...) {
1808 // __cxa_guard_abort (&obj_guard);
1809 // throw;
1810 // }
1811 // ... queue object destructor with __cxa_atexit() ...;
1812 // __cxa_guard_release (&obj_guard);
1813 // }
1814 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001815
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001816 // Load the first byte of the guard variable.
1817 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001818 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001819 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001820
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001821 // Itanium ABI:
1822 // An implementation supporting thread-safety on multiprocessor
1823 // systems must also guarantee that references to the initialized
1824 // object do not occur before the load of the initialization flag.
1825 //
1826 // In LLVM, we do this by marking the load Acquire.
1827 if (threadsafe)
1828 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001829
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001830 // For ARM, we should only check the first bit, rather than the entire byte:
1831 //
1832 // ARM C++ ABI 3.2.3.1:
1833 // To support the potential use of initialization guard variables
1834 // as semaphores that are the target of ARM SWP and LDREX/STREX
1835 // synchronizing instructions we define a static initialization
1836 // guard variable to be a 4-byte aligned, 4-byte word with the
1837 // following inline access protocol.
1838 // #define INITIALIZED 1
1839 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1840 // if (__cxa_guard_acquire(&obj_guard))
1841 // ...
1842 // }
1843 //
1844 // and similarly for ARM64:
1845 //
1846 // ARM64 C++ ABI 3.2.2:
1847 // This ABI instead only specifies the value bit 0 of the static guard
1848 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1849 // variable is not initialized and 1 when it is.
1850 llvm::Value *V =
1851 (UseARMGuardVarABI && !useInt8GuardVariable)
1852 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1853 : LI;
1854 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001855
1856 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1857 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1858
1859 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001860 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001861
1862 CGF.EmitBlock(InitCheckBlock);
1863
1864 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001865 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001866 // Call __cxa_guard_acquire.
1867 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001868 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001869
1870 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1871
1872 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1873 InitBlock, EndBlock);
1874
1875 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001876 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001877
1878 CGF.EmitBlock(InitBlock);
1879 }
1880
1881 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001882 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001883
John McCall5aa52592011-06-17 07:33:57 +00001884 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001885 // Pop the guard-abort cleanup if we pushed one.
1886 CGF.PopCleanupBlock();
1887
1888 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001889 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001890 } else {
John McCallb88a5662012-03-30 21:00:39 +00001891 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001892 }
1893
1894 CGF.EmitBlock(EndBlock);
1895}
John McCallc84ed6a2012-05-01 06:13:13 +00001896
1897/// Register a global destructor using __cxa_atexit.
1898static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1899 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001900 llvm::Constant *addr,
1901 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001902 const char *Name = "__cxa_atexit";
1903 if (TLS) {
1904 const llvm::Triple &T = CGF.getTarget().getTriple();
1905 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1906 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001907
John McCallc84ed6a2012-05-01 06:13:13 +00001908 // We're assuming that the destructor function is something we can
1909 // reasonably call with the default CC. Go ahead and cast it to the
1910 // right prototype.
1911 llvm::Type *dtorTy =
1912 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1913
1914 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1915 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1916 llvm::FunctionType *atexitTy =
1917 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1918
1919 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001920 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001921 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1922 fn->setDoesNotThrow();
1923
1924 // Create a variable that binds the atexit to this shared object.
1925 llvm::Constant *handle =
1926 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1927
1928 llvm::Value *args[] = {
1929 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1930 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1931 handle
1932 };
John McCall882987f2013-02-28 19:01:20 +00001933 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001934}
1935
1936/// Register a global destructor as best as we know how.
1937void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001938 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00001939 llvm::Constant *dtor,
1940 llvm::Constant *addr) {
1941 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001942 if (CGM.getCodeGenOpts().CXAAtExit)
1943 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1944
1945 if (D.getTLSKind())
1946 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00001947
1948 // In Apple kexts, we want to add a global destructor entry.
1949 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00001950 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00001951 // Generate a global destructor entry.
1952 return CGM.AddCXXDtorEntry(dtor, addr);
1953 }
1954
David Blaikieebe87e12013-08-27 23:57:18 +00001955 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00001956}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001957
David Majnemer9b21c332014-07-11 20:28:10 +00001958static bool isThreadWrapperReplaceable(const VarDecl *VD,
1959 CodeGen::CodeGenModule &CGM) {
1960 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1961 // OS X prefers to have references to thread local variables to go through
1962 // the thread wrapper instead of directly referencing the backing variable.
1963 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1964 CGM.getTarget().getTriple().isMacOSX();
1965}
1966
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001967/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00001968/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001969/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00001970static llvm::GlobalValue::LinkageTypes
1971getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1972 llvm::GlobalValue::LinkageTypes VarLinkage =
1973 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1974
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001975 // For internal linkage variables, we don't need an external or weak wrapper.
1976 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1977 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00001978
David Majnemer9b21c332014-07-11 20:28:10 +00001979 // If the thread wrapper is replaceable, give it appropriate linkage.
1980 if (isThreadWrapperReplaceable(VD, CGM)) {
1981 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1982 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1983 return llvm::GlobalVariable::WeakAnyLinkage;
1984 return VarLinkage;
1985 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001986 return llvm::GlobalValue::WeakODRLinkage;
1987}
1988
1989llvm::Function *
1990ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00001991 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001992 // Mangle the name for the thread_local wrapper function.
1993 SmallString<256> WrapperName;
1994 {
1995 llvm::raw_svector_ostream Out(WrapperName);
1996 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1997 Out.flush();
1998 }
1999
Alexander Musmanf94c3182014-09-26 06:28:25 +00002000 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002001 return cast<llvm::Function>(V);
2002
Alexander Musmanf94c3182014-09-26 06:28:25 +00002003 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002004 if (VD->getType()->isReferenceType())
2005 RetTy = RetTy->getPointerElementType();
2006
2007 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002008 llvm::Function *Wrapper =
2009 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2010 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002011 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002012 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002013 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002014 return Wrapper;
2015}
2016
2017void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002018 CodeGenModule &CGM,
2019 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2020 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2021 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2022 llvm::Function *InitFunc = nullptr;
2023 if (!CXXThreadLocalInits.empty()) {
2024 // Generate a guarded initialization function.
2025 llvm::FunctionType *FTy =
2026 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2027 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002028 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002029 /*TLS=*/true);
2030 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2031 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2032 llvm::GlobalVariable::InternalLinkage,
2033 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2034 Guard->setThreadLocal(true);
2035 CodeGenFunction(CGM)
2036 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2037 }
2038 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
2039 const VarDecl *VD = CXXThreadLocals[I].first;
2040 llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002041
David Majnemer9b21c332014-07-11 20:28:10 +00002042 // Some targets require that all access to thread local variables go through
2043 // the thread wrapper. This means that we cannot attempt to create a thread
2044 // wrapper or a thread helper.
2045 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2046 continue;
2047
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002048 // Mangle the name for the thread_local initialization function.
2049 SmallString<256> InitFnName;
2050 {
2051 llvm::raw_svector_ostream Out(InitFnName);
2052 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
2053 Out.flush();
2054 }
2055
2056 // If we have a definition for the variable, emit the initialization
2057 // function as an alias to the global Init function (if any). Otherwise,
2058 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002059 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002060 bool InitIsInitFunc = false;
2061 if (VD->hasDefinition()) {
2062 InitIsInitFunc = true;
2063 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002064 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2065 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002066 } else {
2067 // Emit a weak global function referring to the initialization function.
2068 // This function will not exist if the TU defining the thread_local
2069 // variable in question does not need any dynamic initialization for
2070 // its thread_local variables.
2071 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2072 Init = llvm::Function::Create(
2073 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2074 &CGM.getModule());
2075 }
2076
2077 if (Init)
2078 Init->setVisibility(Var->getVisibility());
2079
2080 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2081 llvm::LLVMContext &Context = CGM.getModule().getContext();
2082 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2083 CGBuilderTy Builder(Entry);
2084 if (InitIsInitFunc) {
2085 if (Init)
2086 Builder.CreateCall(Init);
2087 } else {
2088 // Don't know whether we have an init function. Call it if it exists.
2089 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2090 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2091 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2092 Builder.CreateCondBr(Have, InitBB, ExitBB);
2093
2094 Builder.SetInsertPoint(InitBB);
2095 Builder.CreateCall(Init);
2096 Builder.CreateBr(ExitBB);
2097
2098 Builder.SetInsertPoint(ExitBB);
2099 }
2100
2101 // For a reference, the result of the wrapper function is a pointer to
2102 // the referenced object.
2103 llvm::Value *Val = Var;
2104 if (VD->getType()->isReferenceType()) {
2105 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2106 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2107 Val = LI;
2108 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002109 if (Val->getType() != Wrapper->getReturnType())
2110 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2111 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002112 Builder.CreateRet(Val);
2113 }
2114}
2115
Richard Smith0f383742014-03-26 22:48:22 +00002116LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2117 const VarDecl *VD,
2118 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002119 QualType T = VD->getType();
2120 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2121 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002122 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002123
2124 Val = CGF.Builder.CreateCall(Wrapper);
2125
2126 LValue LV;
2127 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002128 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002129 else
Richard Smith0f383742014-03-26 22:48:22 +00002130 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002131 // FIXME: need setObjCGCLValueClass?
2132 return LV;
2133}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002134
2135/// Return whether the given global decl needs a VTT parameter, which it does
2136/// if it's a base constructor or destructor with virtual bases.
2137bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2138 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2139
2140 // We don't have any virtual bases, just return early.
2141 if (!MD->getParent()->getNumVBases())
2142 return false;
2143
2144 // Check if we have a base constructor.
2145 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2146 return true;
2147
2148 // Check if we have a base destructor.
2149 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2150 return true;
2151
2152 return false;
2153}
David Majnemere2cb8d12014-07-07 06:20:47 +00002154
2155namespace {
2156class ItaniumRTTIBuilder {
2157 CodeGenModule &CGM; // Per-module state.
2158 llvm::LLVMContext &VMContext;
2159 const ItaniumCXXABI &CXXABI; // Per-module state.
2160
2161 /// Fields - The fields of the RTTI descriptor currently being built.
2162 SmallVector<llvm::Constant *, 16> Fields;
2163
2164 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2165 llvm::GlobalVariable *
2166 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2167
2168 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2169 /// descriptor of the given type.
2170 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2171
2172 /// BuildVTablePointer - Build the vtable pointer for the given type.
2173 void BuildVTablePointer(const Type *Ty);
2174
2175 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2176 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2177 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2178
2179 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2180 /// classes with bases that do not satisfy the abi::__si_class_type_info
2181 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2182 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2183
2184 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2185 /// for pointer types.
2186 void BuildPointerTypeInfo(QualType PointeeTy);
2187
2188 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2189 /// type_info for an object type.
2190 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2191
2192 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2193 /// struct, used for member pointer types.
2194 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2195
2196public:
2197 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2198 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2199
2200 // Pointer type info flags.
2201 enum {
2202 /// PTI_Const - Type has const qualifier.
2203 PTI_Const = 0x1,
2204
2205 /// PTI_Volatile - Type has volatile qualifier.
2206 PTI_Volatile = 0x2,
2207
2208 /// PTI_Restrict - Type has restrict qualifier.
2209 PTI_Restrict = 0x4,
2210
2211 /// PTI_Incomplete - Type is incomplete.
2212 PTI_Incomplete = 0x8,
2213
2214 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2215 /// (in pointer to member).
2216 PTI_ContainingClassIncomplete = 0x10
2217 };
2218
2219 // VMI type info flags.
2220 enum {
2221 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2222 VMI_NonDiamondRepeat = 0x1,
2223
2224 /// VMI_DiamondShaped - Class is diamond shaped.
2225 VMI_DiamondShaped = 0x2
2226 };
2227
2228 // Base class type info flags.
2229 enum {
2230 /// BCTI_Virtual - Base class is virtual.
2231 BCTI_Virtual = 0x1,
2232
2233 /// BCTI_Public - Base class is public.
2234 BCTI_Public = 0x2
2235 };
2236
2237 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2238 ///
2239 /// \param Force - true to force the creation of this RTTI value
2240 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2241};
2242}
2243
2244llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2245 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2246 SmallString<256> OutName;
2247 llvm::raw_svector_ostream Out(OutName);
2248 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2249 Out.flush();
2250 StringRef Name = OutName.str();
2251
2252 // We know that the mangled name of the type starts at index 4 of the
2253 // mangled name of the typename, so we can just index into it in order to
2254 // get the mangled name of the type.
2255 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2256 Name.substr(4));
2257
2258 llvm::GlobalVariable *GV =
2259 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2260
2261 GV->setInitializer(Init);
2262
2263 return GV;
2264}
2265
2266llvm::Constant *
2267ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2268 // Mangle the RTTI name.
2269 SmallString<256> OutName;
2270 llvm::raw_svector_ostream Out(OutName);
2271 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2272 Out.flush();
2273 StringRef Name = OutName.str();
2274
2275 // Look for an existing global.
2276 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2277
2278 if (!GV) {
2279 // Create a new global variable.
2280 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2281 /*Constant=*/true,
2282 llvm::GlobalValue::ExternalLinkage, nullptr,
2283 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002284 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2285 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2286 if (RD->hasAttr<DLLImportAttr>())
2287 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2288 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002289 }
2290
2291 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2292}
2293
2294/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2295/// info for that type is defined in the standard library.
2296static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2297 // Itanium C++ ABI 2.9.2:
2298 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2299 // the run-time support library. Specifically, the run-time support
2300 // library should contain type_info objects for the types X, X* and
2301 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2302 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2303 // long, unsigned long, long long, unsigned long long, float, double,
2304 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2305 // half-precision floating point types.
2306 switch (Ty->getKind()) {
2307 case BuiltinType::Void:
2308 case BuiltinType::NullPtr:
2309 case BuiltinType::Bool:
2310 case BuiltinType::WChar_S:
2311 case BuiltinType::WChar_U:
2312 case BuiltinType::Char_U:
2313 case BuiltinType::Char_S:
2314 case BuiltinType::UChar:
2315 case BuiltinType::SChar:
2316 case BuiltinType::Short:
2317 case BuiltinType::UShort:
2318 case BuiltinType::Int:
2319 case BuiltinType::UInt:
2320 case BuiltinType::Long:
2321 case BuiltinType::ULong:
2322 case BuiltinType::LongLong:
2323 case BuiltinType::ULongLong:
2324 case BuiltinType::Half:
2325 case BuiltinType::Float:
2326 case BuiltinType::Double:
2327 case BuiltinType::LongDouble:
2328 case BuiltinType::Char16:
2329 case BuiltinType::Char32:
2330 case BuiltinType::Int128:
2331 case BuiltinType::UInt128:
2332 case BuiltinType::OCLImage1d:
2333 case BuiltinType::OCLImage1dArray:
2334 case BuiltinType::OCLImage1dBuffer:
2335 case BuiltinType::OCLImage2d:
2336 case BuiltinType::OCLImage2dArray:
2337 case BuiltinType::OCLImage3d:
2338 case BuiltinType::OCLSampler:
2339 case BuiltinType::OCLEvent:
2340 return true;
2341
2342 case BuiltinType::Dependent:
2343#define BUILTIN_TYPE(Id, SingletonId)
2344#define PLACEHOLDER_TYPE(Id, SingletonId) \
2345 case BuiltinType::Id:
2346#include "clang/AST/BuiltinTypes.def"
2347 llvm_unreachable("asking for RRTI for a placeholder type!");
2348
2349 case BuiltinType::ObjCId:
2350 case BuiltinType::ObjCClass:
2351 case BuiltinType::ObjCSel:
2352 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2353 }
2354
2355 llvm_unreachable("Invalid BuiltinType Kind!");
2356}
2357
2358static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2359 QualType PointeeTy = PointerTy->getPointeeType();
2360 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2361 if (!BuiltinTy)
2362 return false;
2363
2364 // Check the qualifiers.
2365 Qualifiers Quals = PointeeTy.getQualifiers();
2366 Quals.removeConst();
2367
2368 if (!Quals.empty())
2369 return false;
2370
2371 return TypeInfoIsInStandardLibrary(BuiltinTy);
2372}
2373
2374/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2375/// information for the given type exists in the standard library.
2376static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2377 // Type info for builtin types is defined in the standard library.
2378 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2379 return TypeInfoIsInStandardLibrary(BuiltinTy);
2380
2381 // Type info for some pointer types to builtin types is defined in the
2382 // standard library.
2383 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2384 return TypeInfoIsInStandardLibrary(PointerTy);
2385
2386 return false;
2387}
2388
2389/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2390/// the given type exists somewhere else, and that we should not emit the type
2391/// information in this translation unit. Assumes that it is not a
2392/// standard-library type.
2393static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2394 QualType Ty) {
2395 ASTContext &Context = CGM.getContext();
2396
2397 // If RTTI is disabled, assume it might be disabled in the
2398 // translation unit that defines any potential key function, too.
2399 if (!Context.getLangOpts().RTTI) return false;
2400
2401 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2402 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2403 if (!RD->hasDefinition())
2404 return false;
2405
2406 if (!RD->isDynamicClass())
2407 return false;
2408
2409 // FIXME: this may need to be reconsidered if the key function
2410 // changes.
David Majnemer1fb1a042014-11-07 07:26:38 +00002411 if (CGM.getVTables().isVTableExternal(RD))
2412 return true;
2413
2414 if (RD->hasAttr<DLLImportAttr>())
2415 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002416 }
2417
2418 return false;
2419}
2420
2421/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2422static bool IsIncompleteClassType(const RecordType *RecordTy) {
2423 return !RecordTy->getDecl()->isCompleteDefinition();
2424}
2425
2426/// ContainsIncompleteClassType - Returns whether the given type contains an
2427/// incomplete class type. This is true if
2428///
2429/// * The given type is an incomplete class type.
2430/// * The given type is a pointer type whose pointee type contains an
2431/// incomplete class type.
2432/// * The given type is a member pointer type whose class is an incomplete
2433/// class type.
2434/// * The given type is a member pointer type whoise pointee type contains an
2435/// incomplete class type.
2436/// is an indirect or direct pointer to an incomplete class type.
2437static bool ContainsIncompleteClassType(QualType Ty) {
2438 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2439 if (IsIncompleteClassType(RecordTy))
2440 return true;
2441 }
2442
2443 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2444 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2445
2446 if (const MemberPointerType *MemberPointerTy =
2447 dyn_cast<MemberPointerType>(Ty)) {
2448 // Check if the class type is incomplete.
2449 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2450 if (IsIncompleteClassType(ClassType))
2451 return true;
2452
2453 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2454 }
2455
2456 return false;
2457}
2458
2459// CanUseSingleInheritance - Return whether the given record decl has a "single,
2460// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2461// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2462static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2463 // Check the number of bases.
2464 if (RD->getNumBases() != 1)
2465 return false;
2466
2467 // Get the base.
2468 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2469
2470 // Check that the base is not virtual.
2471 if (Base->isVirtual())
2472 return false;
2473
2474 // Check that the base is public.
2475 if (Base->getAccessSpecifier() != AS_public)
2476 return false;
2477
2478 // Check that the class is dynamic iff the base is.
2479 const CXXRecordDecl *BaseDecl =
2480 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2481 if (!BaseDecl->isEmpty() &&
2482 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2483 return false;
2484
2485 return true;
2486}
2487
2488void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2489 // abi::__class_type_info.
2490 static const char * const ClassTypeInfo =
2491 "_ZTVN10__cxxabiv117__class_type_infoE";
2492 // abi::__si_class_type_info.
2493 static const char * const SIClassTypeInfo =
2494 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2495 // abi::__vmi_class_type_info.
2496 static const char * const VMIClassTypeInfo =
2497 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2498
2499 const char *VTableName = nullptr;
2500
2501 switch (Ty->getTypeClass()) {
2502#define TYPE(Class, Base)
2503#define ABSTRACT_TYPE(Class, Base)
2504#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2505#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2506#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2507#include "clang/AST/TypeNodes.def"
2508 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2509
2510 case Type::LValueReference:
2511 case Type::RValueReference:
2512 llvm_unreachable("References shouldn't get here");
2513
2514 case Type::Auto:
2515 llvm_unreachable("Undeduced auto type shouldn't get here");
2516
2517 case Type::Builtin:
2518 // GCC treats vector and complex types as fundamental types.
2519 case Type::Vector:
2520 case Type::ExtVector:
2521 case Type::Complex:
2522 case Type::Atomic:
2523 // FIXME: GCC treats block pointers as fundamental types?!
2524 case Type::BlockPointer:
2525 // abi::__fundamental_type_info.
2526 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2527 break;
2528
2529 case Type::ConstantArray:
2530 case Type::IncompleteArray:
2531 case Type::VariableArray:
2532 // abi::__array_type_info.
2533 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2534 break;
2535
2536 case Type::FunctionNoProto:
2537 case Type::FunctionProto:
2538 // abi::__function_type_info.
2539 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2540 break;
2541
2542 case Type::Enum:
2543 // abi::__enum_type_info.
2544 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2545 break;
2546
2547 case Type::Record: {
2548 const CXXRecordDecl *RD =
2549 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2550
2551 if (!RD->hasDefinition() || !RD->getNumBases()) {
2552 VTableName = ClassTypeInfo;
2553 } else if (CanUseSingleInheritance(RD)) {
2554 VTableName = SIClassTypeInfo;
2555 } else {
2556 VTableName = VMIClassTypeInfo;
2557 }
2558
2559 break;
2560 }
2561
2562 case Type::ObjCObject:
2563 // Ignore protocol qualifiers.
2564 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2565
2566 // Handle id and Class.
2567 if (isa<BuiltinType>(Ty)) {
2568 VTableName = ClassTypeInfo;
2569 break;
2570 }
2571
2572 assert(isa<ObjCInterfaceType>(Ty));
2573 // Fall through.
2574
2575 case Type::ObjCInterface:
2576 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2577 VTableName = SIClassTypeInfo;
2578 } else {
2579 VTableName = ClassTypeInfo;
2580 }
2581 break;
2582
2583 case Type::ObjCObjectPointer:
2584 case Type::Pointer:
2585 // abi::__pointer_type_info.
2586 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2587 break;
2588
2589 case Type::MemberPointer:
2590 // abi::__pointer_to_member_type_info.
2591 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2592 break;
2593 }
2594
2595 llvm::Constant *VTable =
2596 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2597
2598 llvm::Type *PtrDiffTy =
2599 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2600
2601 // The vtable address point is 2.
2602 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2603 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2604 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2605
2606 Fields.push_back(VTable);
2607}
2608
2609/// \brief Return the linkage that the type info and type info name constants
2610/// should have for the given type.
2611static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2612 QualType Ty) {
2613 // Itanium C++ ABI 2.9.5p7:
2614 // In addition, it and all of the intermediate abi::__pointer_type_info
2615 // structs in the chain down to the abi::__class_type_info for the
2616 // incomplete class type must be prevented from resolving to the
2617 // corresponding type_info structs for the complete class type, possibly
2618 // by making them local static objects. Finally, a dummy class RTTI is
2619 // generated for the incomplete type that will not resolve to the final
2620 // complete class RTTI (because the latter need not exist), possibly by
2621 // making it a local static object.
2622 if (ContainsIncompleteClassType(Ty))
2623 return llvm::GlobalValue::InternalLinkage;
2624
2625 switch (Ty->getLinkage()) {
2626 case NoLinkage:
2627 case InternalLinkage:
2628 case UniqueExternalLinkage:
2629 return llvm::GlobalValue::InternalLinkage;
2630
2631 case VisibleNoLinkage:
2632 case ExternalLinkage:
2633 if (!CGM.getLangOpts().RTTI) {
2634 // RTTI is not enabled, which means that this type info struct is going
2635 // to be used for exception handling. Give it linkonce_odr linkage.
2636 return llvm::GlobalValue::LinkOnceODRLinkage;
2637 }
2638
2639 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2640 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2641 if (RD->hasAttr<WeakAttr>())
2642 return llvm::GlobalValue::WeakODRLinkage;
2643 if (RD->isDynamicClass())
2644 return CGM.getVTableLinkage(RD);
2645 }
2646
2647 return llvm::GlobalValue::LinkOnceODRLinkage;
2648 }
2649
2650 llvm_unreachable("Invalid linkage!");
2651}
2652
2653llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2654 // We want to operate on the canonical type.
2655 Ty = CGM.getContext().getCanonicalType(Ty);
2656
2657 // Check if we've already emitted an RTTI descriptor for this type.
2658 SmallString<256> OutName;
2659 llvm::raw_svector_ostream Out(OutName);
2660 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2661 Out.flush();
2662 StringRef Name = OutName.str();
2663
2664 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2665 if (OldGV && !OldGV->isDeclaration()) {
2666 assert(!OldGV->hasAvailableExternallyLinkage() &&
2667 "available_externally typeinfos not yet implemented");
2668
2669 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2670 }
2671
2672 // Check if there is already an external RTTI descriptor for this type.
2673 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2674 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2675 return GetAddrOfExternalRTTIDescriptor(Ty);
2676
2677 // Emit the standard library with external linkage.
2678 llvm::GlobalVariable::LinkageTypes Linkage;
2679 if (IsStdLib)
2680 Linkage = llvm::GlobalValue::ExternalLinkage;
2681 else
2682 Linkage = getTypeInfoLinkage(CGM, Ty);
2683
2684 // Add the vtable pointer.
2685 BuildVTablePointer(cast<Type>(Ty));
2686
2687 // And the name.
2688 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2689 llvm::Constant *TypeNameField;
2690
2691 // If we're supposed to demote the visibility, be sure to set a flag
2692 // to use a string comparison for type_info comparisons.
2693 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2694 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2695 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2696 // The flag is the sign bit, which on ARM64 is defined to be clear
2697 // for global pointers. This is very ARM64-specific.
2698 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2699 llvm::Constant *flag =
2700 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2701 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2702 TypeNameField =
2703 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2704 } else {
2705 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2706 }
2707 Fields.push_back(TypeNameField);
2708
2709 switch (Ty->getTypeClass()) {
2710#define TYPE(Class, Base)
2711#define ABSTRACT_TYPE(Class, Base)
2712#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2713#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2714#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2715#include "clang/AST/TypeNodes.def"
2716 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2717
2718 // GCC treats vector types as fundamental types.
2719 case Type::Builtin:
2720 case Type::Vector:
2721 case Type::ExtVector:
2722 case Type::Complex:
2723 case Type::BlockPointer:
2724 // Itanium C++ ABI 2.9.5p4:
2725 // abi::__fundamental_type_info adds no data members to std::type_info.
2726 break;
2727
2728 case Type::LValueReference:
2729 case Type::RValueReference:
2730 llvm_unreachable("References shouldn't get here");
2731
2732 case Type::Auto:
2733 llvm_unreachable("Undeduced auto type shouldn't get here");
2734
2735 case Type::ConstantArray:
2736 case Type::IncompleteArray:
2737 case Type::VariableArray:
2738 // Itanium C++ ABI 2.9.5p5:
2739 // abi::__array_type_info adds no data members to std::type_info.
2740 break;
2741
2742 case Type::FunctionNoProto:
2743 case Type::FunctionProto:
2744 // Itanium C++ ABI 2.9.5p5:
2745 // abi::__function_type_info adds no data members to std::type_info.
2746 break;
2747
2748 case Type::Enum:
2749 // Itanium C++ ABI 2.9.5p5:
2750 // abi::__enum_type_info adds no data members to std::type_info.
2751 break;
2752
2753 case Type::Record: {
2754 const CXXRecordDecl *RD =
2755 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2756 if (!RD->hasDefinition() || !RD->getNumBases()) {
2757 // We don't need to emit any fields.
2758 break;
2759 }
2760
2761 if (CanUseSingleInheritance(RD))
2762 BuildSIClassTypeInfo(RD);
2763 else
2764 BuildVMIClassTypeInfo(RD);
2765
2766 break;
2767 }
2768
2769 case Type::ObjCObject:
2770 case Type::ObjCInterface:
2771 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2772 break;
2773
2774 case Type::ObjCObjectPointer:
2775 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2776 break;
2777
2778 case Type::Pointer:
2779 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2780 break;
2781
2782 case Type::MemberPointer:
2783 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2784 break;
2785
2786 case Type::Atomic:
2787 // No fields, at least for the moment.
2788 break;
2789 }
2790
2791 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2792
Rafael Espindolacb92c192015-01-15 23:18:01 +00002793 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002794 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002795 new llvm::GlobalVariable(M, Init->getType(),
2796 /*Constant=*/true, Linkage, Init, Name);
2797
2798 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2799 GV->setComdat(M.getOrInsertComdat(GV->getName()));
David Majnemere2cb8d12014-07-07 06:20:47 +00002800
2801 // If there's already an old global variable, replace it with the new one.
2802 if (OldGV) {
2803 GV->takeName(OldGV);
2804 llvm::Constant *NewPtr =
2805 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2806 OldGV->replaceAllUsesWith(NewPtr);
2807 OldGV->eraseFromParent();
2808 }
2809
2810 // The Itanium ABI specifies that type_info objects must be globally
2811 // unique, with one exception: if the type is an incomplete class
2812 // type or a (possibly indirect) pointer to one. That exception
2813 // affects the general case of comparing type_info objects produced
2814 // by the typeid operator, which is why the comparison operators on
2815 // std::type_info generally use the type_info name pointers instead
2816 // of the object addresses. However, the language's built-in uses
2817 // of RTTI generally require class types to be complete, even when
2818 // manipulating pointers to those class types. This allows the
2819 // implementation of dynamic_cast to rely on address equality tests,
2820 // which is much faster.
2821
2822 // All of this is to say that it's important that both the type_info
2823 // object and the type_info name be uniqued when weakly emitted.
2824
2825 // Give the type_info object and name the formal visibility of the
2826 // type itself.
2827 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2828 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2829 // If the linkage is local, only default visibility makes sense.
2830 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2831 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2832 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2833 else
2834 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2835 TypeName->setVisibility(llvmVisibility);
2836 GV->setVisibility(llvmVisibility);
2837
2838 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2839}
2840
2841/// ComputeQualifierFlags - Compute the pointer type info flags from the
2842/// given qualifier.
2843static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2844 unsigned Flags = 0;
2845
2846 if (Quals.hasConst())
2847 Flags |= ItaniumRTTIBuilder::PTI_Const;
2848 if (Quals.hasVolatile())
2849 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2850 if (Quals.hasRestrict())
2851 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2852
2853 return Flags;
2854}
2855
2856/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2857/// for the given Objective-C object type.
2858void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2859 // Drop qualifiers.
2860 const Type *T = OT->getBaseType().getTypePtr();
2861 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2862
2863 // The builtin types are abi::__class_type_infos and don't require
2864 // extra fields.
2865 if (isa<BuiltinType>(T)) return;
2866
2867 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2868 ObjCInterfaceDecl *Super = Class->getSuperClass();
2869
2870 // Root classes are also __class_type_info.
2871 if (!Super) return;
2872
2873 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2874
2875 // Everything else is single inheritance.
2876 llvm::Constant *BaseTypeInfo =
2877 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2878 Fields.push_back(BaseTypeInfo);
2879}
2880
2881/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2882/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2883void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2884 // Itanium C++ ABI 2.9.5p6b:
2885 // It adds to abi::__class_type_info a single member pointing to the
2886 // type_info structure for the base type,
2887 llvm::Constant *BaseTypeInfo =
2888 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2889 Fields.push_back(BaseTypeInfo);
2890}
2891
2892namespace {
2893 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2894 /// a class hierarchy.
2895 struct SeenBases {
2896 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2897 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2898 };
2899}
2900
2901/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2902/// abi::__vmi_class_type_info.
2903///
2904static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2905 SeenBases &Bases) {
2906
2907 unsigned Flags = 0;
2908
2909 const CXXRecordDecl *BaseDecl =
2910 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2911
2912 if (Base->isVirtual()) {
2913 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002914 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002915 // If this virtual base has been seen before, then the class is diamond
2916 // shaped.
2917 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2918 } else {
2919 if (Bases.NonVirtualBases.count(BaseDecl))
2920 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2921 }
2922 } else {
2923 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002924 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002925 // If this non-virtual base has been seen before, then the class has non-
2926 // diamond shaped repeated inheritance.
2927 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2928 } else {
2929 if (Bases.VirtualBases.count(BaseDecl))
2930 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2931 }
2932 }
2933
2934 // Walk all bases.
2935 for (const auto &I : BaseDecl->bases())
2936 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2937
2938 return Flags;
2939}
2940
2941static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2942 unsigned Flags = 0;
2943 SeenBases Bases;
2944
2945 // Walk all bases.
2946 for (const auto &I : RD->bases())
2947 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2948
2949 return Flags;
2950}
2951
2952/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2953/// classes with bases that do not satisfy the abi::__si_class_type_info
2954/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2955void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2956 llvm::Type *UnsignedIntLTy =
2957 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2958
2959 // Itanium C++ ABI 2.9.5p6c:
2960 // __flags is a word with flags describing details about the class
2961 // structure, which may be referenced by using the __flags_masks
2962 // enumeration. These flags refer to both direct and indirect bases.
2963 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2964 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2965
2966 // Itanium C++ ABI 2.9.5p6c:
2967 // __base_count is a word with the number of direct proper base class
2968 // descriptions that follow.
2969 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2970
2971 if (!RD->getNumBases())
2972 return;
2973
2974 llvm::Type *LongLTy =
2975 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2976
2977 // Now add the base class descriptions.
2978
2979 // Itanium C++ ABI 2.9.5p6c:
2980 // __base_info[] is an array of base class descriptions -- one for every
2981 // direct proper base. Each description is of the type:
2982 //
2983 // struct abi::__base_class_type_info {
2984 // public:
2985 // const __class_type_info *__base_type;
2986 // long __offset_flags;
2987 //
2988 // enum __offset_flags_masks {
2989 // __virtual_mask = 0x1,
2990 // __public_mask = 0x2,
2991 // __offset_shift = 8
2992 // };
2993 // };
2994 for (const auto &Base : RD->bases()) {
2995 // The __base_type member points to the RTTI for the base type.
2996 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2997
2998 const CXXRecordDecl *BaseDecl =
2999 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3000
3001 int64_t OffsetFlags = 0;
3002
3003 // All but the lower 8 bits of __offset_flags are a signed offset.
3004 // For a non-virtual base, this is the offset in the object of the base
3005 // subobject. For a virtual base, this is the offset in the virtual table of
3006 // the virtual base offset for the virtual base referenced (negative).
3007 CharUnits Offset;
3008 if (Base.isVirtual())
3009 Offset =
3010 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3011 else {
3012 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3013 Offset = Layout.getBaseClassOffset(BaseDecl);
3014 };
3015
3016 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3017
3018 // The low-order byte of __offset_flags contains flags, as given by the
3019 // masks from the enumeration __offset_flags_masks.
3020 if (Base.isVirtual())
3021 OffsetFlags |= BCTI_Virtual;
3022 if (Base.getAccessSpecifier() == AS_public)
3023 OffsetFlags |= BCTI_Public;
3024
3025 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3026 }
3027}
3028
3029/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3030/// used for pointer types.
3031void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3032 Qualifiers Quals;
3033 QualType UnqualifiedPointeeTy =
3034 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3035
3036 // Itanium C++ ABI 2.9.5p7:
3037 // __flags is a flag word describing the cv-qualification and other
3038 // attributes of the type pointed to
3039 unsigned Flags = ComputeQualifierFlags(Quals);
3040
3041 // Itanium C++ ABI 2.9.5p7:
3042 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3043 // incomplete class type, the incomplete target type flag is set.
3044 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3045 Flags |= PTI_Incomplete;
3046
3047 llvm::Type *UnsignedIntLTy =
3048 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3049 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3050
3051 // Itanium C++ ABI 2.9.5p7:
3052 // __pointee is a pointer to the std::type_info derivation for the
3053 // unqualified type being pointed to.
3054 llvm::Constant *PointeeTypeInfo =
3055 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3056 Fields.push_back(PointeeTypeInfo);
3057}
3058
3059/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3060/// struct, used for member pointer types.
3061void
3062ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3063 QualType PointeeTy = Ty->getPointeeType();
3064
3065 Qualifiers Quals;
3066 QualType UnqualifiedPointeeTy =
3067 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3068
3069 // Itanium C++ ABI 2.9.5p7:
3070 // __flags is a flag word describing the cv-qualification and other
3071 // attributes of the type pointed to.
3072 unsigned Flags = ComputeQualifierFlags(Quals);
3073
3074 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3075
3076 // Itanium C++ ABI 2.9.5p7:
3077 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3078 // incomplete class type, the incomplete target type flag is set.
3079 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3080 Flags |= PTI_Incomplete;
3081
3082 if (IsIncompleteClassType(ClassType))
3083 Flags |= PTI_ContainingClassIncomplete;
3084
3085 llvm::Type *UnsignedIntLTy =
3086 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3087 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3088
3089 // Itanium C++ ABI 2.9.5p7:
3090 // __pointee is a pointer to the std::type_info derivation for the
3091 // unqualified type being pointed to.
3092 llvm::Constant *PointeeTypeInfo =
3093 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3094 Fields.push_back(PointeeTypeInfo);
3095
3096 // Itanium C++ ABI 2.9.5p9:
3097 // __context is a pointer to an abi::__class_type_info corresponding to the
3098 // class type containing the member pointed to
3099 // (e.g., the "A" in "int A::*").
3100 Fields.push_back(
3101 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3102}
3103
David Majnemerad803d42015-03-15 07:10:01 +00003104llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty,
3105 bool ForEH) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003106 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3107}
3108
3109void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3110 QualType PointerType = getContext().getPointerType(Type);
3111 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3112 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3113 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3114 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3115}
3116
3117void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3118 QualType FundamentalTypes[] = {
3119 getContext().VoidTy, getContext().NullPtrTy,
3120 getContext().BoolTy, getContext().WCharTy,
3121 getContext().CharTy, getContext().UnsignedCharTy,
3122 getContext().SignedCharTy, getContext().ShortTy,
3123 getContext().UnsignedShortTy, getContext().IntTy,
3124 getContext().UnsignedIntTy, getContext().LongTy,
3125 getContext().UnsignedLongTy, getContext().LongLongTy,
3126 getContext().UnsignedLongLongTy, getContext().HalfTy,
3127 getContext().FloatTy, getContext().DoubleTy,
3128 getContext().LongDoubleTy, getContext().Char16Ty,
3129 getContext().Char32Ty,
3130 };
3131 for (const QualType &FundamentalType : FundamentalTypes)
3132 EmitFundamentalRTTIDescriptor(FundamentalType);
3133}
3134
3135/// What sort of uniqueness rules should we use for the RTTI for the
3136/// given type?
3137ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3138 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3139 if (shouldRTTIBeUnique())
3140 return RUK_Unique;
3141
3142 // It's only necessary for linkonce_odr or weak_odr linkage.
3143 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3144 Linkage != llvm::GlobalValue::WeakODRLinkage)
3145 return RUK_Unique;
3146
3147 // It's only necessary with default visibility.
3148 if (CanTy->getVisibility() != DefaultVisibility)
3149 return RUK_Unique;
3150
3151 // If we're not required to publish this symbol, hide it.
3152 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3153 return RUK_NonUniqueHidden;
3154
3155 // If we're required to publish this symbol, as we might be under an
3156 // explicit instantiation, leave it with default visibility but
3157 // enable string-comparisons.
3158 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3159 return RUK_NonUniqueVisible;
3160}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003161
Rafael Espindola1e4df922014-09-16 15:18:21 +00003162// Find out how to codegen the complete destructor and constructor
3163namespace {
3164enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3165}
3166static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3167 const CXXMethodDecl *MD) {
3168 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3169 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003170
Rafael Espindola1e4df922014-09-16 15:18:21 +00003171 // The complete and base structors are not equivalent if there are any virtual
3172 // bases, so emit separate functions.
3173 if (MD->getParent()->getNumVBases())
3174 return StructorCodegen::Emit;
3175
3176 GlobalDecl AliasDecl;
3177 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3178 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3179 } else {
3180 const auto *CD = cast<CXXConstructorDecl>(MD);
3181 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3182 }
3183 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3184
3185 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3186 return StructorCodegen::RAUW;
3187
3188 // FIXME: Should we allow available_externally aliases?
3189 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3190 return StructorCodegen::RAUW;
3191
Rafael Espindola0806f982014-09-16 20:19:43 +00003192 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3193 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3194 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3195 return StructorCodegen::COMDAT;
3196 return StructorCodegen::Emit;
3197 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003198
3199 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003200}
3201
Rafael Espindola1e4df922014-09-16 15:18:21 +00003202static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3203 GlobalDecl AliasDecl,
3204 GlobalDecl TargetDecl) {
3205 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3206
3207 StringRef MangledName = CGM.getMangledName(AliasDecl);
3208 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3209 if (Entry && !Entry->isDeclaration())
3210 return;
3211
3212 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3213 llvm::PointerType *AliasType = Aliasee->getType();
3214
3215 // Create the alias with no name.
3216 auto *Alias = llvm::GlobalAlias::create(
3217 AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule());
3218
3219 // Switch any previous uses to the alias.
3220 if (Entry) {
3221 assert(Entry->getType() == AliasType &&
3222 "declaration exists with different type");
3223 Alias->takeName(Entry);
3224 Entry->replaceAllUsesWith(Alias);
3225 Entry->eraseFromParent();
3226 } else {
3227 Alias->setName(MangledName);
3228 }
3229
3230 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003231 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003232}
3233
3234void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3235 StructorType Type) {
3236 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3237 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3238
3239 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3240
3241 if (Type == StructorType::Complete) {
3242 GlobalDecl CompleteDecl;
3243 GlobalDecl BaseDecl;
3244 if (CD) {
3245 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3246 BaseDecl = GlobalDecl(CD, Ctor_Base);
3247 } else {
3248 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3249 BaseDecl = GlobalDecl(DD, Dtor_Base);
3250 }
3251
3252 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3253 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3254 return;
3255 }
3256
3257 if (CGType == StructorCodegen::RAUW) {
3258 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3259 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3260 CGM.addReplacement(MangledName, Aliasee);
3261 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003262 }
3263 }
3264
3265 // The base destructor is equivalent to the base destructor of its
3266 // base class if there is exactly one non-virtual base class with a
3267 // non-trivial destructor, there are no fields with a non-trivial
3268 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003269 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3270 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003271 return;
3272
Rafael Espindola1e4df922014-09-16 15:18:21 +00003273 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003274
Rafael Espindola1e4df922014-09-16 15:18:21 +00003275 if (CGType == StructorCodegen::COMDAT) {
3276 SmallString<256> Buffer;
3277 llvm::raw_svector_ostream Out(Buffer);
3278 if (DD)
3279 getMangleContext().mangleCXXDtorComdat(DD, Out);
3280 else
3281 getMangleContext().mangleCXXCtorComdat(CD, Out);
3282 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3283 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003284 } else {
3285 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003286 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003287}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003288
3289static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3290 // void *__cxa_begin_catch(void*);
3291 llvm::FunctionType *FTy = llvm::FunctionType::get(
3292 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3293
3294 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3295}
3296
3297static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3298 // void __cxa_end_catch();
3299 llvm::FunctionType *FTy =
3300 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3301
3302 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3303}
3304
3305static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3306 // void *__cxa_get_exception_ptr(void*);
3307 llvm::FunctionType *FTy = llvm::FunctionType::get(
3308 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3309
3310 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3311}
3312
3313namespace {
3314 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3315 /// exception type lets us state definitively that the thrown exception
3316 /// type does not have a destructor. In particular:
3317 /// - Catch-alls tell us nothing, so we have to conservatively
3318 /// assume that the thrown exception might have a destructor.
3319 /// - Catches by reference behave according to their base types.
3320 /// - Catches of non-record types will only trigger for exceptions
3321 /// of non-record types, which never have destructors.
3322 /// - Catches of record types can trigger for arbitrary subclasses
3323 /// of the caught type, so we have to assume the actual thrown
3324 /// exception type might have a throwing destructor, even if the
3325 /// caught type's destructor is trivial or nothrow.
3326 struct CallEndCatch : EHScopeStack::Cleanup {
3327 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3328 bool MightThrow;
3329
3330 void Emit(CodeGenFunction &CGF, Flags flags) override {
3331 if (!MightThrow) {
3332 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3333 return;
3334 }
3335
3336 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3337 }
3338 };
3339}
3340
3341/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3342/// __cxa_end_catch.
3343///
3344/// \param EndMightThrow - true if __cxa_end_catch might throw
3345static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3346 llvm::Value *Exn,
3347 bool EndMightThrow) {
3348 llvm::CallInst *call =
3349 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3350
3351 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3352
3353 return call;
3354}
3355
3356/// A "special initializer" callback for initializing a catch
3357/// parameter during catch initialization.
3358static void InitCatchParam(CodeGenFunction &CGF,
3359 const VarDecl &CatchParam,
3360 llvm::Value *ParamAddr,
3361 SourceLocation Loc) {
3362 // Load the exception from where the landing pad saved it.
3363 llvm::Value *Exn = CGF.getExceptionFromSlot();
3364
3365 CanQualType CatchType =
3366 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3367 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3368
3369 // If we're catching by reference, we can just cast the object
3370 // pointer to the appropriate pointer.
3371 if (isa<ReferenceType>(CatchType)) {
3372 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3373 bool EndCatchMightThrow = CaughtType->isRecordType();
3374
3375 // __cxa_begin_catch returns the adjusted object pointer.
3376 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3377
3378 // We have no way to tell the personality function that we're
3379 // catching by reference, so if we're catching a pointer,
3380 // __cxa_begin_catch will actually return that pointer by value.
3381 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3382 QualType PointeeType = PT->getPointeeType();
3383
3384 // When catching by reference, generally we should just ignore
3385 // this by-value pointer and use the exception object instead.
3386 if (!PointeeType->isRecordType()) {
3387
3388 // Exn points to the struct _Unwind_Exception header, which
3389 // we have to skip past in order to reach the exception data.
3390 unsigned HeaderSize =
3391 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3392 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3393
3394 // However, if we're catching a pointer-to-record type that won't
3395 // work, because the personality function might have adjusted
3396 // the pointer. There's actually no way for us to fully satisfy
3397 // the language/ABI contract here: we can't use Exn because it
3398 // might have the wrong adjustment, but we can't use the by-value
3399 // pointer because it's off by a level of abstraction.
3400 //
3401 // The current solution is to dump the adjusted pointer into an
3402 // alloca, which breaks language semantics (because changing the
3403 // pointer doesn't change the exception) but at least works.
3404 // The better solution would be to filter out non-exact matches
3405 // and rethrow them, but this is tricky because the rethrow
3406 // really needs to be catchable by other sites at this landing
3407 // pad. The best solution is to fix the personality function.
3408 } else {
3409 // Pull the pointer for the reference type off.
3410 llvm::Type *PtrTy =
3411 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3412
3413 // Create the temporary and write the adjusted pointer into it.
3414 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3415 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3416 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3417
3418 // Bind the reference to the temporary.
3419 AdjustedExn = ExnPtrTmp;
3420 }
3421 }
3422
3423 llvm::Value *ExnCast =
3424 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3425 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3426 return;
3427 }
3428
3429 // Scalars and complexes.
3430 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3431 if (TEK != TEK_Aggregate) {
3432 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3433
3434 // If the catch type is a pointer type, __cxa_begin_catch returns
3435 // the pointer by value.
3436 if (CatchType->hasPointerRepresentation()) {
3437 llvm::Value *CastExn =
3438 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3439
3440 switch (CatchType.getQualifiers().getObjCLifetime()) {
3441 case Qualifiers::OCL_Strong:
3442 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3443 // fallthrough
3444
3445 case Qualifiers::OCL_None:
3446 case Qualifiers::OCL_ExplicitNone:
3447 case Qualifiers::OCL_Autoreleasing:
3448 CGF.Builder.CreateStore(CastExn, ParamAddr);
3449 return;
3450
3451 case Qualifiers::OCL_Weak:
3452 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3453 return;
3454 }
3455 llvm_unreachable("bad ownership qualifier!");
3456 }
3457
3458 // Otherwise, it returns a pointer into the exception object.
3459
3460 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3461 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3462
3463 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3464 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3465 CGF.getContext().getDeclAlign(&CatchParam));
3466 switch (TEK) {
3467 case TEK_Complex:
3468 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3469 /*init*/ true);
3470 return;
3471 case TEK_Scalar: {
3472 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3473 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3474 return;
3475 }
3476 case TEK_Aggregate:
3477 llvm_unreachable("evaluation kind filtered out!");
3478 }
3479 llvm_unreachable("bad evaluation kind");
3480 }
3481
3482 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3483
3484 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3485
3486 // Check for a copy expression. If we don't have a copy expression,
3487 // that means a trivial copy is okay.
3488 const Expr *copyExpr = CatchParam.getInit();
3489 if (!copyExpr) {
3490 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3491 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3492 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3493 return;
3494 }
3495
3496 // We have to call __cxa_get_exception_ptr to get the adjusted
3497 // pointer before copying.
3498 llvm::CallInst *rawAdjustedExn =
3499 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3500
3501 // Cast that to the appropriate type.
3502 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3503
3504 // The copy expression is defined in terms of an OpaqueValueExpr.
3505 // Find it and map it to the adjusted expression.
3506 CodeGenFunction::OpaqueValueMapping
3507 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3508 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3509
3510 // Call the copy ctor in a terminate scope.
3511 CGF.EHStack.pushTerminate();
3512
3513 // Perform the copy construction.
3514 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3515 CGF.EmitAggExpr(copyExpr,
3516 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3517 AggValueSlot::IsNotDestructed,
3518 AggValueSlot::DoesNotNeedGCBarriers,
3519 AggValueSlot::IsNotAliased));
3520
3521 // Leave the terminate scope.
3522 CGF.EHStack.popTerminate();
3523
3524 // Undo the opaque value mapping.
3525 opaque.pop();
3526
3527 // Finally we can call __cxa_begin_catch.
3528 CallBeginCatch(CGF, Exn, true);
3529}
3530
3531/// Begins a catch statement by initializing the catch variable and
3532/// calling __cxa_begin_catch.
3533void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3534 const CXXCatchStmt *S) {
3535 // We have to be very careful with the ordering of cleanups here:
3536 // C++ [except.throw]p4:
3537 // The destruction [of the exception temporary] occurs
3538 // immediately after the destruction of the object declared in
3539 // the exception-declaration in the handler.
3540 //
3541 // So the precise ordering is:
3542 // 1. Construct catch variable.
3543 // 2. __cxa_begin_catch
3544 // 3. Enter __cxa_end_catch cleanup
3545 // 4. Enter dtor cleanup
3546 //
3547 // We do this by using a slightly abnormal initialization process.
3548 // Delegation sequence:
3549 // - ExitCXXTryStmt opens a RunCleanupsScope
3550 // - EmitAutoVarAlloca creates the variable and debug info
3551 // - InitCatchParam initializes the variable from the exception
3552 // - CallBeginCatch calls __cxa_begin_catch
3553 // - CallBeginCatch enters the __cxa_end_catch cleanup
3554 // - EmitAutoVarCleanups enters the variable destructor cleanup
3555 // - EmitCXXTryStmt emits the code for the catch body
3556 // - EmitCXXTryStmt close the RunCleanupsScope
3557
3558 VarDecl *CatchParam = S->getExceptionDecl();
3559 if (!CatchParam) {
3560 llvm::Value *Exn = CGF.getExceptionFromSlot();
3561 CallBeginCatch(CGF, Exn, true);
3562 return;
3563 }
3564
3565 // Emit the local.
3566 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3567 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3568 CGF.EmitAutoVarCleanups(var);
3569}
3570
3571/// Get or define the following function:
3572/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3573/// This code is used only in C++.
3574static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3575 llvm::FunctionType *fnTy =
3576 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3577 llvm::Constant *fnRef =
3578 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3579
3580 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3581 if (fn && fn->empty()) {
3582 fn->setDoesNotThrow();
3583 fn->setDoesNotReturn();
3584
3585 // What we really want is to massively penalize inlining without
3586 // forbidding it completely. The difference between that and
3587 // 'noinline' is negligible.
3588 fn->addFnAttr(llvm::Attribute::NoInline);
3589
3590 // Allow this function to be shared across translation units, but
3591 // we don't want it to turn into an exported symbol.
3592 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3593 fn->setVisibility(llvm::Function::HiddenVisibility);
3594 if (CGM.supportsCOMDAT())
3595 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
3596
3597 // Set up the function.
3598 llvm::BasicBlock *entry =
3599 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3600 CGBuilderTy builder(entry);
3601
3602 // Pull the exception pointer out of the parameter list.
3603 llvm::Value *exn = &*fn->arg_begin();
3604
3605 // Call __cxa_begin_catch(exn).
3606 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3607 catchCall->setDoesNotThrow();
3608 catchCall->setCallingConv(CGM.getRuntimeCC());
3609
3610 // Call std::terminate().
3611 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
3612 termCall->setDoesNotThrow();
3613 termCall->setDoesNotReturn();
3614 termCall->setCallingConv(CGM.getRuntimeCC());
3615
3616 // std::terminate cannot return.
3617 builder.CreateUnreachable();
3618 }
3619
3620 return fnRef;
3621}
3622
3623llvm::CallInst *
3624ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3625 llvm::Value *Exn) {
3626 // In C++, we want to call __cxa_begin_catch() before terminating.
3627 if (Exn) {
3628 assert(CGF.CGM.getLangOpts().CPlusPlus);
3629 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3630 }
3631 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3632}