blob: 31a1e488bc5823a171ab96566d4d4e3f2ef1b687 [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
David Majnemere2be95b2015-06-23 07:31:01 +000097 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +000098 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +000099 CharUnits offset) override;
100 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000101 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
102 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000103
John McCall7a9aac22010-08-23 01:21:21 +0000104 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000105 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000106 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000107 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000108
John McCall7a9aac22010-08-23 01:21:21 +0000109 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000110 llvm::Value *Addr,
111 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000112
David Majnemer08681372014-11-01 07:37:17 +0000113 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000114 llvm::Value *Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000115 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000116
David Majnemer442d0a22014-11-25 07:20:20 +0000117 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000118 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000119
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000120 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
121
122 llvm::CallInst *
123 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
124 llvm::Value *Exn) override;
125
David Majnemere2cb8d12014-07-07 06:20:47 +0000126 void EmitFundamentalRTTIDescriptor(QualType Type);
127 void EmitFundamentalRTTIDescriptors();
David Majnemer443250f2015-03-17 20:35:00 +0000128 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Justin Bogner0729afa2015-03-17 22:31:34 +0000129 llvm::Constant *
David Majnemer37b417f2015-03-29 21:55:10 +0000130 getAddrOfCXXCatchHandlerType(QualType Ty,
131 QualType CatchHandlerType) override {
David Majnemer443250f2015-03-17 20:35:00 +0000132 return getAddrOfRTTIDescriptor(Ty);
133 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000134
David Majnemer1162d252014-06-22 19:05:33 +0000135 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
136 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
137 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
138 llvm::Value *ThisPtr,
139 llvm::Type *StdTypeInfoPtrTy) override;
140
141 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
142 QualType SrcRecordTy) override;
143
144 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
145 QualType SrcRecordTy, QualType DestTy,
146 QualType DestRecordTy,
147 llvm::BasicBlock *CastEnd) override;
148
149 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
150 QualType SrcRecordTy,
151 QualType DestTy) override;
152
153 bool EmitBadCastCall(CodeGenFunction &CGF) override;
154
Craig Topper4f12f102014-03-12 06:41:41 +0000155 llvm::Value *
156 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
157 const CXXRecordDecl *ClassDecl,
158 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000159
Craig Topper4f12f102014-03-12 06:41:41 +0000160 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000161
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000162 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
163 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000164
Reid Klecknere7de47e2013-07-22 13:51:44 +0000165 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000166 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000167 // Itanium does not emit any destructor variant as an inline thunk.
168 // Delegating may occur as an optimization, but all variants are either
169 // emitted with external linkage or as linkonce if they are inline and used.
170 return false;
171 }
172
Craig Topper4f12f102014-03-12 06:41:41 +0000173 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000174
Reid Kleckner89077a12013-12-17 19:46:40 +0000175 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000176 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000177
Craig Topper4f12f102014-03-12 06:41:41 +0000178 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000179
Reid Kleckner89077a12013-12-17 19:46:40 +0000180 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
181 const CXXConstructorDecl *D,
182 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000183 bool Delegating,
184 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000185
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000186 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
187 CXXDtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000188 bool Delegating, llvm::Value *This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000189
Craig Topper4f12f102014-03-12 06:41:41 +0000190 void emitVTableDefinitions(CodeGenVTables &CGVT,
191 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000192
Piotr Padlewski525f7462015-08-27 21:35:37 +0000193 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
194 CodeGenFunction::VPtr Vptr) override;
195
196 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
197 return true;
198 }
199
200 llvm::Constant *
201 getVTableAddressPoint(BaseSubobject Base,
202 const CXXRecordDecl *VTableClass) override;
203
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000204 llvm::Value *getVTableAddressPointInStructor(
205 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewski525f7462015-08-27 21:35:37 +0000206 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
207
208 llvm::Value *getVTableAddressPointInStructorWithVTT(
209 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
210 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000211
212 llvm::Constant *
213 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000214 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000215
216 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000217 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000218
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000219 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Craig Topper4f12f102014-03-12 06:41:41 +0000220 llvm::Value *This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000221 llvm::Type *Ty,
222 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000223
David Majnemer0c0b6d92014-10-31 20:09:12 +0000224 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
225 const CXXDestructorDecl *Dtor,
226 CXXDtorType DtorType,
227 llvm::Value *This,
228 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000229
Craig Topper4f12f102014-03-12 06:41:41 +0000230 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000231
Piotr Padlewski81461a42015-08-27 21:35:41 +0000232 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000233
Hans Wennborgc94391d2014-06-06 20:04:01 +0000234 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
235 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000236 // Allow inlining of thunks by emitting them with available_externally
237 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000238 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000239 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
240 }
241
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000242 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
Craig Topper4f12f102014-03-12 06:41:41 +0000243 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000244
245 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000246 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000247
David Majnemer196ac332014-09-11 23:05:02 +0000248 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
249 FunctionArgList &Args) const override {
250 assert(!Args.empty() && "expected the arglist to not be empty!");
251 return Args.size() - 1;
252 }
253
Craig Topper4f12f102014-03-12 06:41:41 +0000254 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
255 StringRef GetDeletedVirtualCallName() override
256 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000257
Craig Topper4f12f102014-03-12 06:41:41 +0000258 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000259 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
260 llvm::Value *NewPtr,
261 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000262 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000263 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000264 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
265 llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000266 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000267
John McCallcdf7ef52010-11-06 09:44:32 +0000268 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000269 llvm::GlobalVariable *DeclPtr,
270 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000271 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000272 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000273
274 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000275 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000276 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000277 CodeGenModule &CGM,
278 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
279 CXXThreadLocals,
280 ArrayRef<llvm::Function *> CXXThreadLocalInits,
281 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
282
283 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000284 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
285 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000286
Craig Topper4f12f102014-03-12 06:41:41 +0000287 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000288
289 /**************************** RTTI Uniqueness ******************************/
290
291protected:
292 /// Returns true if the ABI requires RTTI type_info objects to be unique
293 /// across a program.
294 virtual bool shouldRTTIBeUnique() const { return true; }
295
296public:
297 /// What sort of unique-RTTI behavior should we use?
298 enum RTTIUniquenessKind {
299 /// We are guaranteeing, or need to guarantee, that the RTTI string
300 /// is unique.
301 RUK_Unique,
302
303 /// We are not guaranteeing uniqueness for the RTTI string, so we
304 /// can demote to hidden visibility but must use string comparisons.
305 RUK_NonUniqueHidden,
306
307 /// We are not guaranteeing uniqueness for the RTTI string, so we
308 /// have to use string comparisons, but we also have to emit it with
309 /// non-hidden visibility.
310 RUK_NonUniqueVisible
311 };
312
313 /// Return the required visibility status for the given type and linkage in
314 /// the current ABI.
315 RTTIUniquenessKind
316 classifyRTTIUniqueness(QualType CanTy,
317 llvm::GlobalValue::LinkageTypes Linkage) const;
318 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000319
320 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000321
322 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000323 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000324 const auto &VtableLayout =
325 CGM.getItaniumVTableContext().getVTableLayout(RD);
326
327 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000328 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000329 continue;
330
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000331 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000332 if (Method->getCanonicalDecl()->isInlined())
333 return true;
334 }
335 return false;
336 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000337};
John McCall86353412010-08-21 22:46:04 +0000338
339class ARMCXXABI : public ItaniumCXXABI {
340public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000341 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
342 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
343 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000344
Craig Topper4f12f102014-03-12 06:41:41 +0000345 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000346 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
347 isa<CXXDestructorDecl>(GD.getDecl()) &&
348 GD.getDtorType() != Dtor_Deleting));
349 }
John McCall5d865c322010-08-31 07:33:07 +0000350
Craig Topper4f12f102014-03-12 06:41:41 +0000351 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
352 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000353
Craig Topper4f12f102014-03-12 06:41:41 +0000354 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall8ed55a52010-09-02 09:58:18 +0000355 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
356 llvm::Value *NewPtr,
357 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000358 const CXXNewExpr *expr,
Craig Topper4f12f102014-03-12 06:41:41 +0000359 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000360 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000361 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000362};
Tim Northovera2ee4332014-03-29 15:09:45 +0000363
364class iOS64CXXABI : public ARMCXXABI {
365public:
366 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
Tim Northover65f582f2014-03-30 17:32:48 +0000367
368 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000369 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000370};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000371}
Charles Davis4e786dd2010-05-25 19:52:27 +0000372
Charles Davis53c59df2010-08-16 03:33:14 +0000373CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000374 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000375 // For IR-generation purposes, there's no significant difference
376 // between the ARM and iOS ABIs.
377 case TargetCXXABI::GenericARM:
378 case TargetCXXABI::iOS:
379 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000380
Tim Northovera2ee4332014-03-29 15:09:45 +0000381 case TargetCXXABI::iOS64:
382 return new iOS64CXXABI(CGM);
383
Tim Northover9bb857a2013-01-31 12:13:10 +0000384 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
385 // include the other 32-bit ARM oddities: constructor/destructor return values
386 // and array cookies.
387 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000388 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
389 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000390
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000391 case TargetCXXABI::GenericMIPS:
392 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
393
John McCall57625922013-01-25 23:36:14 +0000394 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000395 if (CGM.getContext().getTargetInfo().getTriple().getArch()
396 == llvm::Triple::le32) {
397 // For PNaCl, use ARM-style method pointers so that PNaCl code
398 // does not assume anything about the alignment of function
399 // pointers.
400 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
401 /* UseARMGuardVarABI = */ false);
402 }
John McCall57625922013-01-25 23:36:14 +0000403 return new ItaniumCXXABI(CGM);
404
405 case TargetCXXABI::Microsoft:
406 llvm_unreachable("Microsoft ABI is not Itanium-based");
407 }
408 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000409}
410
Chris Lattnera5f58b02011-07-09 17:41:47 +0000411llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000412ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
413 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000414 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000415 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000416}
417
John McCalld9c6c0b2010-08-22 00:59:17 +0000418/// In the Itanium and ARM ABIs, method pointers have the form:
419/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
420///
421/// In the Itanium ABI:
422/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
423/// - the this-adjustment is (memptr.adj)
424/// - the virtual offset is (memptr.ptr - 1)
425///
426/// In the ARM ABI:
427/// - method pointers are virtual if (memptr.adj & 1) is nonzero
428/// - the this-adjustment is (memptr.adj >> 1)
429/// - the virtual offset is (memptr.ptr)
430/// ARM uses 'adj' for the virtual flag because Thumb functions
431/// may be only single-byte aligned.
432///
433/// If the member is virtual, the adjusted 'this' pointer points
434/// to a vtable pointer from which the virtual offset is applied.
435///
436/// If the member is non-virtual, memptr.ptr is the address of
437/// the function to call.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000438llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
439 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
440 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000441 CGBuilderTy &Builder = CGF.Builder;
442
443 const FunctionProtoType *FPT =
444 MPT->getPointeeType()->getAs<FunctionProtoType>();
445 const CXXRecordDecl *RD =
446 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
447
Chris Lattner2192fe52011-07-18 04:24:23 +0000448 llvm::FunctionType *FTy =
John McCalla729c622012-02-17 03:33:10 +0000449 CGM.getTypes().GetFunctionType(
450 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
John McCall475999d2010-08-22 00:05:51 +0000451
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000452 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000453
John McCalld9c6c0b2010-08-22 00:59:17 +0000454 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
455 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
456 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
457
John McCalla1dee5302010-08-22 10:59:02 +0000458 // Extract memptr.adj, which is in the second field.
459 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000460
461 // Compute the true adjustment.
462 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000463 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000464 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000465
466 // Apply the adjustment and cast back to the original struct type
467 // for consistency.
John McCalld9c6c0b2010-08-22 00:59:17 +0000468 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
469 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
470 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall475999d2010-08-22 00:05:51 +0000471
472 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000473 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000474
475 // If the LSB in the function pointer is 1, the function pointer points to
476 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000477 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000478 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000479 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
480 else
481 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
482 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000483 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
484
485 // In the virtual path, the adjustment left 'This' pointing to the
486 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000487 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000488 CGF.EmitBlock(FnVirtual);
489
490 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000491 llvm::Type *VTableTy = Builder.getInt8PtrTy();
Richard Smith0fc7bdc2014-03-12 18:26:14 +0000492 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
John McCall475999d2010-08-22 00:05:51 +0000493
494 // Apply the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000495 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000496 if (!UseARMMethodPtrABI)
497 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld9c6c0b2010-08-22 00:59:17 +0000498 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000499
500 // Load the virtual function to call.
501 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCalld9c6c0b2010-08-22 00:59:17 +0000502 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000503 CGF.EmitBranch(FnEnd);
504
505 // In the non-virtual path, the function pointer is actually a
506 // function pointer.
507 CGF.EmitBlock(FnNonVirtual);
508 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000509 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000510
511 // We're done.
512 CGF.EmitBlock(FnEnd);
Jay Foad20c0f022011-03-30 11:28:58 +0000513 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
John McCall475999d2010-08-22 00:05:51 +0000514 Callee->addIncoming(VirtualFn, FnVirtual);
515 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
516 return Callee;
517}
John McCalla8bbb822010-08-22 03:04:22 +0000518
John McCallc134eb52010-08-31 21:07:20 +0000519/// Compute an l-value by applying the given pointer-to-member to a
520/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000521llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
522 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
523 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000524 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000525
526 CGBuilderTy &Builder = CGF.Builder;
527
Micah Villmowea2fea22012-10-25 15:39:14 +0000528 unsigned AS = Base->getType()->getPointerAddressSpace();
John McCallc134eb52010-08-31 21:07:20 +0000529
530 // Cast to char*.
531 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
532
533 // Apply the offset, which we assume is non-null.
534 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
535
536 // Cast the address to the appropriate pointer type, adopting the
537 // address space of the base pointer.
Chris Lattner2192fe52011-07-18 04:24:23 +0000538 llvm::Type *PType
Douglas Gregor04f36212010-09-02 17:38:50 +0000539 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
John McCallc134eb52010-08-31 21:07:20 +0000540 return Builder.CreateBitCast(Addr, PType);
541}
542
John McCallc62bb392012-02-15 01:22:51 +0000543/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
544/// conversion.
545///
546/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000547///
548/// Obligatory offset/adjustment diagram:
549/// <-- offset --> <-- adjustment -->
550/// |--------------------------|----------------------|--------------------|
551/// ^Derived address point ^Base address point ^Member address point
552///
553/// So when converting a base member pointer to a derived member pointer,
554/// we add the offset to the adjustment because the address point has
555/// decreased; and conversely, when converting a derived MP to a base MP
556/// we subtract the offset from the adjustment because the address point
557/// has increased.
558///
559/// The standard forbids (at compile time) conversion to and from
560/// virtual bases, which is why we don't have to consider them here.
561///
562/// The standard forbids (at run time) casting a derived MP to a base
563/// MP when the derived MP does not point to a member of the base.
564/// This is why -1 is a reasonable choice for null data member
565/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000566llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000567ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
568 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000569 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000570 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000571 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
572 E->getCastKind() == CK_ReinterpretMemberPointer);
573
574 // Under Itanium, reinterprets don't require any additional processing.
575 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
576
577 // Use constant emission if we can.
578 if (isa<llvm::Constant>(src))
579 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
580
581 llvm::Constant *adj = getMemberPointerAdjustment(E);
582 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000583
584 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000585 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000586
John McCallc62bb392012-02-15 01:22:51 +0000587 const MemberPointerType *destTy =
588 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000589
John McCall7a9aac22010-08-23 01:21:21 +0000590 // For member data pointers, this is just a matter of adding the
591 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000592 if (destTy->isMemberDataPointer()) {
593 llvm::Value *dst;
594 if (isDerivedToBase)
595 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000596 else
John McCallc62bb392012-02-15 01:22:51 +0000597 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000598
599 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000600 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
601 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
602 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000603 }
604
John McCalla1dee5302010-08-22 10:59:02 +0000605 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000606 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000607 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
608 offset <<= 1;
609 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000610 }
611
John McCallc62bb392012-02-15 01:22:51 +0000612 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
613 llvm::Value *dstAdj;
614 if (isDerivedToBase)
615 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000616 else
John McCallc62bb392012-02-15 01:22:51 +0000617 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000618
John McCallc62bb392012-02-15 01:22:51 +0000619 return Builder.CreateInsertValue(src, dstAdj, 1);
620}
621
622llvm::Constant *
623ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
624 llvm::Constant *src) {
625 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
626 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
627 E->getCastKind() == CK_ReinterpretMemberPointer);
628
629 // Under Itanium, reinterprets don't require any additional processing.
630 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
631
632 // If the adjustment is trivial, we don't need to do anything.
633 llvm::Constant *adj = getMemberPointerAdjustment(E);
634 if (!adj) return src;
635
636 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
637
638 const MemberPointerType *destTy =
639 E->getType()->castAs<MemberPointerType>();
640
641 // For member data pointers, this is just a matter of adding the
642 // offset if the source is non-null.
643 if (destTy->isMemberDataPointer()) {
644 // null maps to null.
645 if (src->isAllOnesValue()) return src;
646
647 if (isDerivedToBase)
648 return llvm::ConstantExpr::getNSWSub(src, adj);
649 else
650 return llvm::ConstantExpr::getNSWAdd(src, adj);
651 }
652
653 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000654 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000655 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
656 offset <<= 1;
657 adj = llvm::ConstantInt::get(adj->getType(), offset);
658 }
659
660 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
661 llvm::Constant *dstAdj;
662 if (isDerivedToBase)
663 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
664 else
665 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
666
667 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000668}
John McCall84fa5102010-08-22 04:16:24 +0000669
670llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000671ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000672 // Itanium C++ ABI 2.3:
673 // A NULL pointer is represented as -1.
674 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000675 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000676
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000677 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000678 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000679 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000680}
681
John McCallf3a88602011-02-03 08:15:49 +0000682llvm::Constant *
683ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
684 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000685 // Itanium C++ ABI 2.3:
686 // A pointer to data member is an offset from the base address of
687 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000688 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000689}
690
David Majnemere2be95b2015-06-23 07:31:01 +0000691llvm::Constant *
692ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000693 return BuildMemberPointer(MD, CharUnits::Zero());
694}
695
696llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
697 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000698 assert(MD->isInstance() && "Member function must not be static!");
699 MD = MD->getCanonicalDecl();
700
701 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000702
703 // Get the function pointer (or index if this is a virtual function).
704 llvm::Constant *MemPtr[2];
705 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000706 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000707
Ken Dyckdf016282011-04-09 01:30:02 +0000708 const ASTContext &Context = getContext();
709 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000711 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000712
Mark Seabornedf0d382013-07-24 16:25:13 +0000713 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000714 // ARM C++ ABI 3.2.1:
715 // This ABI specifies that adj contains twice the this
716 // adjustment, plus 1 if the member function is virtual. The
717 // least significant bit of adj then makes exactly the same
718 // discrimination as the least significant bit of ptr does for
719 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000720 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
721 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000722 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000723 } else {
724 // Itanium C++ ABI 2.3:
725 // For a virtual function, [the pointer field] is 1 plus the
726 // virtual table offset (in bytes) of the function,
727 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000728 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
729 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000730 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000731 }
732 } else {
John McCall2979fe02011-04-12 00:42:48 +0000733 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000734 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000735 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000736 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000737 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000738 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000739 } else {
John McCall2979fe02011-04-12 00:42:48 +0000740 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
741 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000742 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000743 }
John McCall2979fe02011-04-12 00:42:48 +0000744 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000745
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000746 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000747 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
748 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000749 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000750 }
John McCall1c456c82010-08-22 06:43:33 +0000751
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000752 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000753}
754
Richard Smithdafff942012-01-14 04:30:29 +0000755llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
756 QualType MPType) {
757 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
758 const ValueDecl *MPD = MP.getMemberPointerDecl();
759 if (!MPD)
760 return EmitNullMemberPointer(MPT);
761
Reid Kleckner452abac2013-05-09 21:01:17 +0000762 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000763
764 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
765 return BuildMemberPointer(MD, ThisAdjustment);
766
767 CharUnits FieldOffset =
768 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
769 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
770}
771
John McCall131d97d2010-08-22 08:30:07 +0000772/// The comparison algorithm is pretty easy: the member pointers are
773/// the same if they're either bitwise identical *or* both null.
774///
775/// ARM is different here only because null-ness is more complicated.
776llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000777ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
778 llvm::Value *L,
779 llvm::Value *R,
780 const MemberPointerType *MPT,
781 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000782 CGBuilderTy &Builder = CGF.Builder;
783
John McCall131d97d2010-08-22 08:30:07 +0000784 llvm::ICmpInst::Predicate Eq;
785 llvm::Instruction::BinaryOps And, Or;
786 if (Inequality) {
787 Eq = llvm::ICmpInst::ICMP_NE;
788 And = llvm::Instruction::Or;
789 Or = llvm::Instruction::And;
790 } else {
791 Eq = llvm::ICmpInst::ICMP_EQ;
792 And = llvm::Instruction::And;
793 Or = llvm::Instruction::Or;
794 }
795
John McCall7a9aac22010-08-23 01:21:21 +0000796 // Member data pointers are easy because there's a unique null
797 // value, so it just comes down to bitwise equality.
798 if (MPT->isMemberDataPointer())
799 return Builder.CreateICmp(Eq, L, R);
800
801 // For member function pointers, the tautologies are more complex.
802 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000803 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000804 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000805 // (L == R) <==> (L.ptr == R.ptr &&
806 // (L.adj == R.adj ||
807 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000808 // The inequality tautologies have exactly the same structure, except
809 // applying De Morgan's laws.
810
811 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
812 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
813
John McCall131d97d2010-08-22 08:30:07 +0000814 // This condition tests whether L.ptr == R.ptr. This must always be
815 // true for equality to hold.
816 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
817
818 // This condition, together with the assumption that L.ptr == R.ptr,
819 // tests whether the pointers are both null. ARM imposes an extra
820 // condition.
821 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
822 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
823
824 // This condition tests whether L.adj == R.adj. If this isn't
825 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000826 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
827 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000828 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
829
830 // Null member function pointers on ARM clear the low bit of Adj,
831 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000832 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000833 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
834
835 // Compute (l.adj | r.adj) & 1 and test it against zero.
836 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
837 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
838 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
839 "cmp.or.adj");
840 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
841 }
842
843 // Tie together all our conditions.
844 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
845 Result = Builder.CreateBinOp(And, PtrEq, Result,
846 Inequality ? "memptr.ne" : "memptr.eq");
847 return Result;
848}
849
850llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000851ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
852 llvm::Value *MemPtr,
853 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000854 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000855
856 /// For member data pointers, this is just a check against -1.
857 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000858 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000859 llvm::Value *NegativeOne =
860 llvm::Constant::getAllOnesValue(MemPtr->getType());
861 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
862 }
John McCall131d97d2010-08-22 08:30:07 +0000863
Daniel Dunbar914bc412011-04-19 23:10:47 +0000864 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000865 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000866
867 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
868 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
869
Daniel Dunbar914bc412011-04-19 23:10:47 +0000870 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
871 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000872 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000873 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000874 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000875 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000876 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
877 "memptr.isvirtual");
878 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000879 }
880
881 return Result;
882}
John McCall1c456c82010-08-22 06:43:33 +0000883
Reid Kleckner40ca9132014-05-13 22:05:45 +0000884bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
885 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
886 if (!RD)
887 return false;
888
Reid Klecknerd355ca72014-05-15 01:26:32 +0000889 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
890 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
891 // special members.
892 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000893 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
894 return true;
895 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000896 return false;
897}
898
John McCall614dbdc2010-08-22 21:01:12 +0000899/// The Itanium ABI requires non-zero initialization only for data
900/// member pointers, for which '0' is a valid offset.
901bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +0000902 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +0000903}
John McCall5d865c322010-08-31 07:33:07 +0000904
John McCall82fb8922012-09-25 10:10:39 +0000905/// The Itanium ABI always places an offset to the complete object
906/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +0000907void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
908 const CXXDeleteExpr *DE,
909 llvm::Value *Ptr,
910 QualType ElementType,
911 const CXXDestructorDecl *Dtor) {
912 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000913 if (UseGlobalDelete) {
914 // Derive the complete-object pointer, which is what we need
915 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +0000916
David Majnemer0c0b6d92014-10-31 20:09:12 +0000917 // Grab the vtable pointer as an intptr_t*.
918 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
John McCall82fb8922012-09-25 10:10:39 +0000919
David Majnemer0c0b6d92014-10-31 20:09:12 +0000920 // Track back to entry -2 and pull out the offset there.
921 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
922 VTable, -2, "complete-offset.ptr");
923 llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
924 Offset->setAlignment(CGF.PointerAlignInBytes);
925
926 // Apply the offset.
927 llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
928 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
929
930 // If we're supposed to call the global delete, make sure we do so
931 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +0000932 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
933 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000934 }
935
936 // FIXME: Provide a source location here even though there's no
937 // CXXMemberCallExpr for dtor call.
938 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
939 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
940
941 if (UseGlobalDelete)
942 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +0000943}
944
David Majnemer442d0a22014-11-25 07:20:20 +0000945void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
946 // void __cxa_rethrow();
947
948 llvm::FunctionType *FTy =
949 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
950
951 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
952
953 if (isNoReturn)
954 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
955 else
956 CGF.EmitRuntimeCallOrInvoke(Fn);
957}
958
David Majnemer7c237072015-03-05 00:46:22 +0000959static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
960 // void *__cxa_allocate_exception(size_t thrown_size);
961
962 llvm::FunctionType *FTy =
963 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
964
965 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
966}
967
968static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
969 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
970 // void (*dest) (void *));
971
972 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
973 llvm::FunctionType *FTy =
974 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
975
976 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
977}
978
979void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
980 QualType ThrowType = E->getSubExpr()->getType();
981 // Now allocate the exception object.
982 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
983 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
984
985 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
986 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
987 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
988
989 CGF.EmitAnyExprToExn(E->getSubExpr(), ExceptionPtr);
990
991 // Now throw the exception.
992 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
993 /*ForEH=*/true);
994
995 // The address of the destructor. If the exception type has a
996 // trivial destructor (or isn't a record), we just pass null.
997 llvm::Constant *Dtor = nullptr;
998 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
999 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1000 if (!Record->hasTrivialDestructor()) {
1001 CXXDestructorDecl *DtorD = Record->getDestructor();
1002 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1003 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1004 }
1005 }
1006 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1007
1008 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1009 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1010}
1011
David Majnemer1162d252014-06-22 19:05:33 +00001012static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1013 // void *__dynamic_cast(const void *sub,
1014 // const abi::__class_type_info *src,
1015 // const abi::__class_type_info *dst,
1016 // std::ptrdiff_t src2dst_offset);
1017
1018 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1019 llvm::Type *PtrDiffTy =
1020 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1021
1022 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1023
1024 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1025
1026 // Mark the function as nounwind readonly.
1027 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1028 llvm::Attribute::ReadOnly };
1029 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1030 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1031
1032 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1033}
1034
1035static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1036 // void __cxa_bad_cast();
1037 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1038 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1039}
1040
1041/// \brief Compute the src2dst_offset hint as described in the
1042/// Itanium C++ ABI [2.9.7]
1043static CharUnits computeOffsetHint(ASTContext &Context,
1044 const CXXRecordDecl *Src,
1045 const CXXRecordDecl *Dst) {
1046 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1047 /*DetectVirtual=*/false);
1048
1049 // If Dst is not derived from Src we can skip the whole computation below and
1050 // return that Src is not a public base of Dst. Record all inheritance paths.
1051 if (!Dst->isDerivedFrom(Src, Paths))
1052 return CharUnits::fromQuantity(-2ULL);
1053
1054 unsigned NumPublicPaths = 0;
1055 CharUnits Offset;
1056
1057 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001058 for (const CXXBasePath &Path : Paths) {
1059 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001060 continue;
1061
1062 ++NumPublicPaths;
1063
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001064 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001065 // If the path contains a virtual base class we can't give any hint.
1066 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001067 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001068 return CharUnits::fromQuantity(-1ULL);
1069
1070 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1071 continue;
1072
1073 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001074 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1075 Offset += L.getBaseClassOffset(
1076 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001077 }
1078 }
1079
1080 // -2: Src is not a public base of Dst.
1081 if (NumPublicPaths == 0)
1082 return CharUnits::fromQuantity(-2ULL);
1083
1084 // -3: Src is a multiple public base type but never a virtual base type.
1085 if (NumPublicPaths > 1)
1086 return CharUnits::fromQuantity(-3ULL);
1087
1088 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1089 // Return the offset of Src from the origin of Dst.
1090 return Offset;
1091}
1092
1093static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1094 // void __cxa_bad_typeid();
1095 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1096
1097 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1098}
1099
1100bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1101 QualType SrcRecordTy) {
1102 return IsDeref;
1103}
1104
1105void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1106 llvm::Value *Fn = getBadTypeidFn(CGF);
1107 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1108 CGF.Builder.CreateUnreachable();
1109}
1110
1111llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1112 QualType SrcRecordTy,
1113 llvm::Value *ThisPtr,
1114 llvm::Type *StdTypeInfoPtrTy) {
1115 llvm::Value *Value =
1116 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
1117
1118 // Load the type info.
1119 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1120 return CGF.Builder.CreateLoad(Value);
1121}
1122
1123bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1124 QualType SrcRecordTy) {
1125 return SrcIsPtr;
1126}
1127
1128llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1129 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
1130 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1131 llvm::Type *PtrDiffLTy =
1132 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1133 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1134
1135 llvm::Value *SrcRTTI =
1136 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1137 llvm::Value *DestRTTI =
1138 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1139
1140 // Compute the offset hint.
1141 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1142 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1143 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1144 PtrDiffLTy,
1145 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1146
1147 // Emit the call to __dynamic_cast.
1148 Value = CGF.EmitCastToVoidPtr(Value);
1149
1150 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1151 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1152 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1153
1154 /// C++ [expr.dynamic.cast]p9:
1155 /// A failed cast to reference type throws std::bad_cast
1156 if (DestTy->isReferenceType()) {
1157 llvm::BasicBlock *BadCastBlock =
1158 CGF.createBasicBlock("dynamic_cast.bad_cast");
1159
1160 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1161 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1162
1163 CGF.EmitBlock(BadCastBlock);
1164 EmitBadCastCall(CGF);
1165 }
1166
1167 return Value;
1168}
1169
1170llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1171 llvm::Value *Value,
1172 QualType SrcRecordTy,
1173 QualType DestTy) {
1174 llvm::Type *PtrDiffLTy =
1175 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1176 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1177
1178 // Get the vtable pointer.
1179 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1180
1181 // Get the offset-to-top from the vtable.
1182 llvm::Value *OffsetToTop =
1183 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1184 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1185
1186 // Finally, add the offset to the pointer.
1187 Value = CGF.EmitCastToVoidPtr(Value);
1188 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1189
1190 return CGF.Builder.CreateBitCast(Value, DestLTy);
1191}
1192
1193bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1194 llvm::Value *Fn = getBadCastFn(CGF);
1195 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1196 CGF.Builder.CreateUnreachable();
1197 return true;
1198}
1199
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001200llvm::Value *
1201ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1202 llvm::Value *This,
1203 const CXXRecordDecl *ClassDecl,
1204 const CXXRecordDecl *BaseClassDecl) {
1205 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1206 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001207 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1208 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001209
1210 llvm::Value *VBaseOffsetPtr =
1211 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1212 "vbase.offset.ptr");
1213 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1214 CGM.PtrDiffTy->getPointerTo());
1215
1216 llvm::Value *VBaseOffset =
1217 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1218
1219 return VBaseOffset;
1220}
1221
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001222void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1223 // Just make sure we're in sync with TargetCXXABI.
1224 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1225
Rafael Espindolac3cde362013-12-09 14:51:17 +00001226 // The constructor used for constructing this as a base class;
1227 // ignores virtual bases.
1228 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1229
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001230 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001231 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001232 if (!D->getParent()->isAbstract()) {
1233 // We don't need to emit the complete ctor if the class is abstract.
1234 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1235 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001236}
1237
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001238void
1239ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1240 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001241 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001242
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001243 // All parameters are already in place except VTT, which goes after 'this'.
1244 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001245
1246 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001247 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1248 ArgTys.insert(ArgTys.begin() + 1,
1249 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001250}
1251
Reid Klecknere7de47e2013-07-22 13:51:44 +00001252void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001253 // The destructor used for destructing this as a base class; ignores
1254 // virtual bases.
1255 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001256
1257 // The destructor used for destructing this as a most-derived class;
1258 // call the base destructor and then destructs any virtual bases.
1259 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1260
Rafael Espindolac3cde362013-12-09 14:51:17 +00001261 // The destructor in a virtual table is always a 'deleting'
1262 // destructor, which calls the complete destructor and then uses the
1263 // appropriate operator delete.
1264 if (D->isVirtual())
1265 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001266}
1267
Reid Kleckner89077a12013-12-17 19:46:40 +00001268void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1269 QualType &ResTy,
1270 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001271 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001272 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001273
1274 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001275 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001276 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001277
1278 // FIXME: avoid the fake decl
1279 QualType T = Context.getPointerType(Context.VoidPtrTy);
1280 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001281 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001282 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001283 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001284 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001285 }
1286}
1287
John McCall5d865c322010-08-31 07:33:07 +00001288void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1289 /// Initialize the 'this' slot.
1290 EmitThisParam(CGF);
1291
1292 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001293 if (getStructorImplicitParamDecl(CGF)) {
1294 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1295 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001296 }
John McCall5d865c322010-08-31 07:33:07 +00001297
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001298 /// If this is a function that the ABI specifies returns 'this', initialize
1299 /// the return slot to 'this' at the start of the function.
1300 ///
1301 /// Unlike the setting of return types, this is done within the ABI
1302 /// implementation instead of by clients of CGCXXABI because:
1303 /// 1) getThisValue is currently protected
1304 /// 2) in theory, an ABI could implement 'this' returns some other way;
1305 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001306 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001307 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001308}
1309
Reid Kleckner89077a12013-12-17 19:46:40 +00001310unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1311 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1312 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1313 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1314 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001315
Reid Kleckner89077a12013-12-17 19:46:40 +00001316 // Insert the implicit 'vtt' argument as the second argument.
1317 llvm::Value *VTT =
1318 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1319 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1320 Args.insert(Args.begin() + 1,
1321 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1322 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001323}
1324
1325void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1326 const CXXDestructorDecl *DD,
1327 CXXDtorType Type, bool ForVirtualBase,
1328 bool Delegating, llvm::Value *This) {
1329 GlobalDecl GD(DD, Type);
1330 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1331 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1332
Craig Topper8a13c412014-05-21 05:09:00 +00001333 llvm::Value *Callee = nullptr;
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001334 if (getContext().getLangOpts().AppleKext)
1335 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1336
1337 if (!Callee)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001338 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001339
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001340 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1341 VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001342}
1343
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001344void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1345 const CXXRecordDecl *RD) {
1346 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1347 if (VTable->hasInitializer())
1348 return;
1349
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001350 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001351 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1352 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001353 llvm::Constant *RTTI =
1354 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001355
1356 // Create and set the initializer.
1357 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1358 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
David Majnemerd905da42014-07-01 20:30:31 +00001359 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001360 VTable->setInitializer(Init);
1361
1362 // Set the correct linkage.
1363 VTable->setLinkage(Linkage);
1364
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001365 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1366 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001367
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001368 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001369 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001370
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001371 // Use pointer alignment for the vtable. Otherwise we would align them based
1372 // on the size of the initializer which doesn't make sense as only single
1373 // values are read.
1374 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1375 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1376
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001377 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1378 // we will emit the typeinfo for the fundamental types. This is the
1379 // same behaviour as GCC.
1380 const DeclContext *DC = RD->getDeclContext();
1381 if (RD->getIdentifier() &&
1382 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1383 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1384 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1385 DC->getParent()->isTranslationUnit())
David Majnemere2cb8d12014-07-07 06:20:47 +00001386 EmitFundamentalRTTIDescriptors();
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001387
1388 CGM.EmitVTableBitSetEntries(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001389}
1390
Piotr Padlewski525f7462015-08-27 21:35:37 +00001391bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1392 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1393 if (Vptr.NearestVBase == nullptr)
1394 return false;
1395 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski910a0592015-08-21 18:28:00 +00001396}
1397
Piotr Padlewski525f7462015-08-27 21:35:37 +00001398llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1399 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1400 const CXXRecordDecl *NearestVBase) {
1401
1402 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1403 NeedsVTTParameter(CGF.CurGD)) {
1404 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1405 NearestVBase);
1406 }
1407 return getVTableAddressPoint(Base, VTableClass);
1408}
1409
1410llvm::Constant *
1411ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1412 const CXXRecordDecl *VTableClass) {
1413 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001414
1415 // Find the appropriate vtable within the vtable group.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001416 uint64_t AddressPoint = CGM.getItaniumVTableContext()
1417 .getVTableLayout(VTableClass)
1418 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001419 llvm::Value *Indices[] = {
1420 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1421 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1422 };
1423
David Blaikiee3b172a2015-04-02 18:55:21 +00001424 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1425 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001426}
1427
Piotr Padlewski525f7462015-08-27 21:35:37 +00001428llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1429 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1430 const CXXRecordDecl *NearestVBase) {
1431 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1432 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1433
1434 // Get the secondary vpointer index.
1435 uint64_t VirtualPointerIndex =
1436 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1437
1438 /// Load the VTT.
1439 llvm::Value *VTT = CGF.LoadCXXVTT();
1440 if (VirtualPointerIndex)
1441 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1442
1443 // And load the address point from the VTT.
1444 return CGF.Builder.CreateLoad(VTT);
1445}
1446
1447llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1448 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1449 return getVTableAddressPoint(Base, VTableClass);
1450}
1451
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001452llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1453 CharUnits VPtrOffset) {
1454 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1455
1456 llvm::GlobalVariable *&VTable = VTables[RD];
1457 if (VTable)
1458 return VTable;
1459
1460 // Queue up this v-table for possible deferred emission.
1461 CGM.addDeferredVTable(RD);
1462
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001463 SmallString<256> Name;
1464 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001465 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001466
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001467 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001468 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1469 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1470
1471 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1472 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1473 VTable->setUnnamedAddr(true);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001474
1475 if (RD->hasAttr<DLLImportAttr>())
1476 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1477 else if (RD->hasAttr<DLLExportAttr>())
1478 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1479
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001480 return VTable;
1481}
1482
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001483llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1484 GlobalDecl GD,
1485 llvm::Value *This,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001486 llvm::Type *Ty,
1487 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001488 GD = GD.getCanonicalDecl();
1489 Ty = Ty->getPointerTo()->getPointerTo();
1490 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1491
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00001492 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001493 CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable,
1494 CodeGenFunction::CFITCK_VCall, Loc);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001495
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001496 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001497 llvm::Value *VFuncPtr =
1498 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1499 return CGF.Builder.CreateLoad(VFuncPtr);
1500}
1501
David Majnemer0c0b6d92014-10-31 20:09:12 +00001502llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1503 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1504 llvm::Value *This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001505 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001506 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1507
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001508 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1509 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001510 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001511 llvm::Value *Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001512 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1513 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001514
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001515 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1516 /*ImplicitParam=*/nullptr, QualType(), CE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001517 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001518}
1519
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001520void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001521 CodeGenVTables &VTables = CGM.getVTables();
1522 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001523 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001524}
1525
Piotr Padlewski81461a42015-08-27 21:35:41 +00001526bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001527 // We don't emit available_externally vtables if we are in -fapple-kext mode
1528 // because kext mode does not permit devirtualization.
1529 if (CGM.getLangOpts().AppleKext)
1530 return false;
1531
1532 // If we don't have any inline virtual functions,
1533 // then we are safe to emit available_externally copy of vtable.
1534 // FIXME we can still emit a copy of the vtable if we
1535 // can emit definition of the inline functions.
Piotr Padlewski1d02f682015-08-19 20:09:09 +00001536 return !hasAnyUsedVirtualInlineFunction(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001537}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001538static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1539 llvm::Value *Ptr,
1540 int64_t NonVirtualAdjustment,
1541 int64_t VirtualAdjustment,
1542 bool IsReturnAdjustment) {
1543 if (!NonVirtualAdjustment && !VirtualAdjustment)
1544 return Ptr;
1545
1546 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1547 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1548
1549 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1550 // Perform the non-virtual adjustment for a base-to-derived cast.
1551 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1552 }
1553
1554 if (VirtualAdjustment) {
1555 llvm::Type *PtrDiffTy =
1556 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1557
1558 // Perform the virtual adjustment.
1559 llvm::Value *VTablePtrPtr =
1560 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1561
1562 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1563
1564 llvm::Value *OffsetPtr =
1565 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1566
1567 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1568
1569 // Load the adjustment offset from the vtable.
1570 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1571
1572 // Adjust our pointer.
1573 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1574 }
1575
1576 if (NonVirtualAdjustment && IsReturnAdjustment) {
1577 // Perform the non-virtual adjustment for a derived-to-base cast.
1578 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1579 }
1580
1581 // Cast back to the original type.
1582 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1583}
1584
1585llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1586 llvm::Value *This,
1587 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001588 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1589 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001590 /*IsReturnAdjustment=*/false);
1591}
1592
1593llvm::Value *
1594ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1595 const ReturnAdjustment &RA) {
1596 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1597 RA.Virtual.Itanium.VBaseOffsetOffset,
1598 /*IsReturnAdjustment=*/true);
1599}
1600
John McCall5d865c322010-08-31 07:33:07 +00001601void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1602 RValue RV, QualType ResultType) {
1603 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1604 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1605
1606 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001607 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001608 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1609 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1610 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1611}
John McCall8ed55a52010-09-02 09:58:18 +00001612
1613/************************** Array allocation cookies **************************/
1614
John McCallb91cd662012-05-01 05:23:51 +00001615CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1616 // The array cookie is a size_t; pad that up to the element alignment.
1617 // The cookie is actually right-justified in that space.
1618 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1619 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001620}
1621
1622llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1623 llvm::Value *NewPtr,
1624 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001625 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001626 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001627 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001628
Micah Villmowea2fea22012-10-25 15:39:14 +00001629 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001630
John McCall9bca9232010-09-02 10:25:57 +00001631 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001632 QualType SizeTy = Ctx.getSizeType();
1633 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1634
1635 // The size of the cookie.
1636 CharUnits CookieSize =
1637 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001638 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001639
1640 // Compute an offset to the cookie.
1641 llvm::Value *CookiePtr = NewPtr;
1642 CharUnits CookieOffset = CookieSize - SizeSize;
1643 if (!CookieOffset.isZero())
1644 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1645 CookieOffset.getQuantity());
1646
1647 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001648 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1649 llvm::Value *NumElementsPtr =
1650 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1651 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001652 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001653 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001654 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001655 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1656 llvm::FunctionType *FTy =
1657 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1658 llvm::Constant *F =
1659 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1660 CGF.Builder.CreateCall(F, NumElementsPtr);
1661 }
John McCall8ed55a52010-09-02 09:58:18 +00001662
1663 // Finally, compute a pointer to the actual data buffer by skipping
1664 // over the cookie completely.
1665 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1666 CookieSize.getQuantity());
1667}
1668
John McCallb91cd662012-05-01 05:23:51 +00001669llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1670 llvm::Value *allocPtr,
1671 CharUnits cookieSize) {
1672 // The element size is right-justified in the cookie.
1673 llvm::Value *numElementsPtr = allocPtr;
1674 CharUnits numElementsOffset =
1675 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1676 if (!numElementsOffset.isZero())
1677 numElementsPtr =
1678 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1679 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001680
Micah Villmowea2fea22012-10-25 15:39:14 +00001681 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001682 numElementsPtr =
1683 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001684 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001685 return CGF.Builder.CreateLoad(numElementsPtr);
1686 // In asan mode emit a function call instead of a regular load and let the
1687 // run-time deal with it: if the shadow is properly poisoned return the
1688 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1689 // We can't simply ignore this load using nosanitize metadata because
1690 // the metadata may be lost.
1691 llvm::FunctionType *FTy =
1692 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1693 llvm::Constant *F =
1694 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1695 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001696}
1697
John McCallb91cd662012-05-01 05:23:51 +00001698CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001699 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001700 // struct array_cookie {
1701 // std::size_t element_size; // element_size != 0
1702 // std::size_t element_count;
1703 // };
John McCallc19c7062013-01-25 23:36:19 +00001704 // But the base ABI doesn't give anything an alignment greater than
1705 // 8, so we can dismiss this as typical ABI-author blindness to
1706 // actual language complexity and round up to the element alignment.
1707 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1708 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001709}
1710
1711llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001712 llvm::Value *newPtr,
1713 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001714 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001715 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001716 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001717
John McCallc19c7062013-01-25 23:36:19 +00001718 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1719 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001720
1721 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001722 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001723
1724 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001725 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1726 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1727 getContext().getTypeSizeInChars(elementType).getQuantity());
1728 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001729
1730 // The second element is the element count.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001731 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.SizeTy, cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00001732 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001733
1734 // Finally, compute a pointer to the actual data buffer by skipping
1735 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001736 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1737 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1738 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001739}
1740
John McCallb91cd662012-05-01 05:23:51 +00001741llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1742 llvm::Value *allocPtr,
1743 CharUnits cookieSize) {
1744 // The number of elements is at offset sizeof(size_t) relative to
1745 // the allocated pointer.
1746 llvm::Value *numElementsPtr
1747 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001748
Micah Villmowea2fea22012-10-25 15:39:14 +00001749 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001750 numElementsPtr =
1751 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1752 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001753}
1754
John McCall68ff0372010-09-08 01:44:27 +00001755/*********************** Static local initialization **************************/
1756
1757static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001758 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001759 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001760 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001761 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001762 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001763 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001764 llvm::AttributeSet::get(CGM.getLLVMContext(),
1765 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001766 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001767}
1768
1769static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001770 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001771 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001772 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001773 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001774 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001775 llvm::AttributeSet::get(CGM.getLLVMContext(),
1776 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001777 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001778}
1779
1780static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001781 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001782 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001783 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001784 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001785 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001786 llvm::AttributeSet::get(CGM.getLLVMContext(),
1787 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001788 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001789}
1790
1791namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001792 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001793 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001794 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001795
Craig Topper4f12f102014-03-12 06:41:41 +00001796 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001797 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1798 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001799 }
1800 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001801}
John McCall68ff0372010-09-08 01:44:27 +00001802
1803/// The ARM code here follows the Itanium code closely enough that we
1804/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001805void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1806 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001807 llvm::GlobalVariable *var,
1808 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001809 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001810
Richard Smithdbf74ba2013-04-14 23:01:42 +00001811 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001812 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001813 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1814 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001815
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001816 // If we have a global variable with internal linkage and thread-safe statics
1817 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001818 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1819
1820 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001821 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001822 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001823 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001824 // Guard variables are 64 bits in the generic ABI and size width on ARM
1825 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001826 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001827 }
John McCallb88a5662012-03-30 21:00:39 +00001828 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001829
John McCallb88a5662012-03-30 21:00:39 +00001830 // Create the guard variable if we don't already have it (as we
1831 // might if we're double-emitting this function body).
1832 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1833 if (!guard) {
1834 // Mangle the name for the guard.
1835 SmallString<256> guardName;
1836 {
1837 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001838 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001839 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001840
John McCallb88a5662012-03-30 21:00:39 +00001841 // Create the guard variable with a zero-initializer.
1842 // Just absorb linkage and visibility from the guarded variable.
1843 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1844 false, var->getLinkage(),
1845 llvm::ConstantInt::get(guardTy, 0),
1846 guardName.str());
1847 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001848 // If the variable is thread-local, so is its guard variable.
1849 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001850
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001851 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1852 // as the associated data object
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001853 llvm::Comdat *C = var->getComdat();
1854 if (!D.isLocalVarDecl() && C) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001855 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001856 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001857 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1858 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001859 }
1860
John McCallb88a5662012-03-30 21:00:39 +00001861 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1862 }
John McCall87590e62012-03-30 07:09:50 +00001863
John McCall68ff0372010-09-08 01:44:27 +00001864 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001865 //
John McCall68ff0372010-09-08 01:44:27 +00001866 // Itanium C++ ABI 3.3.2:
1867 // The following is pseudo-code showing how these functions can be used:
1868 // if (obj_guard.first_byte == 0) {
1869 // if ( __cxa_guard_acquire (&obj_guard) ) {
1870 // try {
1871 // ... initialize the object ...;
1872 // } catch (...) {
1873 // __cxa_guard_abort (&obj_guard);
1874 // throw;
1875 // }
1876 // ... queue object destructor with __cxa_atexit() ...;
1877 // __cxa_guard_release (&obj_guard);
1878 // }
1879 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001880
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001881 // Load the first byte of the guard variable.
1882 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001883 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001884 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001885
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001886 // Itanium ABI:
1887 // An implementation supporting thread-safety on multiprocessor
1888 // systems must also guarantee that references to the initialized
1889 // object do not occur before the load of the initialization flag.
1890 //
1891 // In LLVM, we do this by marking the load Acquire.
1892 if (threadsafe)
1893 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001894
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001895 // For ARM, we should only check the first bit, rather than the entire byte:
1896 //
1897 // ARM C++ ABI 3.2.3.1:
1898 // To support the potential use of initialization guard variables
1899 // as semaphores that are the target of ARM SWP and LDREX/STREX
1900 // synchronizing instructions we define a static initialization
1901 // guard variable to be a 4-byte aligned, 4-byte word with the
1902 // following inline access protocol.
1903 // #define INITIALIZED 1
1904 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1905 // if (__cxa_guard_acquire(&obj_guard))
1906 // ...
1907 // }
1908 //
1909 // and similarly for ARM64:
1910 //
1911 // ARM64 C++ ABI 3.2.2:
1912 // This ABI instead only specifies the value bit 0 of the static guard
1913 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1914 // variable is not initialized and 1 when it is.
1915 llvm::Value *V =
1916 (UseARMGuardVarABI && !useInt8GuardVariable)
1917 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1918 : LI;
1919 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001920
1921 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1922 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1923
1924 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001925 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001926
1927 CGF.EmitBlock(InitCheckBlock);
1928
1929 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001930 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001931 // Call __cxa_guard_acquire.
1932 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001933 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001934
1935 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1936
1937 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1938 InitBlock, EndBlock);
1939
1940 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001941 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001942
1943 CGF.EmitBlock(InitBlock);
1944 }
1945
1946 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001947 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001948
John McCall5aa52592011-06-17 07:33:57 +00001949 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001950 // Pop the guard-abort cleanup if we pushed one.
1951 CGF.PopCleanupBlock();
1952
1953 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001954 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001955 } else {
John McCallb88a5662012-03-30 21:00:39 +00001956 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001957 }
1958
1959 CGF.EmitBlock(EndBlock);
1960}
John McCallc84ed6a2012-05-01 06:13:13 +00001961
1962/// Register a global destructor using __cxa_atexit.
1963static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1964 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001965 llvm::Constant *addr,
1966 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001967 const char *Name = "__cxa_atexit";
1968 if (TLS) {
1969 const llvm::Triple &T = CGF.getTarget().getTriple();
1970 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1971 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001972
John McCallc84ed6a2012-05-01 06:13:13 +00001973 // We're assuming that the destructor function is something we can
1974 // reasonably call with the default CC. Go ahead and cast it to the
1975 // right prototype.
1976 llvm::Type *dtorTy =
1977 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1978
1979 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1980 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1981 llvm::FunctionType *atexitTy =
1982 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1983
1984 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001985 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001986 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1987 fn->setDoesNotThrow();
1988
1989 // Create a variable that binds the atexit to this shared object.
1990 llvm::Constant *handle =
1991 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1992
1993 llvm::Value *args[] = {
1994 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1995 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1996 handle
1997 };
John McCall882987f2013-02-28 19:01:20 +00001998 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00001999}
2000
2001/// Register a global destructor as best as we know how.
2002void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002003 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002004 llvm::Constant *dtor,
2005 llvm::Constant *addr) {
2006 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002007 if (CGM.getCodeGenOpts().CXAAtExit)
2008 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2009
2010 if (D.getTLSKind())
2011 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002012
2013 // In Apple kexts, we want to add a global destructor entry.
2014 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002015 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002016 // Generate a global destructor entry.
2017 return CGM.AddCXXDtorEntry(dtor, addr);
2018 }
2019
David Blaikieebe87e12013-08-27 23:57:18 +00002020 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002021}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002022
David Majnemer9b21c332014-07-11 20:28:10 +00002023static bool isThreadWrapperReplaceable(const VarDecl *VD,
2024 CodeGen::CodeGenModule &CGM) {
2025 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2026 // OS X prefers to have references to thread local variables to go through
2027 // the thread wrapper instead of directly referencing the backing variable.
2028 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2029 CGM.getTarget().getTriple().isMacOSX();
2030}
2031
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002032/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002033/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002034/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002035static llvm::GlobalValue::LinkageTypes
2036getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2037 llvm::GlobalValue::LinkageTypes VarLinkage =
2038 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2039
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002040 // For internal linkage variables, we don't need an external or weak wrapper.
2041 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2042 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002043
David Majnemer9b21c332014-07-11 20:28:10 +00002044 // If the thread wrapper is replaceable, give it appropriate linkage.
2045 if (isThreadWrapperReplaceable(VD, CGM)) {
2046 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
2047 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2048 return llvm::GlobalVariable::WeakAnyLinkage;
2049 return VarLinkage;
2050 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002051 return llvm::GlobalValue::WeakODRLinkage;
2052}
2053
2054llvm::Function *
2055ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002056 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002057 // Mangle the name for the thread_local wrapper function.
2058 SmallString<256> WrapperName;
2059 {
2060 llvm::raw_svector_ostream Out(WrapperName);
2061 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002062 }
2063
Alexander Musmanf94c3182014-09-26 06:28:25 +00002064 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002065 return cast<llvm::Function>(V);
2066
Alexander Musmanf94c3182014-09-26 06:28:25 +00002067 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002068 if (VD->getType()->isReferenceType())
2069 RetTy = RetTy->getPointerElementType();
2070
2071 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002072 llvm::Function *Wrapper =
2073 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2074 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002075 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002076 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002077 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002078 return Wrapper;
2079}
2080
2081void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002082 CodeGenModule &CGM,
2083 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2084 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2085 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2086 llvm::Function *InitFunc = nullptr;
2087 if (!CXXThreadLocalInits.empty()) {
2088 // Generate a guarded initialization function.
2089 llvm::FunctionType *FTy =
2090 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2091 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002092 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002093 /*TLS=*/true);
2094 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2095 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2096 llvm::GlobalVariable::InternalLinkage,
2097 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2098 Guard->setThreadLocal(true);
2099 CodeGenFunction(CGM)
2100 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2101 }
Yaron Kerenede60302015-08-01 19:11:36 +00002102 for (auto &I : CXXThreadLocals) {
2103 const VarDecl *VD = I.first;
2104 llvm::GlobalVariable *Var = I.second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002105
David Majnemer9b21c332014-07-11 20:28:10 +00002106 // Some targets require that all access to thread local variables go through
2107 // the thread wrapper. This means that we cannot attempt to create a thread
2108 // wrapper or a thread helper.
2109 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2110 continue;
2111
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002112 // Mangle the name for the thread_local initialization function.
2113 SmallString<256> InitFnName;
2114 {
2115 llvm::raw_svector_ostream Out(InitFnName);
2116 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002117 }
2118
2119 // If we have a definition for the variable, emit the initialization
2120 // function as an alias to the global Init function (if any). Otherwise,
2121 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002122 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002123 bool InitIsInitFunc = false;
2124 if (VD->hasDefinition()) {
2125 InitIsInitFunc = true;
2126 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002127 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2128 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002129 } else {
2130 // Emit a weak global function referring to the initialization function.
2131 // This function will not exist if the TU defining the thread_local
2132 // variable in question does not need any dynamic initialization for
2133 // its thread_local variables.
2134 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2135 Init = llvm::Function::Create(
2136 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2137 &CGM.getModule());
2138 }
2139
2140 if (Init)
2141 Init->setVisibility(Var->getVisibility());
2142
2143 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2144 llvm::LLVMContext &Context = CGM.getModule().getContext();
2145 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2146 CGBuilderTy Builder(Entry);
2147 if (InitIsInitFunc) {
2148 if (Init)
David Blaikie4ba525b2015-07-14 17:27:39 +00002149 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002150 } else {
2151 // Don't know whether we have an init function. Call it if it exists.
2152 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2153 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2154 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2155 Builder.CreateCondBr(Have, InitBB, ExitBB);
2156
2157 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002158 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002159 Builder.CreateBr(ExitBB);
2160
2161 Builder.SetInsertPoint(ExitBB);
2162 }
2163
2164 // For a reference, the result of the wrapper function is a pointer to
2165 // the referenced object.
2166 llvm::Value *Val = Var;
2167 if (VD->getType()->isReferenceType()) {
2168 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2169 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2170 Val = LI;
2171 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002172 if (Val->getType() != Wrapper->getReturnType())
2173 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2174 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002175 Builder.CreateRet(Val);
2176 }
2177}
2178
Richard Smith0f383742014-03-26 22:48:22 +00002179LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2180 const VarDecl *VD,
2181 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002182 QualType T = VD->getType();
2183 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2184 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002185 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002186
David Blaikie4ba525b2015-07-14 17:27:39 +00002187 Val = CGF.Builder.CreateCall(Wrapper);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002188
2189 LValue LV;
2190 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002191 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002192 else
Richard Smith0f383742014-03-26 22:48:22 +00002193 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002194 // FIXME: need setObjCGCLValueClass?
2195 return LV;
2196}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002197
2198/// Return whether the given global decl needs a VTT parameter, which it does
2199/// if it's a base constructor or destructor with virtual bases.
2200bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2201 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2202
2203 // We don't have any virtual bases, just return early.
2204 if (!MD->getParent()->getNumVBases())
2205 return false;
2206
2207 // Check if we have a base constructor.
2208 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2209 return true;
2210
2211 // Check if we have a base destructor.
2212 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2213 return true;
2214
2215 return false;
2216}
David Majnemere2cb8d12014-07-07 06:20:47 +00002217
2218namespace {
2219class ItaniumRTTIBuilder {
2220 CodeGenModule &CGM; // Per-module state.
2221 llvm::LLVMContext &VMContext;
2222 const ItaniumCXXABI &CXXABI; // Per-module state.
2223
2224 /// Fields - The fields of the RTTI descriptor currently being built.
2225 SmallVector<llvm::Constant *, 16> Fields;
2226
2227 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2228 llvm::GlobalVariable *
2229 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2230
2231 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2232 /// descriptor of the given type.
2233 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2234
2235 /// BuildVTablePointer - Build the vtable pointer for the given type.
2236 void BuildVTablePointer(const Type *Ty);
2237
2238 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2239 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2240 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2241
2242 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2243 /// classes with bases that do not satisfy the abi::__si_class_type_info
2244 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2245 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2246
2247 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2248 /// for pointer types.
2249 void BuildPointerTypeInfo(QualType PointeeTy);
2250
2251 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2252 /// type_info for an object type.
2253 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2254
2255 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2256 /// struct, used for member pointer types.
2257 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2258
2259public:
2260 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2261 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2262
2263 // Pointer type info flags.
2264 enum {
2265 /// PTI_Const - Type has const qualifier.
2266 PTI_Const = 0x1,
2267
2268 /// PTI_Volatile - Type has volatile qualifier.
2269 PTI_Volatile = 0x2,
2270
2271 /// PTI_Restrict - Type has restrict qualifier.
2272 PTI_Restrict = 0x4,
2273
2274 /// PTI_Incomplete - Type is incomplete.
2275 PTI_Incomplete = 0x8,
2276
2277 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2278 /// (in pointer to member).
2279 PTI_ContainingClassIncomplete = 0x10
2280 };
2281
2282 // VMI type info flags.
2283 enum {
2284 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2285 VMI_NonDiamondRepeat = 0x1,
2286
2287 /// VMI_DiamondShaped - Class is diamond shaped.
2288 VMI_DiamondShaped = 0x2
2289 };
2290
2291 // Base class type info flags.
2292 enum {
2293 /// BCTI_Virtual - Base class is virtual.
2294 BCTI_Virtual = 0x1,
2295
2296 /// BCTI_Public - Base class is public.
2297 BCTI_Public = 0x2
2298 };
2299
2300 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2301 ///
2302 /// \param Force - true to force the creation of this RTTI value
2303 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2304};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002305}
David Majnemere2cb8d12014-07-07 06:20:47 +00002306
2307llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2308 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002309 SmallString<256> Name;
2310 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002311 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002312
2313 // We know that the mangled name of the type starts at index 4 of the
2314 // mangled name of the typename, so we can just index into it in order to
2315 // get the mangled name of the type.
2316 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2317 Name.substr(4));
2318
2319 llvm::GlobalVariable *GV =
2320 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2321
2322 GV->setInitializer(Init);
2323
2324 return GV;
2325}
2326
2327llvm::Constant *
2328ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2329 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002330 SmallString<256> Name;
2331 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002332 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002333
2334 // Look for an existing global.
2335 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2336
2337 if (!GV) {
2338 // Create a new global variable.
2339 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2340 /*Constant=*/true,
2341 llvm::GlobalValue::ExternalLinkage, nullptr,
2342 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002343 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2344 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2345 if (RD->hasAttr<DLLImportAttr>())
2346 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2347 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002348 }
2349
2350 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2351}
2352
2353/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2354/// info for that type is defined in the standard library.
2355static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2356 // Itanium C++ ABI 2.9.2:
2357 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2358 // the run-time support library. Specifically, the run-time support
2359 // library should contain type_info objects for the types X, X* and
2360 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2361 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2362 // long, unsigned long, long long, unsigned long long, float, double,
2363 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2364 // half-precision floating point types.
2365 switch (Ty->getKind()) {
2366 case BuiltinType::Void:
2367 case BuiltinType::NullPtr:
2368 case BuiltinType::Bool:
2369 case BuiltinType::WChar_S:
2370 case BuiltinType::WChar_U:
2371 case BuiltinType::Char_U:
2372 case BuiltinType::Char_S:
2373 case BuiltinType::UChar:
2374 case BuiltinType::SChar:
2375 case BuiltinType::Short:
2376 case BuiltinType::UShort:
2377 case BuiltinType::Int:
2378 case BuiltinType::UInt:
2379 case BuiltinType::Long:
2380 case BuiltinType::ULong:
2381 case BuiltinType::LongLong:
2382 case BuiltinType::ULongLong:
2383 case BuiltinType::Half:
2384 case BuiltinType::Float:
2385 case BuiltinType::Double:
2386 case BuiltinType::LongDouble:
2387 case BuiltinType::Char16:
2388 case BuiltinType::Char32:
2389 case BuiltinType::Int128:
2390 case BuiltinType::UInt128:
2391 case BuiltinType::OCLImage1d:
2392 case BuiltinType::OCLImage1dArray:
2393 case BuiltinType::OCLImage1dBuffer:
2394 case BuiltinType::OCLImage2d:
2395 case BuiltinType::OCLImage2dArray:
2396 case BuiltinType::OCLImage3d:
2397 case BuiltinType::OCLSampler:
2398 case BuiltinType::OCLEvent:
2399 return true;
2400
2401 case BuiltinType::Dependent:
2402#define BUILTIN_TYPE(Id, SingletonId)
2403#define PLACEHOLDER_TYPE(Id, SingletonId) \
2404 case BuiltinType::Id:
2405#include "clang/AST/BuiltinTypes.def"
2406 llvm_unreachable("asking for RRTI for a placeholder type!");
2407
2408 case BuiltinType::ObjCId:
2409 case BuiltinType::ObjCClass:
2410 case BuiltinType::ObjCSel:
2411 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2412 }
2413
2414 llvm_unreachable("Invalid BuiltinType Kind!");
2415}
2416
2417static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2418 QualType PointeeTy = PointerTy->getPointeeType();
2419 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2420 if (!BuiltinTy)
2421 return false;
2422
2423 // Check the qualifiers.
2424 Qualifiers Quals = PointeeTy.getQualifiers();
2425 Quals.removeConst();
2426
2427 if (!Quals.empty())
2428 return false;
2429
2430 return TypeInfoIsInStandardLibrary(BuiltinTy);
2431}
2432
2433/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2434/// information for the given type exists in the standard library.
2435static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2436 // Type info for builtin types is defined in the standard library.
2437 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2438 return TypeInfoIsInStandardLibrary(BuiltinTy);
2439
2440 // Type info for some pointer types to builtin types is defined in the
2441 // standard library.
2442 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2443 return TypeInfoIsInStandardLibrary(PointerTy);
2444
2445 return false;
2446}
2447
2448/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2449/// the given type exists somewhere else, and that we should not emit the type
2450/// information in this translation unit. Assumes that it is not a
2451/// standard-library type.
2452static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2453 QualType Ty) {
2454 ASTContext &Context = CGM.getContext();
2455
2456 // If RTTI is disabled, assume it might be disabled in the
2457 // translation unit that defines any potential key function, too.
2458 if (!Context.getLangOpts().RTTI) return false;
2459
2460 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2461 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2462 if (!RD->hasDefinition())
2463 return false;
2464
2465 if (!RD->isDynamicClass())
2466 return false;
2467
2468 // FIXME: this may need to be reconsidered if the key function
2469 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002470 // N.B. We must always emit the RTTI data ourselves if there exists a key
2471 // function.
2472 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002473 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002474 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002475
David Majnemerbe9022c2015-08-06 20:56:55 +00002476 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002477 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002478 }
2479
2480 return false;
2481}
2482
2483/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2484static bool IsIncompleteClassType(const RecordType *RecordTy) {
2485 return !RecordTy->getDecl()->isCompleteDefinition();
2486}
2487
2488/// ContainsIncompleteClassType - Returns whether the given type contains an
2489/// incomplete class type. This is true if
2490///
2491/// * The given type is an incomplete class type.
2492/// * The given type is a pointer type whose pointee type contains an
2493/// incomplete class type.
2494/// * The given type is a member pointer type whose class is an incomplete
2495/// class type.
2496/// * The given type is a member pointer type whoise pointee type contains an
2497/// incomplete class type.
2498/// is an indirect or direct pointer to an incomplete class type.
2499static bool ContainsIncompleteClassType(QualType Ty) {
2500 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2501 if (IsIncompleteClassType(RecordTy))
2502 return true;
2503 }
2504
2505 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2506 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2507
2508 if (const MemberPointerType *MemberPointerTy =
2509 dyn_cast<MemberPointerType>(Ty)) {
2510 // Check if the class type is incomplete.
2511 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2512 if (IsIncompleteClassType(ClassType))
2513 return true;
2514
2515 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2516 }
2517
2518 return false;
2519}
2520
2521// CanUseSingleInheritance - Return whether the given record decl has a "single,
2522// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2523// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2524static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2525 // Check the number of bases.
2526 if (RD->getNumBases() != 1)
2527 return false;
2528
2529 // Get the base.
2530 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2531
2532 // Check that the base is not virtual.
2533 if (Base->isVirtual())
2534 return false;
2535
2536 // Check that the base is public.
2537 if (Base->getAccessSpecifier() != AS_public)
2538 return false;
2539
2540 // Check that the class is dynamic iff the base is.
2541 const CXXRecordDecl *BaseDecl =
2542 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2543 if (!BaseDecl->isEmpty() &&
2544 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2545 return false;
2546
2547 return true;
2548}
2549
2550void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2551 // abi::__class_type_info.
2552 static const char * const ClassTypeInfo =
2553 "_ZTVN10__cxxabiv117__class_type_infoE";
2554 // abi::__si_class_type_info.
2555 static const char * const SIClassTypeInfo =
2556 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2557 // abi::__vmi_class_type_info.
2558 static const char * const VMIClassTypeInfo =
2559 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2560
2561 const char *VTableName = nullptr;
2562
2563 switch (Ty->getTypeClass()) {
2564#define TYPE(Class, Base)
2565#define ABSTRACT_TYPE(Class, Base)
2566#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2567#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2568#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2569#include "clang/AST/TypeNodes.def"
2570 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2571
2572 case Type::LValueReference:
2573 case Type::RValueReference:
2574 llvm_unreachable("References shouldn't get here");
2575
2576 case Type::Auto:
2577 llvm_unreachable("Undeduced auto type shouldn't get here");
2578
2579 case Type::Builtin:
2580 // GCC treats vector and complex types as fundamental types.
2581 case Type::Vector:
2582 case Type::ExtVector:
2583 case Type::Complex:
2584 case Type::Atomic:
2585 // FIXME: GCC treats block pointers as fundamental types?!
2586 case Type::BlockPointer:
2587 // abi::__fundamental_type_info.
2588 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2589 break;
2590
2591 case Type::ConstantArray:
2592 case Type::IncompleteArray:
2593 case Type::VariableArray:
2594 // abi::__array_type_info.
2595 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2596 break;
2597
2598 case Type::FunctionNoProto:
2599 case Type::FunctionProto:
2600 // abi::__function_type_info.
2601 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2602 break;
2603
2604 case Type::Enum:
2605 // abi::__enum_type_info.
2606 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2607 break;
2608
2609 case Type::Record: {
2610 const CXXRecordDecl *RD =
2611 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2612
2613 if (!RD->hasDefinition() || !RD->getNumBases()) {
2614 VTableName = ClassTypeInfo;
2615 } else if (CanUseSingleInheritance(RD)) {
2616 VTableName = SIClassTypeInfo;
2617 } else {
2618 VTableName = VMIClassTypeInfo;
2619 }
2620
2621 break;
2622 }
2623
2624 case Type::ObjCObject:
2625 // Ignore protocol qualifiers.
2626 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2627
2628 // Handle id and Class.
2629 if (isa<BuiltinType>(Ty)) {
2630 VTableName = ClassTypeInfo;
2631 break;
2632 }
2633
2634 assert(isa<ObjCInterfaceType>(Ty));
2635 // Fall through.
2636
2637 case Type::ObjCInterface:
2638 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2639 VTableName = SIClassTypeInfo;
2640 } else {
2641 VTableName = ClassTypeInfo;
2642 }
2643 break;
2644
2645 case Type::ObjCObjectPointer:
2646 case Type::Pointer:
2647 // abi::__pointer_type_info.
2648 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2649 break;
2650
2651 case Type::MemberPointer:
2652 // abi::__pointer_to_member_type_info.
2653 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2654 break;
2655 }
2656
2657 llvm::Constant *VTable =
2658 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2659
2660 llvm::Type *PtrDiffTy =
2661 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2662
2663 // The vtable address point is 2.
2664 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002665 VTable =
2666 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002667 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2668
2669 Fields.push_back(VTable);
2670}
2671
2672/// \brief Return the linkage that the type info and type info name constants
2673/// should have for the given type.
2674static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2675 QualType Ty) {
2676 // Itanium C++ ABI 2.9.5p7:
2677 // In addition, it and all of the intermediate abi::__pointer_type_info
2678 // structs in the chain down to the abi::__class_type_info for the
2679 // incomplete class type must be prevented from resolving to the
2680 // corresponding type_info structs for the complete class type, possibly
2681 // by making them local static objects. Finally, a dummy class RTTI is
2682 // generated for the incomplete type that will not resolve to the final
2683 // complete class RTTI (because the latter need not exist), possibly by
2684 // making it a local static object.
2685 if (ContainsIncompleteClassType(Ty))
2686 return llvm::GlobalValue::InternalLinkage;
2687
2688 switch (Ty->getLinkage()) {
2689 case NoLinkage:
2690 case InternalLinkage:
2691 case UniqueExternalLinkage:
2692 return llvm::GlobalValue::InternalLinkage;
2693
2694 case VisibleNoLinkage:
2695 case ExternalLinkage:
2696 if (!CGM.getLangOpts().RTTI) {
2697 // RTTI is not enabled, which means that this type info struct is going
2698 // to be used for exception handling. Give it linkonce_odr linkage.
2699 return llvm::GlobalValue::LinkOnceODRLinkage;
2700 }
2701
2702 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2703 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2704 if (RD->hasAttr<WeakAttr>())
2705 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002706 if (RD->isDynamicClass()) {
2707 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2708 // MinGW won't export the RTTI information when there is a key function.
2709 // Make sure we emit our own copy instead of attempting to dllimport it.
2710 if (RD->hasAttr<DLLImportAttr>() &&
2711 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2712 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2713 return LT;
2714 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002715 }
2716
2717 return llvm::GlobalValue::LinkOnceODRLinkage;
2718 }
2719
2720 llvm_unreachable("Invalid linkage!");
2721}
2722
2723llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2724 // We want to operate on the canonical type.
2725 Ty = CGM.getContext().getCanonicalType(Ty);
2726
2727 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002728 SmallString<256> Name;
2729 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002730 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002731
2732 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2733 if (OldGV && !OldGV->isDeclaration()) {
2734 assert(!OldGV->hasAvailableExternallyLinkage() &&
2735 "available_externally typeinfos not yet implemented");
2736
2737 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2738 }
2739
2740 // Check if there is already an external RTTI descriptor for this type.
2741 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2742 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2743 return GetAddrOfExternalRTTIDescriptor(Ty);
2744
2745 // Emit the standard library with external linkage.
2746 llvm::GlobalVariable::LinkageTypes Linkage;
2747 if (IsStdLib)
2748 Linkage = llvm::GlobalValue::ExternalLinkage;
2749 else
2750 Linkage = getTypeInfoLinkage(CGM, Ty);
2751
2752 // Add the vtable pointer.
2753 BuildVTablePointer(cast<Type>(Ty));
2754
2755 // And the name.
2756 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2757 llvm::Constant *TypeNameField;
2758
2759 // If we're supposed to demote the visibility, be sure to set a flag
2760 // to use a string comparison for type_info comparisons.
2761 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2762 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2763 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2764 // The flag is the sign bit, which on ARM64 is defined to be clear
2765 // for global pointers. This is very ARM64-specific.
2766 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2767 llvm::Constant *flag =
2768 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2769 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2770 TypeNameField =
2771 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2772 } else {
2773 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2774 }
2775 Fields.push_back(TypeNameField);
2776
2777 switch (Ty->getTypeClass()) {
2778#define TYPE(Class, Base)
2779#define ABSTRACT_TYPE(Class, Base)
2780#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2781#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2782#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2783#include "clang/AST/TypeNodes.def"
2784 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2785
2786 // GCC treats vector types as fundamental types.
2787 case Type::Builtin:
2788 case Type::Vector:
2789 case Type::ExtVector:
2790 case Type::Complex:
2791 case Type::BlockPointer:
2792 // Itanium C++ ABI 2.9.5p4:
2793 // abi::__fundamental_type_info adds no data members to std::type_info.
2794 break;
2795
2796 case Type::LValueReference:
2797 case Type::RValueReference:
2798 llvm_unreachable("References shouldn't get here");
2799
2800 case Type::Auto:
2801 llvm_unreachable("Undeduced auto type shouldn't get here");
2802
2803 case Type::ConstantArray:
2804 case Type::IncompleteArray:
2805 case Type::VariableArray:
2806 // Itanium C++ ABI 2.9.5p5:
2807 // abi::__array_type_info adds no data members to std::type_info.
2808 break;
2809
2810 case Type::FunctionNoProto:
2811 case Type::FunctionProto:
2812 // Itanium C++ ABI 2.9.5p5:
2813 // abi::__function_type_info adds no data members to std::type_info.
2814 break;
2815
2816 case Type::Enum:
2817 // Itanium C++ ABI 2.9.5p5:
2818 // abi::__enum_type_info adds no data members to std::type_info.
2819 break;
2820
2821 case Type::Record: {
2822 const CXXRecordDecl *RD =
2823 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2824 if (!RD->hasDefinition() || !RD->getNumBases()) {
2825 // We don't need to emit any fields.
2826 break;
2827 }
2828
2829 if (CanUseSingleInheritance(RD))
2830 BuildSIClassTypeInfo(RD);
2831 else
2832 BuildVMIClassTypeInfo(RD);
2833
2834 break;
2835 }
2836
2837 case Type::ObjCObject:
2838 case Type::ObjCInterface:
2839 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2840 break;
2841
2842 case Type::ObjCObjectPointer:
2843 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2844 break;
2845
2846 case Type::Pointer:
2847 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2848 break;
2849
2850 case Type::MemberPointer:
2851 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2852 break;
2853
2854 case Type::Atomic:
2855 // No fields, at least for the moment.
2856 break;
2857 }
2858
2859 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2860
Rafael Espindolacb92c192015-01-15 23:18:01 +00002861 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002862 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002863 new llvm::GlobalVariable(M, Init->getType(),
2864 /*Constant=*/true, Linkage, Init, Name);
2865
David Majnemere2cb8d12014-07-07 06:20:47 +00002866 // If there's already an old global variable, replace it with the new one.
2867 if (OldGV) {
2868 GV->takeName(OldGV);
2869 llvm::Constant *NewPtr =
2870 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2871 OldGV->replaceAllUsesWith(NewPtr);
2872 OldGV->eraseFromParent();
2873 }
2874
Yaron Keren04da2382015-07-29 15:42:28 +00002875 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2876 GV->setComdat(M.getOrInsertComdat(GV->getName()));
2877
David Majnemere2cb8d12014-07-07 06:20:47 +00002878 // The Itanium ABI specifies that type_info objects must be globally
2879 // unique, with one exception: if the type is an incomplete class
2880 // type or a (possibly indirect) pointer to one. That exception
2881 // affects the general case of comparing type_info objects produced
2882 // by the typeid operator, which is why the comparison operators on
2883 // std::type_info generally use the type_info name pointers instead
2884 // of the object addresses. However, the language's built-in uses
2885 // of RTTI generally require class types to be complete, even when
2886 // manipulating pointers to those class types. This allows the
2887 // implementation of dynamic_cast to rely on address equality tests,
2888 // which is much faster.
2889
2890 // All of this is to say that it's important that both the type_info
2891 // object and the type_info name be uniqued when weakly emitted.
2892
2893 // Give the type_info object and name the formal visibility of the
2894 // type itself.
2895 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2896 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2897 // If the linkage is local, only default visibility makes sense.
2898 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2899 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2900 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2901 else
2902 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2903 TypeName->setVisibility(llvmVisibility);
2904 GV->setVisibility(llvmVisibility);
2905
2906 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2907}
2908
2909/// ComputeQualifierFlags - Compute the pointer type info flags from the
2910/// given qualifier.
2911static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2912 unsigned Flags = 0;
2913
2914 if (Quals.hasConst())
2915 Flags |= ItaniumRTTIBuilder::PTI_Const;
2916 if (Quals.hasVolatile())
2917 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2918 if (Quals.hasRestrict())
2919 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2920
2921 return Flags;
2922}
2923
2924/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2925/// for the given Objective-C object type.
2926void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2927 // Drop qualifiers.
2928 const Type *T = OT->getBaseType().getTypePtr();
2929 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2930
2931 // The builtin types are abi::__class_type_infos and don't require
2932 // extra fields.
2933 if (isa<BuiltinType>(T)) return;
2934
2935 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2936 ObjCInterfaceDecl *Super = Class->getSuperClass();
2937
2938 // Root classes are also __class_type_info.
2939 if (!Super) return;
2940
2941 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2942
2943 // Everything else is single inheritance.
2944 llvm::Constant *BaseTypeInfo =
2945 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2946 Fields.push_back(BaseTypeInfo);
2947}
2948
2949/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2950/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2951void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2952 // Itanium C++ ABI 2.9.5p6b:
2953 // It adds to abi::__class_type_info a single member pointing to the
2954 // type_info structure for the base type,
2955 llvm::Constant *BaseTypeInfo =
2956 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2957 Fields.push_back(BaseTypeInfo);
2958}
2959
2960namespace {
2961 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2962 /// a class hierarchy.
2963 struct SeenBases {
2964 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2965 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2966 };
2967}
2968
2969/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2970/// abi::__vmi_class_type_info.
2971///
2972static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2973 SeenBases &Bases) {
2974
2975 unsigned Flags = 0;
2976
2977 const CXXRecordDecl *BaseDecl =
2978 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2979
2980 if (Base->isVirtual()) {
2981 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002982 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002983 // If this virtual base has been seen before, then the class is diamond
2984 // shaped.
2985 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2986 } else {
2987 if (Bases.NonVirtualBases.count(BaseDecl))
2988 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2989 }
2990 } else {
2991 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002992 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002993 // If this non-virtual base has been seen before, then the class has non-
2994 // diamond shaped repeated inheritance.
2995 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2996 } else {
2997 if (Bases.VirtualBases.count(BaseDecl))
2998 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2999 }
3000 }
3001
3002 // Walk all bases.
3003 for (const auto &I : BaseDecl->bases())
3004 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3005
3006 return Flags;
3007}
3008
3009static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3010 unsigned Flags = 0;
3011 SeenBases Bases;
3012
3013 // Walk all bases.
3014 for (const auto &I : RD->bases())
3015 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3016
3017 return Flags;
3018}
3019
3020/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3021/// classes with bases that do not satisfy the abi::__si_class_type_info
3022/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3023void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3024 llvm::Type *UnsignedIntLTy =
3025 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3026
3027 // Itanium C++ ABI 2.9.5p6c:
3028 // __flags is a word with flags describing details about the class
3029 // structure, which may be referenced by using the __flags_masks
3030 // enumeration. These flags refer to both direct and indirect bases.
3031 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3032 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3033
3034 // Itanium C++ ABI 2.9.5p6c:
3035 // __base_count is a word with the number of direct proper base class
3036 // descriptions that follow.
3037 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3038
3039 if (!RD->getNumBases())
3040 return;
3041
3042 llvm::Type *LongLTy =
3043 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3044
3045 // Now add the base class descriptions.
3046
3047 // Itanium C++ ABI 2.9.5p6c:
3048 // __base_info[] is an array of base class descriptions -- one for every
3049 // direct proper base. Each description is of the type:
3050 //
3051 // struct abi::__base_class_type_info {
3052 // public:
3053 // const __class_type_info *__base_type;
3054 // long __offset_flags;
3055 //
3056 // enum __offset_flags_masks {
3057 // __virtual_mask = 0x1,
3058 // __public_mask = 0x2,
3059 // __offset_shift = 8
3060 // };
3061 // };
3062 for (const auto &Base : RD->bases()) {
3063 // The __base_type member points to the RTTI for the base type.
3064 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3065
3066 const CXXRecordDecl *BaseDecl =
3067 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3068
3069 int64_t OffsetFlags = 0;
3070
3071 // All but the lower 8 bits of __offset_flags are a signed offset.
3072 // For a non-virtual base, this is the offset in the object of the base
3073 // subobject. For a virtual base, this is the offset in the virtual table of
3074 // the virtual base offset for the virtual base referenced (negative).
3075 CharUnits Offset;
3076 if (Base.isVirtual())
3077 Offset =
3078 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3079 else {
3080 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3081 Offset = Layout.getBaseClassOffset(BaseDecl);
3082 };
3083
3084 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3085
3086 // The low-order byte of __offset_flags contains flags, as given by the
3087 // masks from the enumeration __offset_flags_masks.
3088 if (Base.isVirtual())
3089 OffsetFlags |= BCTI_Virtual;
3090 if (Base.getAccessSpecifier() == AS_public)
3091 OffsetFlags |= BCTI_Public;
3092
3093 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3094 }
3095}
3096
3097/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3098/// used for pointer types.
3099void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3100 Qualifiers Quals;
3101 QualType UnqualifiedPointeeTy =
3102 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3103
3104 // Itanium C++ ABI 2.9.5p7:
3105 // __flags is a flag word describing the cv-qualification and other
3106 // attributes of the type pointed to
3107 unsigned Flags = ComputeQualifierFlags(Quals);
3108
3109 // Itanium C++ ABI 2.9.5p7:
3110 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3111 // incomplete class type, the incomplete target type flag is set.
3112 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3113 Flags |= PTI_Incomplete;
3114
3115 llvm::Type *UnsignedIntLTy =
3116 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3117 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3118
3119 // Itanium C++ ABI 2.9.5p7:
3120 // __pointee is a pointer to the std::type_info derivation for the
3121 // unqualified type being pointed to.
3122 llvm::Constant *PointeeTypeInfo =
3123 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3124 Fields.push_back(PointeeTypeInfo);
3125}
3126
3127/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3128/// struct, used for member pointer types.
3129void
3130ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3131 QualType PointeeTy = Ty->getPointeeType();
3132
3133 Qualifiers Quals;
3134 QualType UnqualifiedPointeeTy =
3135 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3136
3137 // Itanium C++ ABI 2.9.5p7:
3138 // __flags is a flag word describing the cv-qualification and other
3139 // attributes of the type pointed to.
3140 unsigned Flags = ComputeQualifierFlags(Quals);
3141
3142 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3143
3144 // Itanium C++ ABI 2.9.5p7:
3145 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3146 // incomplete class type, the incomplete target type flag is set.
3147 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3148 Flags |= PTI_Incomplete;
3149
3150 if (IsIncompleteClassType(ClassType))
3151 Flags |= PTI_ContainingClassIncomplete;
3152
3153 llvm::Type *UnsignedIntLTy =
3154 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3155 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3156
3157 // Itanium C++ ABI 2.9.5p7:
3158 // __pointee is a pointer to the std::type_info derivation for the
3159 // unqualified type being pointed to.
3160 llvm::Constant *PointeeTypeInfo =
3161 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3162 Fields.push_back(PointeeTypeInfo);
3163
3164 // Itanium C++ ABI 2.9.5p9:
3165 // __context is a pointer to an abi::__class_type_info corresponding to the
3166 // class type containing the member pointed to
3167 // (e.g., the "A" in "int A::*").
3168 Fields.push_back(
3169 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3170}
3171
David Majnemer443250f2015-03-17 20:35:00 +00003172llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003173 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3174}
3175
3176void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3177 QualType PointerType = getContext().getPointerType(Type);
3178 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3179 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3180 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3181 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3182}
3183
3184void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3185 QualType FundamentalTypes[] = {
3186 getContext().VoidTy, getContext().NullPtrTy,
3187 getContext().BoolTy, getContext().WCharTy,
3188 getContext().CharTy, getContext().UnsignedCharTy,
3189 getContext().SignedCharTy, getContext().ShortTy,
3190 getContext().UnsignedShortTy, getContext().IntTy,
3191 getContext().UnsignedIntTy, getContext().LongTy,
3192 getContext().UnsignedLongTy, getContext().LongLongTy,
3193 getContext().UnsignedLongLongTy, getContext().HalfTy,
3194 getContext().FloatTy, getContext().DoubleTy,
3195 getContext().LongDoubleTy, getContext().Char16Ty,
3196 getContext().Char32Ty,
3197 };
3198 for (const QualType &FundamentalType : FundamentalTypes)
3199 EmitFundamentalRTTIDescriptor(FundamentalType);
3200}
3201
3202/// What sort of uniqueness rules should we use for the RTTI for the
3203/// given type?
3204ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3205 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3206 if (shouldRTTIBeUnique())
3207 return RUK_Unique;
3208
3209 // It's only necessary for linkonce_odr or weak_odr linkage.
3210 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3211 Linkage != llvm::GlobalValue::WeakODRLinkage)
3212 return RUK_Unique;
3213
3214 // It's only necessary with default visibility.
3215 if (CanTy->getVisibility() != DefaultVisibility)
3216 return RUK_Unique;
3217
3218 // If we're not required to publish this symbol, hide it.
3219 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3220 return RUK_NonUniqueHidden;
3221
3222 // If we're required to publish this symbol, as we might be under an
3223 // explicit instantiation, leave it with default visibility but
3224 // enable string-comparisons.
3225 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3226 return RUK_NonUniqueVisible;
3227}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003228
Rafael Espindola1e4df922014-09-16 15:18:21 +00003229// Find out how to codegen the complete destructor and constructor
3230namespace {
3231enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3232}
3233static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3234 const CXXMethodDecl *MD) {
3235 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3236 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003237
Rafael Espindola1e4df922014-09-16 15:18:21 +00003238 // The complete and base structors are not equivalent if there are any virtual
3239 // bases, so emit separate functions.
3240 if (MD->getParent()->getNumVBases())
3241 return StructorCodegen::Emit;
3242
3243 GlobalDecl AliasDecl;
3244 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3245 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3246 } else {
3247 const auto *CD = cast<CXXConstructorDecl>(MD);
3248 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3249 }
3250 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3251
3252 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3253 return StructorCodegen::RAUW;
3254
3255 // FIXME: Should we allow available_externally aliases?
3256 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3257 return StructorCodegen::RAUW;
3258
Rafael Espindola0806f982014-09-16 20:19:43 +00003259 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3260 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3261 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3262 return StructorCodegen::COMDAT;
3263 return StructorCodegen::Emit;
3264 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003265
3266 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003267}
3268
Rafael Espindola1e4df922014-09-16 15:18:21 +00003269static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3270 GlobalDecl AliasDecl,
3271 GlobalDecl TargetDecl) {
3272 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3273
3274 StringRef MangledName = CGM.getMangledName(AliasDecl);
3275 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3276 if (Entry && !Entry->isDeclaration())
3277 return;
3278
3279 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3280 llvm::PointerType *AliasType = Aliasee->getType();
3281
3282 // Create the alias with no name.
David Blaikie881b2342015-04-29 21:22:47 +00003283 auto *Alias = llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee,
3284 &CGM.getModule());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003285
3286 // Switch any previous uses to the alias.
3287 if (Entry) {
3288 assert(Entry->getType() == AliasType &&
3289 "declaration exists with different type");
3290 Alias->takeName(Entry);
3291 Entry->replaceAllUsesWith(Alias);
3292 Entry->eraseFromParent();
3293 } else {
3294 Alias->setName(MangledName);
3295 }
3296
3297 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003298 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003299}
3300
3301void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3302 StructorType Type) {
3303 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3304 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3305
3306 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3307
3308 if (Type == StructorType::Complete) {
3309 GlobalDecl CompleteDecl;
3310 GlobalDecl BaseDecl;
3311 if (CD) {
3312 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3313 BaseDecl = GlobalDecl(CD, Ctor_Base);
3314 } else {
3315 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3316 BaseDecl = GlobalDecl(DD, Dtor_Base);
3317 }
3318
3319 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3320 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3321 return;
3322 }
3323
3324 if (CGType == StructorCodegen::RAUW) {
3325 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3326 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3327 CGM.addReplacement(MangledName, Aliasee);
3328 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003329 }
3330 }
3331
3332 // The base destructor is equivalent to the base destructor of its
3333 // base class if there is exactly one non-virtual base class with a
3334 // non-trivial destructor, there are no fields with a non-trivial
3335 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003336 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3337 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003338 return;
3339
Rafael Espindola1e4df922014-09-16 15:18:21 +00003340 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003341
Rafael Espindola1e4df922014-09-16 15:18:21 +00003342 if (CGType == StructorCodegen::COMDAT) {
3343 SmallString<256> Buffer;
3344 llvm::raw_svector_ostream Out(Buffer);
3345 if (DD)
3346 getMangleContext().mangleCXXDtorComdat(DD, Out);
3347 else
3348 getMangleContext().mangleCXXCtorComdat(CD, Out);
3349 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3350 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003351 } else {
3352 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003353 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003354}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003355
3356static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3357 // void *__cxa_begin_catch(void*);
3358 llvm::FunctionType *FTy = llvm::FunctionType::get(
3359 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3360
3361 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3362}
3363
3364static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3365 // void __cxa_end_catch();
3366 llvm::FunctionType *FTy =
3367 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3368
3369 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3370}
3371
3372static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3373 // void *__cxa_get_exception_ptr(void*);
3374 llvm::FunctionType *FTy = llvm::FunctionType::get(
3375 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3376
3377 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3378}
3379
3380namespace {
3381 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3382 /// exception type lets us state definitively that the thrown exception
3383 /// type does not have a destructor. In particular:
3384 /// - Catch-alls tell us nothing, so we have to conservatively
3385 /// assume that the thrown exception might have a destructor.
3386 /// - Catches by reference behave according to their base types.
3387 /// - Catches of non-record types will only trigger for exceptions
3388 /// of non-record types, which never have destructors.
3389 /// - Catches of record types can trigger for arbitrary subclasses
3390 /// of the caught type, so we have to assume the actual thrown
3391 /// exception type might have a throwing destructor, even if the
3392 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003393 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003394 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3395 bool MightThrow;
3396
3397 void Emit(CodeGenFunction &CGF, Flags flags) override {
3398 if (!MightThrow) {
3399 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3400 return;
3401 }
3402
3403 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3404 }
3405 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003406}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003407
3408/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3409/// __cxa_end_catch.
3410///
3411/// \param EndMightThrow - true if __cxa_end_catch might throw
3412static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3413 llvm::Value *Exn,
3414 bool EndMightThrow) {
3415 llvm::CallInst *call =
3416 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3417
3418 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3419
3420 return call;
3421}
3422
3423/// A "special initializer" callback for initializing a catch
3424/// parameter during catch initialization.
3425static void InitCatchParam(CodeGenFunction &CGF,
3426 const VarDecl &CatchParam,
3427 llvm::Value *ParamAddr,
3428 SourceLocation Loc) {
3429 // Load the exception from where the landing pad saved it.
3430 llvm::Value *Exn = CGF.getExceptionFromSlot();
3431
3432 CanQualType CatchType =
3433 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3434 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3435
3436 // If we're catching by reference, we can just cast the object
3437 // pointer to the appropriate pointer.
3438 if (isa<ReferenceType>(CatchType)) {
3439 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3440 bool EndCatchMightThrow = CaughtType->isRecordType();
3441
3442 // __cxa_begin_catch returns the adjusted object pointer.
3443 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3444
3445 // We have no way to tell the personality function that we're
3446 // catching by reference, so if we're catching a pointer,
3447 // __cxa_begin_catch will actually return that pointer by value.
3448 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3449 QualType PointeeType = PT->getPointeeType();
3450
3451 // When catching by reference, generally we should just ignore
3452 // this by-value pointer and use the exception object instead.
3453 if (!PointeeType->isRecordType()) {
3454
3455 // Exn points to the struct _Unwind_Exception header, which
3456 // we have to skip past in order to reach the exception data.
3457 unsigned HeaderSize =
3458 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3459 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3460
3461 // However, if we're catching a pointer-to-record type that won't
3462 // work, because the personality function might have adjusted
3463 // the pointer. There's actually no way for us to fully satisfy
3464 // the language/ABI contract here: we can't use Exn because it
3465 // might have the wrong adjustment, but we can't use the by-value
3466 // pointer because it's off by a level of abstraction.
3467 //
3468 // The current solution is to dump the adjusted pointer into an
3469 // alloca, which breaks language semantics (because changing the
3470 // pointer doesn't change the exception) but at least works.
3471 // The better solution would be to filter out non-exact matches
3472 // and rethrow them, but this is tricky because the rethrow
3473 // really needs to be catchable by other sites at this landing
3474 // pad. The best solution is to fix the personality function.
3475 } else {
3476 // Pull the pointer for the reference type off.
3477 llvm::Type *PtrTy =
3478 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3479
3480 // Create the temporary and write the adjusted pointer into it.
3481 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3482 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3483 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3484
3485 // Bind the reference to the temporary.
3486 AdjustedExn = ExnPtrTmp;
3487 }
3488 }
3489
3490 llvm::Value *ExnCast =
3491 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3492 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3493 return;
3494 }
3495
3496 // Scalars and complexes.
3497 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3498 if (TEK != TEK_Aggregate) {
3499 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3500
3501 // If the catch type is a pointer type, __cxa_begin_catch returns
3502 // the pointer by value.
3503 if (CatchType->hasPointerRepresentation()) {
3504 llvm::Value *CastExn =
3505 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3506
3507 switch (CatchType.getQualifiers().getObjCLifetime()) {
3508 case Qualifiers::OCL_Strong:
3509 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3510 // fallthrough
3511
3512 case Qualifiers::OCL_None:
3513 case Qualifiers::OCL_ExplicitNone:
3514 case Qualifiers::OCL_Autoreleasing:
3515 CGF.Builder.CreateStore(CastExn, ParamAddr);
3516 return;
3517
3518 case Qualifiers::OCL_Weak:
3519 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3520 return;
3521 }
3522 llvm_unreachable("bad ownership qualifier!");
3523 }
3524
3525 // Otherwise, it returns a pointer into the exception object.
3526
3527 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3528 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3529
3530 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3531 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3532 CGF.getContext().getDeclAlign(&CatchParam));
3533 switch (TEK) {
3534 case TEK_Complex:
3535 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3536 /*init*/ true);
3537 return;
3538 case TEK_Scalar: {
3539 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3540 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3541 return;
3542 }
3543 case TEK_Aggregate:
3544 llvm_unreachable("evaluation kind filtered out!");
3545 }
3546 llvm_unreachable("bad evaluation kind");
3547 }
3548
3549 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3550
3551 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3552
3553 // Check for a copy expression. If we don't have a copy expression,
3554 // that means a trivial copy is okay.
3555 const Expr *copyExpr = CatchParam.getInit();
3556 if (!copyExpr) {
3557 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3558 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3559 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3560 return;
3561 }
3562
3563 // We have to call __cxa_get_exception_ptr to get the adjusted
3564 // pointer before copying.
3565 llvm::CallInst *rawAdjustedExn =
3566 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3567
3568 // Cast that to the appropriate type.
3569 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3570
3571 // The copy expression is defined in terms of an OpaqueValueExpr.
3572 // Find it and map it to the adjusted expression.
3573 CodeGenFunction::OpaqueValueMapping
3574 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3575 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3576
3577 // Call the copy ctor in a terminate scope.
3578 CGF.EHStack.pushTerminate();
3579
3580 // Perform the copy construction.
3581 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3582 CGF.EmitAggExpr(copyExpr,
3583 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3584 AggValueSlot::IsNotDestructed,
3585 AggValueSlot::DoesNotNeedGCBarriers,
3586 AggValueSlot::IsNotAliased));
3587
3588 // Leave the terminate scope.
3589 CGF.EHStack.popTerminate();
3590
3591 // Undo the opaque value mapping.
3592 opaque.pop();
3593
3594 // Finally we can call __cxa_begin_catch.
3595 CallBeginCatch(CGF, Exn, true);
3596}
3597
3598/// Begins a catch statement by initializing the catch variable and
3599/// calling __cxa_begin_catch.
3600void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3601 const CXXCatchStmt *S) {
3602 // We have to be very careful with the ordering of cleanups here:
3603 // C++ [except.throw]p4:
3604 // The destruction [of the exception temporary] occurs
3605 // immediately after the destruction of the object declared in
3606 // the exception-declaration in the handler.
3607 //
3608 // So the precise ordering is:
3609 // 1. Construct catch variable.
3610 // 2. __cxa_begin_catch
3611 // 3. Enter __cxa_end_catch cleanup
3612 // 4. Enter dtor cleanup
3613 //
3614 // We do this by using a slightly abnormal initialization process.
3615 // Delegation sequence:
3616 // - ExitCXXTryStmt opens a RunCleanupsScope
3617 // - EmitAutoVarAlloca creates the variable and debug info
3618 // - InitCatchParam initializes the variable from the exception
3619 // - CallBeginCatch calls __cxa_begin_catch
3620 // - CallBeginCatch enters the __cxa_end_catch cleanup
3621 // - EmitAutoVarCleanups enters the variable destructor cleanup
3622 // - EmitCXXTryStmt emits the code for the catch body
3623 // - EmitCXXTryStmt close the RunCleanupsScope
3624
3625 VarDecl *CatchParam = S->getExceptionDecl();
3626 if (!CatchParam) {
3627 llvm::Value *Exn = CGF.getExceptionFromSlot();
3628 CallBeginCatch(CGF, Exn, true);
3629 return;
3630 }
3631
3632 // Emit the local.
3633 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3634 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3635 CGF.EmitAutoVarCleanups(var);
3636}
3637
3638/// Get or define the following function:
3639/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3640/// This code is used only in C++.
3641static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3642 llvm::FunctionType *fnTy =
3643 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3644 llvm::Constant *fnRef =
3645 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3646
3647 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3648 if (fn && fn->empty()) {
3649 fn->setDoesNotThrow();
3650 fn->setDoesNotReturn();
3651
3652 // What we really want is to massively penalize inlining without
3653 // forbidding it completely. The difference between that and
3654 // 'noinline' is negligible.
3655 fn->addFnAttr(llvm::Attribute::NoInline);
3656
3657 // Allow this function to be shared across translation units, but
3658 // we don't want it to turn into an exported symbol.
3659 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3660 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003661 if (CGM.supportsCOMDAT())
3662 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003663
3664 // Set up the function.
3665 llvm::BasicBlock *entry =
3666 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3667 CGBuilderTy builder(entry);
3668
3669 // Pull the exception pointer out of the parameter list.
3670 llvm::Value *exn = &*fn->arg_begin();
3671
3672 // Call __cxa_begin_catch(exn).
3673 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3674 catchCall->setDoesNotThrow();
3675 catchCall->setCallingConv(CGM.getRuntimeCC());
3676
3677 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003678 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003679 termCall->setDoesNotThrow();
3680 termCall->setDoesNotReturn();
3681 termCall->setCallingConv(CGM.getRuntimeCC());
3682
3683 // std::terminate cannot return.
3684 builder.CreateUnreachable();
3685 }
3686
3687 return fnRef;
3688}
3689
3690llvm::CallInst *
3691ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3692 llvm::Value *Exn) {
3693 // In C++, we want to call __cxa_begin_catch() before terminating.
3694 if (Exn) {
3695 assert(CGF.CGM.getLangOpts().CPlusPlus);
3696 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3697 }
3698 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3699}