blob: ce37a7fbe0bbf37b1713df9d2cd3146a064926fa [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 Padlewskia68a7872015-07-24 04:04:49 +0000232 bool canEmitAvailableExternallyVTable(const CXXRecordDecl *RD) const override;
233
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 Padlewskia68a7872015-07-24 04:04:49 +00001526bool ItaniumCXXABI::canEmitAvailableExternallyVTable(
1527 const CXXRecordDecl *RD) const {
1528 // We don't emit available_externally vtables if we are in -fapple-kext mode
1529 // because kext mode does not permit devirtualization.
1530 if (CGM.getLangOpts().AppleKext)
1531 return false;
1532
1533 // If we don't have any inline virtual functions,
1534 // then we are safe to emit available_externally copy of vtable.
1535 // FIXME we can still emit a copy of the vtable if we
1536 // can emit definition of the inline functions.
Piotr Padlewski1d02f682015-08-19 20:09:09 +00001537 return !hasAnyUsedVirtualInlineFunction(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001538}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001539static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1540 llvm::Value *Ptr,
1541 int64_t NonVirtualAdjustment,
1542 int64_t VirtualAdjustment,
1543 bool IsReturnAdjustment) {
1544 if (!NonVirtualAdjustment && !VirtualAdjustment)
1545 return Ptr;
1546
1547 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1548 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1549
1550 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1551 // Perform the non-virtual adjustment for a base-to-derived cast.
1552 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1553 }
1554
1555 if (VirtualAdjustment) {
1556 llvm::Type *PtrDiffTy =
1557 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1558
1559 // Perform the virtual adjustment.
1560 llvm::Value *VTablePtrPtr =
1561 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1562
1563 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1564
1565 llvm::Value *OffsetPtr =
1566 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1567
1568 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1569
1570 // Load the adjustment offset from the vtable.
1571 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1572
1573 // Adjust our pointer.
1574 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1575 }
1576
1577 if (NonVirtualAdjustment && IsReturnAdjustment) {
1578 // Perform the non-virtual adjustment for a derived-to-base cast.
1579 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1580 }
1581
1582 // Cast back to the original type.
1583 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1584}
1585
1586llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1587 llvm::Value *This,
1588 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001589 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1590 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001591 /*IsReturnAdjustment=*/false);
1592}
1593
1594llvm::Value *
1595ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1596 const ReturnAdjustment &RA) {
1597 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1598 RA.Virtual.Itanium.VBaseOffsetOffset,
1599 /*IsReturnAdjustment=*/true);
1600}
1601
John McCall5d865c322010-08-31 07:33:07 +00001602void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1603 RValue RV, QualType ResultType) {
1604 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1605 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1606
1607 // Destructor thunks in the ARM ABI have indeterminate results.
Chris Lattner2192fe52011-07-18 04:24:23 +00001608 llvm::Type *T =
John McCall5d865c322010-08-31 07:33:07 +00001609 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1610 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1611 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1612}
John McCall8ed55a52010-09-02 09:58:18 +00001613
1614/************************** Array allocation cookies **************************/
1615
John McCallb91cd662012-05-01 05:23:51 +00001616CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1617 // The array cookie is a size_t; pad that up to the element alignment.
1618 // The cookie is actually right-justified in that space.
1619 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1620 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001621}
1622
1623llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1624 llvm::Value *NewPtr,
1625 llvm::Value *NumElements,
John McCall284c48f2011-01-27 09:37:56 +00001626 const CXXNewExpr *expr,
John McCall8ed55a52010-09-02 09:58:18 +00001627 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001628 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001629
Micah Villmowea2fea22012-10-25 15:39:14 +00001630 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001631
John McCall9bca9232010-09-02 10:25:57 +00001632 ASTContext &Ctx = getContext();
John McCall8ed55a52010-09-02 09:58:18 +00001633 QualType SizeTy = Ctx.getSizeType();
1634 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1635
1636 // The size of the cookie.
1637 CharUnits CookieSize =
1638 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001639 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001640
1641 // Compute an offset to the cookie.
1642 llvm::Value *CookiePtr = NewPtr;
1643 CharUnits CookieOffset = CookieSize - SizeSize;
1644 if (!CookieOffset.isZero())
1645 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1646 CookieOffset.getQuantity());
1647
1648 // Write the number of elements into the appropriate slot.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001649 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1650 llvm::Value *NumElementsPtr =
1651 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1652 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001653 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001654 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001655 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001656 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1657 llvm::FunctionType *FTy =
1658 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1659 llvm::Constant *F =
1660 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1661 CGF.Builder.CreateCall(F, NumElementsPtr);
1662 }
John McCall8ed55a52010-09-02 09:58:18 +00001663
1664 // Finally, compute a pointer to the actual data buffer by skipping
1665 // over the cookie completely.
1666 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1667 CookieSize.getQuantity());
1668}
1669
John McCallb91cd662012-05-01 05:23:51 +00001670llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1671 llvm::Value *allocPtr,
1672 CharUnits cookieSize) {
1673 // The element size is right-justified in the cookie.
1674 llvm::Value *numElementsPtr = allocPtr;
1675 CharUnits numElementsOffset =
1676 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1677 if (!numElementsOffset.isZero())
1678 numElementsPtr =
1679 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1680 numElementsOffset.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001681
Micah Villmowea2fea22012-10-25 15:39:14 +00001682 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001683 numElementsPtr =
1684 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001685 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001686 return CGF.Builder.CreateLoad(numElementsPtr);
1687 // In asan mode emit a function call instead of a regular load and let the
1688 // run-time deal with it: if the shadow is properly poisoned return the
1689 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1690 // We can't simply ignore this load using nosanitize metadata because
1691 // the metadata may be lost.
1692 llvm::FunctionType *FTy =
1693 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1694 llvm::Constant *F =
1695 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1696 return CGF.Builder.CreateCall(F, numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001697}
1698
John McCallb91cd662012-05-01 05:23:51 +00001699CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001700 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001701 // struct array_cookie {
1702 // std::size_t element_size; // element_size != 0
1703 // std::size_t element_count;
1704 // };
John McCallc19c7062013-01-25 23:36:19 +00001705 // But the base ABI doesn't give anything an alignment greater than
1706 // 8, so we can dismiss this as typical ABI-author blindness to
1707 // actual language complexity and round up to the element alignment.
1708 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1709 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001710}
1711
1712llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
John McCallc19c7062013-01-25 23:36:19 +00001713 llvm::Value *newPtr,
1714 llvm::Value *numElements,
John McCall284c48f2011-01-27 09:37:56 +00001715 const CXXNewExpr *expr,
John McCallc19c7062013-01-25 23:36:19 +00001716 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001717 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001718
John McCallc19c7062013-01-25 23:36:19 +00001719 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1720 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001721
1722 // The cookie is always at the start of the buffer.
John McCallc19c7062013-01-25 23:36:19 +00001723 llvm::Value *cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001724
1725 // The first element is the element size.
John McCallc19c7062013-01-25 23:36:19 +00001726 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1727 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1728 getContext().getTypeSizeInChars(elementType).getQuantity());
1729 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001730
1731 // The second element is the element count.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001732 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.SizeTy, cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00001733 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001734
1735 // Finally, compute a pointer to the actual data buffer by skipping
1736 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001737 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1738 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1739 cookieSize.getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +00001740}
1741
John McCallb91cd662012-05-01 05:23:51 +00001742llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1743 llvm::Value *allocPtr,
1744 CharUnits cookieSize) {
1745 // The number of elements is at offset sizeof(size_t) relative to
1746 // the allocated pointer.
1747 llvm::Value *numElementsPtr
1748 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
John McCall8ed55a52010-09-02 09:58:18 +00001749
Micah Villmowea2fea22012-10-25 15:39:14 +00001750 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001751 numElementsPtr =
1752 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1753 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001754}
1755
John McCall68ff0372010-09-08 01:44:27 +00001756/*********************** Static local initialization **************************/
1757
1758static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001759 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001760 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001761 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001762 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001763 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001764 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001765 llvm::AttributeSet::get(CGM.getLLVMContext(),
1766 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001767 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001768}
1769
1770static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001771 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001772 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001773 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001774 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001775 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001776 llvm::AttributeSet::get(CGM.getLLVMContext(),
1777 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001778 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001779}
1780
1781static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001782 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001783 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001784 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001785 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001786 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001787 llvm::AttributeSet::get(CGM.getLLVMContext(),
1788 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001789 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001790}
1791
1792namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001793 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001794 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001795 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001796
Craig Topper4f12f102014-03-12 06:41:41 +00001797 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001798 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1799 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001800 }
1801 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001802}
John McCall68ff0372010-09-08 01:44:27 +00001803
1804/// The ARM code here follows the Itanium code closely enough that we
1805/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001806void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1807 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001808 llvm::GlobalVariable *var,
1809 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001810 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001811
Richard Smithdbf74ba2013-04-14 23:01:42 +00001812 // We only need to use thread-safe statics for local non-TLS variables;
John McCallcdf7ef52010-11-06 09:44:32 +00001813 // global initialization is always single-threaded.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001814 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1815 D.isLocalVarDecl() && !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001816
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001817 // If we have a global variable with internal linkage and thread-safe statics
1818 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001819 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1820
1821 llvm::IntegerType *guardTy;
John McCall5aa52592011-06-17 07:33:57 +00001822 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001823 guardTy = CGF.Int8Ty;
John McCall5aa52592011-06-17 07:33:57 +00001824 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001825 // Guard variables are 64 bits in the generic ABI and size width on ARM
1826 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
Mark Seabornedf0d382013-07-24 16:25:13 +00001827 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001828 }
John McCallb88a5662012-03-30 21:00:39 +00001829 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001830
John McCallb88a5662012-03-30 21:00:39 +00001831 // Create the guard variable if we don't already have it (as we
1832 // might if we're double-emitting this function body).
1833 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1834 if (!guard) {
1835 // Mangle the name for the guard.
1836 SmallString<256> guardName;
1837 {
1838 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00001839 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00001840 }
John McCall8e7cb6d2010-11-02 21:04:24 +00001841
John McCallb88a5662012-03-30 21:00:39 +00001842 // Create the guard variable with a zero-initializer.
1843 // Just absorb linkage and visibility from the guarded variable.
1844 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1845 false, var->getLinkage(),
1846 llvm::ConstantInt::get(guardTy, 0),
1847 guardName.str());
1848 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00001849 // If the variable is thread-local, so is its guard variable.
1850 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCallb88a5662012-03-30 21:00:39 +00001851
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001852 // The ABI says: It is suggested that it be emitted in the same COMDAT group
1853 // as the associated data object
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001854 llvm::Comdat *C = var->getComdat();
1855 if (!D.isLocalVarDecl() && C) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001856 guard->setComdat(C);
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001857 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001858 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1859 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00001860 }
1861
John McCallb88a5662012-03-30 21:00:39 +00001862 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1863 }
John McCall87590e62012-03-30 07:09:50 +00001864
John McCall68ff0372010-09-08 01:44:27 +00001865 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001866 //
John McCall68ff0372010-09-08 01:44:27 +00001867 // Itanium C++ ABI 3.3.2:
1868 // The following is pseudo-code showing how these functions can be used:
1869 // if (obj_guard.first_byte == 0) {
1870 // if ( __cxa_guard_acquire (&obj_guard) ) {
1871 // try {
1872 // ... initialize the object ...;
1873 // } catch (...) {
1874 // __cxa_guard_abort (&obj_guard);
1875 // throw;
1876 // }
1877 // ... queue object destructor with __cxa_atexit() ...;
1878 // __cxa_guard_release (&obj_guard);
1879 // }
1880 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00001881
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001882 // Load the first byte of the guard variable.
1883 llvm::LoadInst *LI =
John McCallb88a5662012-03-30 21:00:39 +00001884 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001885 LI->setAlignment(1);
John McCall68ff0372010-09-08 01:44:27 +00001886
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001887 // Itanium ABI:
1888 // An implementation supporting thread-safety on multiprocessor
1889 // systems must also guarantee that references to the initialized
1890 // object do not occur before the load of the initialization flag.
1891 //
1892 // In LLVM, we do this by marking the load Acquire.
1893 if (threadsafe)
1894 LI->setAtomic(llvm::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00001895
Justin Bogner0cbb6d82014-04-23 01:50:10 +00001896 // For ARM, we should only check the first bit, rather than the entire byte:
1897 //
1898 // ARM C++ ABI 3.2.3.1:
1899 // To support the potential use of initialization guard variables
1900 // as semaphores that are the target of ARM SWP and LDREX/STREX
1901 // synchronizing instructions we define a static initialization
1902 // guard variable to be a 4-byte aligned, 4-byte word with the
1903 // following inline access protocol.
1904 // #define INITIALIZED 1
1905 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1906 // if (__cxa_guard_acquire(&obj_guard))
1907 // ...
1908 // }
1909 //
1910 // and similarly for ARM64:
1911 //
1912 // ARM64 C++ ABI 3.2.2:
1913 // This ABI instead only specifies the value bit 0 of the static guard
1914 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
1915 // variable is not initialized and 1 when it is.
1916 llvm::Value *V =
1917 (UseARMGuardVarABI && !useInt8GuardVariable)
1918 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1919 : LI;
1920 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00001921
1922 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1923 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1924
1925 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00001926 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00001927
1928 CGF.EmitBlock(InitCheckBlock);
1929
1930 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00001931 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001932 // Call __cxa_guard_acquire.
1933 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00001934 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001935
1936 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1937
1938 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1939 InitBlock, EndBlock);
1940
1941 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00001942 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00001943
1944 CGF.EmitBlock(InitBlock);
1945 }
1946
1947 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00001948 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00001949
John McCall5aa52592011-06-17 07:33:57 +00001950 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00001951 // Pop the guard-abort cleanup if we pushed one.
1952 CGF.PopCleanupBlock();
1953
1954 // Call __cxa_guard_release. This cannot throw.
John McCall882987f2013-02-28 19:01:20 +00001955 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00001956 } else {
John McCallb88a5662012-03-30 21:00:39 +00001957 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
John McCall68ff0372010-09-08 01:44:27 +00001958 }
1959
1960 CGF.EmitBlock(EndBlock);
1961}
John McCallc84ed6a2012-05-01 06:13:13 +00001962
1963/// Register a global destructor using __cxa_atexit.
1964static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1965 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00001966 llvm::Constant *addr,
1967 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00001968 const char *Name = "__cxa_atexit";
1969 if (TLS) {
1970 const llvm::Triple &T = CGF.getTarget().getTriple();
1971 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1972 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00001973
John McCallc84ed6a2012-05-01 06:13:13 +00001974 // We're assuming that the destructor function is something we can
1975 // reasonably call with the default CC. Go ahead and cast it to the
1976 // right prototype.
1977 llvm::Type *dtorTy =
1978 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1979
1980 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1981 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1982 llvm::FunctionType *atexitTy =
1983 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1984
1985 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001986 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00001987 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1988 fn->setDoesNotThrow();
1989
1990 // Create a variable that binds the atexit to this shared object.
1991 llvm::Constant *handle =
1992 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1993
1994 llvm::Value *args[] = {
1995 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1996 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1997 handle
1998 };
John McCall882987f2013-02-28 19:01:20 +00001999 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002000}
2001
2002/// Register a global destructor as best as we know how.
2003void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002004 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002005 llvm::Constant *dtor,
2006 llvm::Constant *addr) {
2007 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002008 if (CGM.getCodeGenOpts().CXAAtExit)
2009 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2010
2011 if (D.getTLSKind())
2012 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002013
2014 // In Apple kexts, we want to add a global destructor entry.
2015 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002016 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002017 // Generate a global destructor entry.
2018 return CGM.AddCXXDtorEntry(dtor, addr);
2019 }
2020
David Blaikieebe87e12013-08-27 23:57:18 +00002021 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002022}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002023
David Majnemer9b21c332014-07-11 20:28:10 +00002024static bool isThreadWrapperReplaceable(const VarDecl *VD,
2025 CodeGen::CodeGenModule &CGM) {
2026 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2027 // OS X prefers to have references to thread local variables to go through
2028 // the thread wrapper instead of directly referencing the backing variable.
2029 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2030 CGM.getTarget().getTriple().isMacOSX();
2031}
2032
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002033/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002034/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002035/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002036static llvm::GlobalValue::LinkageTypes
2037getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2038 llvm::GlobalValue::LinkageTypes VarLinkage =
2039 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2040
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002041 // For internal linkage variables, we don't need an external or weak wrapper.
2042 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2043 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002044
David Majnemer9b21c332014-07-11 20:28:10 +00002045 // If the thread wrapper is replaceable, give it appropriate linkage.
2046 if (isThreadWrapperReplaceable(VD, CGM)) {
2047 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
2048 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2049 return llvm::GlobalVariable::WeakAnyLinkage;
2050 return VarLinkage;
2051 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002052 return llvm::GlobalValue::WeakODRLinkage;
2053}
2054
2055llvm::Function *
2056ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002057 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002058 // Mangle the name for the thread_local wrapper function.
2059 SmallString<256> WrapperName;
2060 {
2061 llvm::raw_svector_ostream Out(WrapperName);
2062 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002063 }
2064
Alexander Musmanf94c3182014-09-26 06:28:25 +00002065 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002066 return cast<llvm::Function>(V);
2067
Alexander Musmanf94c3182014-09-26 06:28:25 +00002068 llvm::Type *RetTy = Val->getType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002069 if (VD->getType()->isReferenceType())
2070 RetTy = RetTy->getPointerElementType();
2071
2072 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
David Majnemer35ab3282014-06-11 04:08:55 +00002073 llvm::Function *Wrapper =
2074 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2075 WrapperName.str(), &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002076 // Always resolve references to the wrapper at link time.
David Majnemer9b21c332014-07-11 20:28:10 +00002077 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002078 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002079 return Wrapper;
2080}
2081
2082void ItaniumCXXABI::EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +00002083 CodeGenModule &CGM,
2084 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2085 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
2086 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2087 llvm::Function *InitFunc = nullptr;
2088 if (!CXXThreadLocalInits.empty()) {
2089 // Generate a guarded initialization function.
2090 llvm::FunctionType *FTy =
2091 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2092 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002093 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002094 /*TLS=*/true);
2095 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2096 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2097 llvm::GlobalVariable::InternalLinkage,
2098 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2099 Guard->setThreadLocal(true);
2100 CodeGenFunction(CGM)
2101 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
2102 }
Yaron Kerenede60302015-08-01 19:11:36 +00002103 for (auto &I : CXXThreadLocals) {
2104 const VarDecl *VD = I.first;
2105 llvm::GlobalVariable *Var = I.second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002106
David Majnemer9b21c332014-07-11 20:28:10 +00002107 // Some targets require that all access to thread local variables go through
2108 // the thread wrapper. This means that we cannot attempt to create a thread
2109 // wrapper or a thread helper.
2110 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2111 continue;
2112
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002113 // Mangle the name for the thread_local initialization function.
2114 SmallString<256> InitFnName;
2115 {
2116 llvm::raw_svector_ostream Out(InitFnName);
2117 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002118 }
2119
2120 // If we have a definition for the variable, emit the initialization
2121 // function as an alias to the global Init function (if any). Otherwise,
2122 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002123 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002124 bool InitIsInitFunc = false;
2125 if (VD->hasDefinition()) {
2126 InitIsInitFunc = true;
2127 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002128 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2129 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002130 } else {
2131 // Emit a weak global function referring to the initialization function.
2132 // This function will not exist if the TU defining the thread_local
2133 // variable in question does not need any dynamic initialization for
2134 // its thread_local variables.
2135 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2136 Init = llvm::Function::Create(
2137 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2138 &CGM.getModule());
2139 }
2140
2141 if (Init)
2142 Init->setVisibility(Var->getVisibility());
2143
2144 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2145 llvm::LLVMContext &Context = CGM.getModule().getContext();
2146 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2147 CGBuilderTy Builder(Entry);
2148 if (InitIsInitFunc) {
2149 if (Init)
David Blaikie4ba525b2015-07-14 17:27:39 +00002150 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002151 } else {
2152 // Don't know whether we have an init function. Call it if it exists.
2153 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2154 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2155 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2156 Builder.CreateCondBr(Have, InitBB, ExitBB);
2157
2158 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002159 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002160 Builder.CreateBr(ExitBB);
2161
2162 Builder.SetInsertPoint(ExitBB);
2163 }
2164
2165 // For a reference, the result of the wrapper function is a pointer to
2166 // the referenced object.
2167 llvm::Value *Val = Var;
2168 if (VD->getType()->isReferenceType()) {
2169 llvm::LoadInst *LI = Builder.CreateLoad(Val);
2170 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
2171 Val = LI;
2172 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002173 if (Val->getType() != Wrapper->getReturnType())
2174 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2175 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002176 Builder.CreateRet(Val);
2177 }
2178}
2179
Richard Smith0f383742014-03-26 22:48:22 +00002180LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2181 const VarDecl *VD,
2182 QualType LValType) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002183 QualType T = VD->getType();
2184 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
2185 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002186 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002187
David Blaikie4ba525b2015-07-14 17:27:39 +00002188 Val = CGF.Builder.CreateCall(Wrapper);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002189
2190 LValue LV;
2191 if (VD->getType()->isReferenceType())
Richard Smith0f383742014-03-26 22:48:22 +00002192 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002193 else
Richard Smith0f383742014-03-26 22:48:22 +00002194 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002195 // FIXME: need setObjCGCLValueClass?
2196 return LV;
2197}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002198
2199/// Return whether the given global decl needs a VTT parameter, which it does
2200/// if it's a base constructor or destructor with virtual bases.
2201bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2202 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2203
2204 // We don't have any virtual bases, just return early.
2205 if (!MD->getParent()->getNumVBases())
2206 return false;
2207
2208 // Check if we have a base constructor.
2209 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2210 return true;
2211
2212 // Check if we have a base destructor.
2213 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2214 return true;
2215
2216 return false;
2217}
David Majnemere2cb8d12014-07-07 06:20:47 +00002218
2219namespace {
2220class ItaniumRTTIBuilder {
2221 CodeGenModule &CGM; // Per-module state.
2222 llvm::LLVMContext &VMContext;
2223 const ItaniumCXXABI &CXXABI; // Per-module state.
2224
2225 /// Fields - The fields of the RTTI descriptor currently being built.
2226 SmallVector<llvm::Constant *, 16> Fields;
2227
2228 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2229 llvm::GlobalVariable *
2230 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2231
2232 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2233 /// descriptor of the given type.
2234 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2235
2236 /// BuildVTablePointer - Build the vtable pointer for the given type.
2237 void BuildVTablePointer(const Type *Ty);
2238
2239 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2240 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2241 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2242
2243 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2244 /// classes with bases that do not satisfy the abi::__si_class_type_info
2245 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2246 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2247
2248 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2249 /// for pointer types.
2250 void BuildPointerTypeInfo(QualType PointeeTy);
2251
2252 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2253 /// type_info for an object type.
2254 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2255
2256 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2257 /// struct, used for member pointer types.
2258 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2259
2260public:
2261 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2262 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2263
2264 // Pointer type info flags.
2265 enum {
2266 /// PTI_Const - Type has const qualifier.
2267 PTI_Const = 0x1,
2268
2269 /// PTI_Volatile - Type has volatile qualifier.
2270 PTI_Volatile = 0x2,
2271
2272 /// PTI_Restrict - Type has restrict qualifier.
2273 PTI_Restrict = 0x4,
2274
2275 /// PTI_Incomplete - Type is incomplete.
2276 PTI_Incomplete = 0x8,
2277
2278 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2279 /// (in pointer to member).
2280 PTI_ContainingClassIncomplete = 0x10
2281 };
2282
2283 // VMI type info flags.
2284 enum {
2285 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2286 VMI_NonDiamondRepeat = 0x1,
2287
2288 /// VMI_DiamondShaped - Class is diamond shaped.
2289 VMI_DiamondShaped = 0x2
2290 };
2291
2292 // Base class type info flags.
2293 enum {
2294 /// BCTI_Virtual - Base class is virtual.
2295 BCTI_Virtual = 0x1,
2296
2297 /// BCTI_Public - Base class is public.
2298 BCTI_Public = 0x2
2299 };
2300
2301 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2302 ///
2303 /// \param Force - true to force the creation of this RTTI value
2304 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2305};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002306}
David Majnemere2cb8d12014-07-07 06:20:47 +00002307
2308llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2309 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002310 SmallString<256> Name;
2311 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002312 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002313
2314 // We know that the mangled name of the type starts at index 4 of the
2315 // mangled name of the typename, so we can just index into it in order to
2316 // get the mangled name of the type.
2317 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2318 Name.substr(4));
2319
2320 llvm::GlobalVariable *GV =
2321 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2322
2323 GV->setInitializer(Init);
2324
2325 return GV;
2326}
2327
2328llvm::Constant *
2329ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2330 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002331 SmallString<256> Name;
2332 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002333 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002334
2335 // Look for an existing global.
2336 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2337
2338 if (!GV) {
2339 // Create a new global variable.
2340 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2341 /*Constant=*/true,
2342 llvm::GlobalValue::ExternalLinkage, nullptr,
2343 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002344 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2345 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2346 if (RD->hasAttr<DLLImportAttr>())
2347 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2348 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002349 }
2350
2351 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2352}
2353
2354/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2355/// info for that type is defined in the standard library.
2356static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2357 // Itanium C++ ABI 2.9.2:
2358 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2359 // the run-time support library. Specifically, the run-time support
2360 // library should contain type_info objects for the types X, X* and
2361 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2362 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2363 // long, unsigned long, long long, unsigned long long, float, double,
2364 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2365 // half-precision floating point types.
2366 switch (Ty->getKind()) {
2367 case BuiltinType::Void:
2368 case BuiltinType::NullPtr:
2369 case BuiltinType::Bool:
2370 case BuiltinType::WChar_S:
2371 case BuiltinType::WChar_U:
2372 case BuiltinType::Char_U:
2373 case BuiltinType::Char_S:
2374 case BuiltinType::UChar:
2375 case BuiltinType::SChar:
2376 case BuiltinType::Short:
2377 case BuiltinType::UShort:
2378 case BuiltinType::Int:
2379 case BuiltinType::UInt:
2380 case BuiltinType::Long:
2381 case BuiltinType::ULong:
2382 case BuiltinType::LongLong:
2383 case BuiltinType::ULongLong:
2384 case BuiltinType::Half:
2385 case BuiltinType::Float:
2386 case BuiltinType::Double:
2387 case BuiltinType::LongDouble:
2388 case BuiltinType::Char16:
2389 case BuiltinType::Char32:
2390 case BuiltinType::Int128:
2391 case BuiltinType::UInt128:
2392 case BuiltinType::OCLImage1d:
2393 case BuiltinType::OCLImage1dArray:
2394 case BuiltinType::OCLImage1dBuffer:
2395 case BuiltinType::OCLImage2d:
2396 case BuiltinType::OCLImage2dArray:
2397 case BuiltinType::OCLImage3d:
2398 case BuiltinType::OCLSampler:
2399 case BuiltinType::OCLEvent:
2400 return true;
2401
2402 case BuiltinType::Dependent:
2403#define BUILTIN_TYPE(Id, SingletonId)
2404#define PLACEHOLDER_TYPE(Id, SingletonId) \
2405 case BuiltinType::Id:
2406#include "clang/AST/BuiltinTypes.def"
2407 llvm_unreachable("asking for RRTI for a placeholder type!");
2408
2409 case BuiltinType::ObjCId:
2410 case BuiltinType::ObjCClass:
2411 case BuiltinType::ObjCSel:
2412 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2413 }
2414
2415 llvm_unreachable("Invalid BuiltinType Kind!");
2416}
2417
2418static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2419 QualType PointeeTy = PointerTy->getPointeeType();
2420 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2421 if (!BuiltinTy)
2422 return false;
2423
2424 // Check the qualifiers.
2425 Qualifiers Quals = PointeeTy.getQualifiers();
2426 Quals.removeConst();
2427
2428 if (!Quals.empty())
2429 return false;
2430
2431 return TypeInfoIsInStandardLibrary(BuiltinTy);
2432}
2433
2434/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2435/// information for the given type exists in the standard library.
2436static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2437 // Type info for builtin types is defined in the standard library.
2438 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2439 return TypeInfoIsInStandardLibrary(BuiltinTy);
2440
2441 // Type info for some pointer types to builtin types is defined in the
2442 // standard library.
2443 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2444 return TypeInfoIsInStandardLibrary(PointerTy);
2445
2446 return false;
2447}
2448
2449/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2450/// the given type exists somewhere else, and that we should not emit the type
2451/// information in this translation unit. Assumes that it is not a
2452/// standard-library type.
2453static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2454 QualType Ty) {
2455 ASTContext &Context = CGM.getContext();
2456
2457 // If RTTI is disabled, assume it might be disabled in the
2458 // translation unit that defines any potential key function, too.
2459 if (!Context.getLangOpts().RTTI) return false;
2460
2461 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2462 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2463 if (!RD->hasDefinition())
2464 return false;
2465
2466 if (!RD->isDynamicClass())
2467 return false;
2468
2469 // FIXME: this may need to be reconsidered if the key function
2470 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002471 // N.B. We must always emit the RTTI data ourselves if there exists a key
2472 // function.
2473 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002474 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002475 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002476
David Majnemerbe9022c2015-08-06 20:56:55 +00002477 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002478 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002479 }
2480
2481 return false;
2482}
2483
2484/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2485static bool IsIncompleteClassType(const RecordType *RecordTy) {
2486 return !RecordTy->getDecl()->isCompleteDefinition();
2487}
2488
2489/// ContainsIncompleteClassType - Returns whether the given type contains an
2490/// incomplete class type. This is true if
2491///
2492/// * The given type is an incomplete class type.
2493/// * The given type is a pointer type whose pointee type contains an
2494/// incomplete class type.
2495/// * The given type is a member pointer type whose class is an incomplete
2496/// class type.
2497/// * The given type is a member pointer type whoise pointee type contains an
2498/// incomplete class type.
2499/// is an indirect or direct pointer to an incomplete class type.
2500static bool ContainsIncompleteClassType(QualType Ty) {
2501 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2502 if (IsIncompleteClassType(RecordTy))
2503 return true;
2504 }
2505
2506 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2507 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2508
2509 if (const MemberPointerType *MemberPointerTy =
2510 dyn_cast<MemberPointerType>(Ty)) {
2511 // Check if the class type is incomplete.
2512 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2513 if (IsIncompleteClassType(ClassType))
2514 return true;
2515
2516 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2517 }
2518
2519 return false;
2520}
2521
2522// CanUseSingleInheritance - Return whether the given record decl has a "single,
2523// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2524// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2525static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2526 // Check the number of bases.
2527 if (RD->getNumBases() != 1)
2528 return false;
2529
2530 // Get the base.
2531 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2532
2533 // Check that the base is not virtual.
2534 if (Base->isVirtual())
2535 return false;
2536
2537 // Check that the base is public.
2538 if (Base->getAccessSpecifier() != AS_public)
2539 return false;
2540
2541 // Check that the class is dynamic iff the base is.
2542 const CXXRecordDecl *BaseDecl =
2543 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2544 if (!BaseDecl->isEmpty() &&
2545 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2546 return false;
2547
2548 return true;
2549}
2550
2551void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2552 // abi::__class_type_info.
2553 static const char * const ClassTypeInfo =
2554 "_ZTVN10__cxxabiv117__class_type_infoE";
2555 // abi::__si_class_type_info.
2556 static const char * const SIClassTypeInfo =
2557 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2558 // abi::__vmi_class_type_info.
2559 static const char * const VMIClassTypeInfo =
2560 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2561
2562 const char *VTableName = nullptr;
2563
2564 switch (Ty->getTypeClass()) {
2565#define TYPE(Class, Base)
2566#define ABSTRACT_TYPE(Class, Base)
2567#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2568#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2569#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2570#include "clang/AST/TypeNodes.def"
2571 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2572
2573 case Type::LValueReference:
2574 case Type::RValueReference:
2575 llvm_unreachable("References shouldn't get here");
2576
2577 case Type::Auto:
2578 llvm_unreachable("Undeduced auto type shouldn't get here");
2579
2580 case Type::Builtin:
2581 // GCC treats vector and complex types as fundamental types.
2582 case Type::Vector:
2583 case Type::ExtVector:
2584 case Type::Complex:
2585 case Type::Atomic:
2586 // FIXME: GCC treats block pointers as fundamental types?!
2587 case Type::BlockPointer:
2588 // abi::__fundamental_type_info.
2589 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2590 break;
2591
2592 case Type::ConstantArray:
2593 case Type::IncompleteArray:
2594 case Type::VariableArray:
2595 // abi::__array_type_info.
2596 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2597 break;
2598
2599 case Type::FunctionNoProto:
2600 case Type::FunctionProto:
2601 // abi::__function_type_info.
2602 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2603 break;
2604
2605 case Type::Enum:
2606 // abi::__enum_type_info.
2607 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2608 break;
2609
2610 case Type::Record: {
2611 const CXXRecordDecl *RD =
2612 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2613
2614 if (!RD->hasDefinition() || !RD->getNumBases()) {
2615 VTableName = ClassTypeInfo;
2616 } else if (CanUseSingleInheritance(RD)) {
2617 VTableName = SIClassTypeInfo;
2618 } else {
2619 VTableName = VMIClassTypeInfo;
2620 }
2621
2622 break;
2623 }
2624
2625 case Type::ObjCObject:
2626 // Ignore protocol qualifiers.
2627 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2628
2629 // Handle id and Class.
2630 if (isa<BuiltinType>(Ty)) {
2631 VTableName = ClassTypeInfo;
2632 break;
2633 }
2634
2635 assert(isa<ObjCInterfaceType>(Ty));
2636 // Fall through.
2637
2638 case Type::ObjCInterface:
2639 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2640 VTableName = SIClassTypeInfo;
2641 } else {
2642 VTableName = ClassTypeInfo;
2643 }
2644 break;
2645
2646 case Type::ObjCObjectPointer:
2647 case Type::Pointer:
2648 // abi::__pointer_type_info.
2649 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2650 break;
2651
2652 case Type::MemberPointer:
2653 // abi::__pointer_to_member_type_info.
2654 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2655 break;
2656 }
2657
2658 llvm::Constant *VTable =
2659 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2660
2661 llvm::Type *PtrDiffTy =
2662 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2663
2664 // The vtable address point is 2.
2665 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002666 VTable =
2667 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002668 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2669
2670 Fields.push_back(VTable);
2671}
2672
2673/// \brief Return the linkage that the type info and type info name constants
2674/// should have for the given type.
2675static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2676 QualType Ty) {
2677 // Itanium C++ ABI 2.9.5p7:
2678 // In addition, it and all of the intermediate abi::__pointer_type_info
2679 // structs in the chain down to the abi::__class_type_info for the
2680 // incomplete class type must be prevented from resolving to the
2681 // corresponding type_info structs for the complete class type, possibly
2682 // by making them local static objects. Finally, a dummy class RTTI is
2683 // generated for the incomplete type that will not resolve to the final
2684 // complete class RTTI (because the latter need not exist), possibly by
2685 // making it a local static object.
2686 if (ContainsIncompleteClassType(Ty))
2687 return llvm::GlobalValue::InternalLinkage;
2688
2689 switch (Ty->getLinkage()) {
2690 case NoLinkage:
2691 case InternalLinkage:
2692 case UniqueExternalLinkage:
2693 return llvm::GlobalValue::InternalLinkage;
2694
2695 case VisibleNoLinkage:
2696 case ExternalLinkage:
2697 if (!CGM.getLangOpts().RTTI) {
2698 // RTTI is not enabled, which means that this type info struct is going
2699 // to be used for exception handling. Give it linkonce_odr linkage.
2700 return llvm::GlobalValue::LinkOnceODRLinkage;
2701 }
2702
2703 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2704 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2705 if (RD->hasAttr<WeakAttr>())
2706 return llvm::GlobalValue::WeakODRLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002707 if (RD->isDynamicClass()) {
2708 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2709 // MinGW won't export the RTTI information when there is a key function.
2710 // Make sure we emit our own copy instead of attempting to dllimport it.
2711 if (RD->hasAttr<DLLImportAttr>() &&
2712 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2713 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2714 return LT;
2715 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002716 }
2717
2718 return llvm::GlobalValue::LinkOnceODRLinkage;
2719 }
2720
2721 llvm_unreachable("Invalid linkage!");
2722}
2723
2724llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2725 // We want to operate on the canonical type.
2726 Ty = CGM.getContext().getCanonicalType(Ty);
2727
2728 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002729 SmallString<256> Name;
2730 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002731 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002732
2733 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2734 if (OldGV && !OldGV->isDeclaration()) {
2735 assert(!OldGV->hasAvailableExternallyLinkage() &&
2736 "available_externally typeinfos not yet implemented");
2737
2738 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2739 }
2740
2741 // Check if there is already an external RTTI descriptor for this type.
2742 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2743 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2744 return GetAddrOfExternalRTTIDescriptor(Ty);
2745
2746 // Emit the standard library with external linkage.
2747 llvm::GlobalVariable::LinkageTypes Linkage;
2748 if (IsStdLib)
2749 Linkage = llvm::GlobalValue::ExternalLinkage;
2750 else
2751 Linkage = getTypeInfoLinkage(CGM, Ty);
2752
2753 // Add the vtable pointer.
2754 BuildVTablePointer(cast<Type>(Ty));
2755
2756 // And the name.
2757 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2758 llvm::Constant *TypeNameField;
2759
2760 // If we're supposed to demote the visibility, be sure to set a flag
2761 // to use a string comparison for type_info comparisons.
2762 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2763 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2764 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2765 // The flag is the sign bit, which on ARM64 is defined to be clear
2766 // for global pointers. This is very ARM64-specific.
2767 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2768 llvm::Constant *flag =
2769 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2770 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2771 TypeNameField =
2772 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2773 } else {
2774 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2775 }
2776 Fields.push_back(TypeNameField);
2777
2778 switch (Ty->getTypeClass()) {
2779#define TYPE(Class, Base)
2780#define ABSTRACT_TYPE(Class, Base)
2781#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2782#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2783#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2784#include "clang/AST/TypeNodes.def"
2785 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2786
2787 // GCC treats vector types as fundamental types.
2788 case Type::Builtin:
2789 case Type::Vector:
2790 case Type::ExtVector:
2791 case Type::Complex:
2792 case Type::BlockPointer:
2793 // Itanium C++ ABI 2.9.5p4:
2794 // abi::__fundamental_type_info adds no data members to std::type_info.
2795 break;
2796
2797 case Type::LValueReference:
2798 case Type::RValueReference:
2799 llvm_unreachable("References shouldn't get here");
2800
2801 case Type::Auto:
2802 llvm_unreachable("Undeduced auto type shouldn't get here");
2803
2804 case Type::ConstantArray:
2805 case Type::IncompleteArray:
2806 case Type::VariableArray:
2807 // Itanium C++ ABI 2.9.5p5:
2808 // abi::__array_type_info adds no data members to std::type_info.
2809 break;
2810
2811 case Type::FunctionNoProto:
2812 case Type::FunctionProto:
2813 // Itanium C++ ABI 2.9.5p5:
2814 // abi::__function_type_info adds no data members to std::type_info.
2815 break;
2816
2817 case Type::Enum:
2818 // Itanium C++ ABI 2.9.5p5:
2819 // abi::__enum_type_info adds no data members to std::type_info.
2820 break;
2821
2822 case Type::Record: {
2823 const CXXRecordDecl *RD =
2824 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2825 if (!RD->hasDefinition() || !RD->getNumBases()) {
2826 // We don't need to emit any fields.
2827 break;
2828 }
2829
2830 if (CanUseSingleInheritance(RD))
2831 BuildSIClassTypeInfo(RD);
2832 else
2833 BuildVMIClassTypeInfo(RD);
2834
2835 break;
2836 }
2837
2838 case Type::ObjCObject:
2839 case Type::ObjCInterface:
2840 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2841 break;
2842
2843 case Type::ObjCObjectPointer:
2844 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2845 break;
2846
2847 case Type::Pointer:
2848 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2849 break;
2850
2851 case Type::MemberPointer:
2852 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2853 break;
2854
2855 case Type::Atomic:
2856 // No fields, at least for the moment.
2857 break;
2858 }
2859
2860 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2861
Rafael Espindolacb92c192015-01-15 23:18:01 +00002862 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00002863 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00002864 new llvm::GlobalVariable(M, Init->getType(),
2865 /*Constant=*/true, Linkage, Init, Name);
2866
David Majnemere2cb8d12014-07-07 06:20:47 +00002867 // If there's already an old global variable, replace it with the new one.
2868 if (OldGV) {
2869 GV->takeName(OldGV);
2870 llvm::Constant *NewPtr =
2871 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2872 OldGV->replaceAllUsesWith(NewPtr);
2873 OldGV->eraseFromParent();
2874 }
2875
Yaron Keren04da2382015-07-29 15:42:28 +00002876 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
2877 GV->setComdat(M.getOrInsertComdat(GV->getName()));
2878
David Majnemere2cb8d12014-07-07 06:20:47 +00002879 // The Itanium ABI specifies that type_info objects must be globally
2880 // unique, with one exception: if the type is an incomplete class
2881 // type or a (possibly indirect) pointer to one. That exception
2882 // affects the general case of comparing type_info objects produced
2883 // by the typeid operator, which is why the comparison operators on
2884 // std::type_info generally use the type_info name pointers instead
2885 // of the object addresses. However, the language's built-in uses
2886 // of RTTI generally require class types to be complete, even when
2887 // manipulating pointers to those class types. This allows the
2888 // implementation of dynamic_cast to rely on address equality tests,
2889 // which is much faster.
2890
2891 // All of this is to say that it's important that both the type_info
2892 // object and the type_info name be uniqued when weakly emitted.
2893
2894 // Give the type_info object and name the formal visibility of the
2895 // type itself.
2896 llvm::GlobalValue::VisibilityTypes llvmVisibility;
2897 if (llvm::GlobalValue::isLocalLinkage(Linkage))
2898 // If the linkage is local, only default visibility makes sense.
2899 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2900 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2901 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2902 else
2903 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2904 TypeName->setVisibility(llvmVisibility);
2905 GV->setVisibility(llvmVisibility);
2906
2907 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2908}
2909
2910/// ComputeQualifierFlags - Compute the pointer type info flags from the
2911/// given qualifier.
2912static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2913 unsigned Flags = 0;
2914
2915 if (Quals.hasConst())
2916 Flags |= ItaniumRTTIBuilder::PTI_Const;
2917 if (Quals.hasVolatile())
2918 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2919 if (Quals.hasRestrict())
2920 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2921
2922 return Flags;
2923}
2924
2925/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2926/// for the given Objective-C object type.
2927void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2928 // Drop qualifiers.
2929 const Type *T = OT->getBaseType().getTypePtr();
2930 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2931
2932 // The builtin types are abi::__class_type_infos and don't require
2933 // extra fields.
2934 if (isa<BuiltinType>(T)) return;
2935
2936 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2937 ObjCInterfaceDecl *Super = Class->getSuperClass();
2938
2939 // Root classes are also __class_type_info.
2940 if (!Super) return;
2941
2942 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2943
2944 // Everything else is single inheritance.
2945 llvm::Constant *BaseTypeInfo =
2946 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2947 Fields.push_back(BaseTypeInfo);
2948}
2949
2950/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2951/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2952void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2953 // Itanium C++ ABI 2.9.5p6b:
2954 // It adds to abi::__class_type_info a single member pointing to the
2955 // type_info structure for the base type,
2956 llvm::Constant *BaseTypeInfo =
2957 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2958 Fields.push_back(BaseTypeInfo);
2959}
2960
2961namespace {
2962 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2963 /// a class hierarchy.
2964 struct SeenBases {
2965 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2966 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2967 };
2968}
2969
2970/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2971/// abi::__vmi_class_type_info.
2972///
2973static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2974 SeenBases &Bases) {
2975
2976 unsigned Flags = 0;
2977
2978 const CXXRecordDecl *BaseDecl =
2979 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2980
2981 if (Base->isVirtual()) {
2982 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002983 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002984 // If this virtual base has been seen before, then the class is diamond
2985 // shaped.
2986 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2987 } else {
2988 if (Bases.NonVirtualBases.count(BaseDecl))
2989 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2990 }
2991 } else {
2992 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00002993 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002994 // If this non-virtual base has been seen before, then the class has non-
2995 // diamond shaped repeated inheritance.
2996 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2997 } else {
2998 if (Bases.VirtualBases.count(BaseDecl))
2999 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3000 }
3001 }
3002
3003 // Walk all bases.
3004 for (const auto &I : BaseDecl->bases())
3005 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3006
3007 return Flags;
3008}
3009
3010static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3011 unsigned Flags = 0;
3012 SeenBases Bases;
3013
3014 // Walk all bases.
3015 for (const auto &I : RD->bases())
3016 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3017
3018 return Flags;
3019}
3020
3021/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3022/// classes with bases that do not satisfy the abi::__si_class_type_info
3023/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3024void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3025 llvm::Type *UnsignedIntLTy =
3026 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3027
3028 // Itanium C++ ABI 2.9.5p6c:
3029 // __flags is a word with flags describing details about the class
3030 // structure, which may be referenced by using the __flags_masks
3031 // enumeration. These flags refer to both direct and indirect bases.
3032 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3033 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3034
3035 // Itanium C++ ABI 2.9.5p6c:
3036 // __base_count is a word with the number of direct proper base class
3037 // descriptions that follow.
3038 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3039
3040 if (!RD->getNumBases())
3041 return;
3042
3043 llvm::Type *LongLTy =
3044 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3045
3046 // Now add the base class descriptions.
3047
3048 // Itanium C++ ABI 2.9.5p6c:
3049 // __base_info[] is an array of base class descriptions -- one for every
3050 // direct proper base. Each description is of the type:
3051 //
3052 // struct abi::__base_class_type_info {
3053 // public:
3054 // const __class_type_info *__base_type;
3055 // long __offset_flags;
3056 //
3057 // enum __offset_flags_masks {
3058 // __virtual_mask = 0x1,
3059 // __public_mask = 0x2,
3060 // __offset_shift = 8
3061 // };
3062 // };
3063 for (const auto &Base : RD->bases()) {
3064 // The __base_type member points to the RTTI for the base type.
3065 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3066
3067 const CXXRecordDecl *BaseDecl =
3068 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3069
3070 int64_t OffsetFlags = 0;
3071
3072 // All but the lower 8 bits of __offset_flags are a signed offset.
3073 // For a non-virtual base, this is the offset in the object of the base
3074 // subobject. For a virtual base, this is the offset in the virtual table of
3075 // the virtual base offset for the virtual base referenced (negative).
3076 CharUnits Offset;
3077 if (Base.isVirtual())
3078 Offset =
3079 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3080 else {
3081 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3082 Offset = Layout.getBaseClassOffset(BaseDecl);
3083 };
3084
3085 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3086
3087 // The low-order byte of __offset_flags contains flags, as given by the
3088 // masks from the enumeration __offset_flags_masks.
3089 if (Base.isVirtual())
3090 OffsetFlags |= BCTI_Virtual;
3091 if (Base.getAccessSpecifier() == AS_public)
3092 OffsetFlags |= BCTI_Public;
3093
3094 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3095 }
3096}
3097
3098/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3099/// used for pointer types.
3100void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3101 Qualifiers Quals;
3102 QualType UnqualifiedPointeeTy =
3103 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3104
3105 // Itanium C++ ABI 2.9.5p7:
3106 // __flags is a flag word describing the cv-qualification and other
3107 // attributes of the type pointed to
3108 unsigned Flags = ComputeQualifierFlags(Quals);
3109
3110 // Itanium C++ ABI 2.9.5p7:
3111 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3112 // incomplete class type, the incomplete target type flag is set.
3113 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3114 Flags |= PTI_Incomplete;
3115
3116 llvm::Type *UnsignedIntLTy =
3117 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3118 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3119
3120 // Itanium C++ ABI 2.9.5p7:
3121 // __pointee is a pointer to the std::type_info derivation for the
3122 // unqualified type being pointed to.
3123 llvm::Constant *PointeeTypeInfo =
3124 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3125 Fields.push_back(PointeeTypeInfo);
3126}
3127
3128/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3129/// struct, used for member pointer types.
3130void
3131ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3132 QualType PointeeTy = Ty->getPointeeType();
3133
3134 Qualifiers Quals;
3135 QualType UnqualifiedPointeeTy =
3136 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3137
3138 // Itanium C++ ABI 2.9.5p7:
3139 // __flags is a flag word describing the cv-qualification and other
3140 // attributes of the type pointed to.
3141 unsigned Flags = ComputeQualifierFlags(Quals);
3142
3143 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3144
3145 // Itanium C++ ABI 2.9.5p7:
3146 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3147 // incomplete class type, the incomplete target type flag is set.
3148 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3149 Flags |= PTI_Incomplete;
3150
3151 if (IsIncompleteClassType(ClassType))
3152 Flags |= PTI_ContainingClassIncomplete;
3153
3154 llvm::Type *UnsignedIntLTy =
3155 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3156 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3157
3158 // Itanium C++ ABI 2.9.5p7:
3159 // __pointee is a pointer to the std::type_info derivation for the
3160 // unqualified type being pointed to.
3161 llvm::Constant *PointeeTypeInfo =
3162 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3163 Fields.push_back(PointeeTypeInfo);
3164
3165 // Itanium C++ ABI 2.9.5p9:
3166 // __context is a pointer to an abi::__class_type_info corresponding to the
3167 // class type containing the member pointed to
3168 // (e.g., the "A" in "int A::*").
3169 Fields.push_back(
3170 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3171}
3172
David Majnemer443250f2015-03-17 20:35:00 +00003173llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003174 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3175}
3176
3177void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3178 QualType PointerType = getContext().getPointerType(Type);
3179 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3180 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3181 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3182 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3183}
3184
3185void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3186 QualType FundamentalTypes[] = {
3187 getContext().VoidTy, getContext().NullPtrTy,
3188 getContext().BoolTy, getContext().WCharTy,
3189 getContext().CharTy, getContext().UnsignedCharTy,
3190 getContext().SignedCharTy, getContext().ShortTy,
3191 getContext().UnsignedShortTy, getContext().IntTy,
3192 getContext().UnsignedIntTy, getContext().LongTy,
3193 getContext().UnsignedLongTy, getContext().LongLongTy,
3194 getContext().UnsignedLongLongTy, getContext().HalfTy,
3195 getContext().FloatTy, getContext().DoubleTy,
3196 getContext().LongDoubleTy, getContext().Char16Ty,
3197 getContext().Char32Ty,
3198 };
3199 for (const QualType &FundamentalType : FundamentalTypes)
3200 EmitFundamentalRTTIDescriptor(FundamentalType);
3201}
3202
3203/// What sort of uniqueness rules should we use for the RTTI for the
3204/// given type?
3205ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3206 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3207 if (shouldRTTIBeUnique())
3208 return RUK_Unique;
3209
3210 // It's only necessary for linkonce_odr or weak_odr linkage.
3211 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3212 Linkage != llvm::GlobalValue::WeakODRLinkage)
3213 return RUK_Unique;
3214
3215 // It's only necessary with default visibility.
3216 if (CanTy->getVisibility() != DefaultVisibility)
3217 return RUK_Unique;
3218
3219 // If we're not required to publish this symbol, hide it.
3220 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3221 return RUK_NonUniqueHidden;
3222
3223 // If we're required to publish this symbol, as we might be under an
3224 // explicit instantiation, leave it with default visibility but
3225 // enable string-comparisons.
3226 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3227 return RUK_NonUniqueVisible;
3228}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003229
Rafael Espindola1e4df922014-09-16 15:18:21 +00003230// Find out how to codegen the complete destructor and constructor
3231namespace {
3232enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3233}
3234static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3235 const CXXMethodDecl *MD) {
3236 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3237 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003238
Rafael Espindola1e4df922014-09-16 15:18:21 +00003239 // The complete and base structors are not equivalent if there are any virtual
3240 // bases, so emit separate functions.
3241 if (MD->getParent()->getNumVBases())
3242 return StructorCodegen::Emit;
3243
3244 GlobalDecl AliasDecl;
3245 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3246 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3247 } else {
3248 const auto *CD = cast<CXXConstructorDecl>(MD);
3249 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3250 }
3251 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3252
3253 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3254 return StructorCodegen::RAUW;
3255
3256 // FIXME: Should we allow available_externally aliases?
3257 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3258 return StructorCodegen::RAUW;
3259
Rafael Espindola0806f982014-09-16 20:19:43 +00003260 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3261 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3262 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3263 return StructorCodegen::COMDAT;
3264 return StructorCodegen::Emit;
3265 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003266
3267 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003268}
3269
Rafael Espindola1e4df922014-09-16 15:18:21 +00003270static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3271 GlobalDecl AliasDecl,
3272 GlobalDecl TargetDecl) {
3273 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3274
3275 StringRef MangledName = CGM.getMangledName(AliasDecl);
3276 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3277 if (Entry && !Entry->isDeclaration())
3278 return;
3279
3280 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3281 llvm::PointerType *AliasType = Aliasee->getType();
3282
3283 // Create the alias with no name.
David Blaikie881b2342015-04-29 21:22:47 +00003284 auto *Alias = llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee,
3285 &CGM.getModule());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003286
3287 // Switch any previous uses to the alias.
3288 if (Entry) {
3289 assert(Entry->getType() == AliasType &&
3290 "declaration exists with different type");
3291 Alias->takeName(Entry);
3292 Entry->replaceAllUsesWith(Alias);
3293 Entry->eraseFromParent();
3294 } else {
3295 Alias->setName(MangledName);
3296 }
3297
3298 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003299 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003300}
3301
3302void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3303 StructorType Type) {
3304 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3305 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3306
3307 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3308
3309 if (Type == StructorType::Complete) {
3310 GlobalDecl CompleteDecl;
3311 GlobalDecl BaseDecl;
3312 if (CD) {
3313 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3314 BaseDecl = GlobalDecl(CD, Ctor_Base);
3315 } else {
3316 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3317 BaseDecl = GlobalDecl(DD, Dtor_Base);
3318 }
3319
3320 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3321 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3322 return;
3323 }
3324
3325 if (CGType == StructorCodegen::RAUW) {
3326 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3327 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3328 CGM.addReplacement(MangledName, Aliasee);
3329 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003330 }
3331 }
3332
3333 // The base destructor is equivalent to the base destructor of its
3334 // base class if there is exactly one non-virtual base class with a
3335 // non-trivial destructor, there are no fields with a non-trivial
3336 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003337 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3338 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003339 return;
3340
Rafael Espindola1e4df922014-09-16 15:18:21 +00003341 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003342
Rafael Espindola1e4df922014-09-16 15:18:21 +00003343 if (CGType == StructorCodegen::COMDAT) {
3344 SmallString<256> Buffer;
3345 llvm::raw_svector_ostream Out(Buffer);
3346 if (DD)
3347 getMangleContext().mangleCXXDtorComdat(DD, Out);
3348 else
3349 getMangleContext().mangleCXXCtorComdat(CD, Out);
3350 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3351 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003352 } else {
3353 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003354 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003355}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003356
3357static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3358 // void *__cxa_begin_catch(void*);
3359 llvm::FunctionType *FTy = llvm::FunctionType::get(
3360 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3361
3362 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3363}
3364
3365static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3366 // void __cxa_end_catch();
3367 llvm::FunctionType *FTy =
3368 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3369
3370 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3371}
3372
3373static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3374 // void *__cxa_get_exception_ptr(void*);
3375 llvm::FunctionType *FTy = llvm::FunctionType::get(
3376 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3377
3378 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3379}
3380
3381namespace {
3382 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3383 /// exception type lets us state definitively that the thrown exception
3384 /// type does not have a destructor. In particular:
3385 /// - Catch-alls tell us nothing, so we have to conservatively
3386 /// assume that the thrown exception might have a destructor.
3387 /// - Catches by reference behave according to their base types.
3388 /// - Catches of non-record types will only trigger for exceptions
3389 /// of non-record types, which never have destructors.
3390 /// - Catches of record types can trigger for arbitrary subclasses
3391 /// of the caught type, so we have to assume the actual thrown
3392 /// exception type might have a throwing destructor, even if the
3393 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003394 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003395 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3396 bool MightThrow;
3397
3398 void Emit(CodeGenFunction &CGF, Flags flags) override {
3399 if (!MightThrow) {
3400 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3401 return;
3402 }
3403
3404 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3405 }
3406 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003407}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003408
3409/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3410/// __cxa_end_catch.
3411///
3412/// \param EndMightThrow - true if __cxa_end_catch might throw
3413static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3414 llvm::Value *Exn,
3415 bool EndMightThrow) {
3416 llvm::CallInst *call =
3417 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3418
3419 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3420
3421 return call;
3422}
3423
3424/// A "special initializer" callback for initializing a catch
3425/// parameter during catch initialization.
3426static void InitCatchParam(CodeGenFunction &CGF,
3427 const VarDecl &CatchParam,
3428 llvm::Value *ParamAddr,
3429 SourceLocation Loc) {
3430 // Load the exception from where the landing pad saved it.
3431 llvm::Value *Exn = CGF.getExceptionFromSlot();
3432
3433 CanQualType CatchType =
3434 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3435 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3436
3437 // If we're catching by reference, we can just cast the object
3438 // pointer to the appropriate pointer.
3439 if (isa<ReferenceType>(CatchType)) {
3440 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3441 bool EndCatchMightThrow = CaughtType->isRecordType();
3442
3443 // __cxa_begin_catch returns the adjusted object pointer.
3444 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3445
3446 // We have no way to tell the personality function that we're
3447 // catching by reference, so if we're catching a pointer,
3448 // __cxa_begin_catch will actually return that pointer by value.
3449 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3450 QualType PointeeType = PT->getPointeeType();
3451
3452 // When catching by reference, generally we should just ignore
3453 // this by-value pointer and use the exception object instead.
3454 if (!PointeeType->isRecordType()) {
3455
3456 // Exn points to the struct _Unwind_Exception header, which
3457 // we have to skip past in order to reach the exception data.
3458 unsigned HeaderSize =
3459 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3460 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3461
3462 // However, if we're catching a pointer-to-record type that won't
3463 // work, because the personality function might have adjusted
3464 // the pointer. There's actually no way for us to fully satisfy
3465 // the language/ABI contract here: we can't use Exn because it
3466 // might have the wrong adjustment, but we can't use the by-value
3467 // pointer because it's off by a level of abstraction.
3468 //
3469 // The current solution is to dump the adjusted pointer into an
3470 // alloca, which breaks language semantics (because changing the
3471 // pointer doesn't change the exception) but at least works.
3472 // The better solution would be to filter out non-exact matches
3473 // and rethrow them, but this is tricky because the rethrow
3474 // really needs to be catchable by other sites at this landing
3475 // pad. The best solution is to fix the personality function.
3476 } else {
3477 // Pull the pointer for the reference type off.
3478 llvm::Type *PtrTy =
3479 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3480
3481 // Create the temporary and write the adjusted pointer into it.
3482 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
3483 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3484 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3485
3486 // Bind the reference to the temporary.
3487 AdjustedExn = ExnPtrTmp;
3488 }
3489 }
3490
3491 llvm::Value *ExnCast =
3492 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3493 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3494 return;
3495 }
3496
3497 // Scalars and complexes.
3498 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3499 if (TEK != TEK_Aggregate) {
3500 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3501
3502 // If the catch type is a pointer type, __cxa_begin_catch returns
3503 // the pointer by value.
3504 if (CatchType->hasPointerRepresentation()) {
3505 llvm::Value *CastExn =
3506 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3507
3508 switch (CatchType.getQualifiers().getObjCLifetime()) {
3509 case Qualifiers::OCL_Strong:
3510 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3511 // fallthrough
3512
3513 case Qualifiers::OCL_None:
3514 case Qualifiers::OCL_ExplicitNone:
3515 case Qualifiers::OCL_Autoreleasing:
3516 CGF.Builder.CreateStore(CastExn, ParamAddr);
3517 return;
3518
3519 case Qualifiers::OCL_Weak:
3520 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3521 return;
3522 }
3523 llvm_unreachable("bad ownership qualifier!");
3524 }
3525
3526 // Otherwise, it returns a pointer into the exception object.
3527
3528 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3529 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3530
3531 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3532 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
3533 CGF.getContext().getDeclAlign(&CatchParam));
3534 switch (TEK) {
3535 case TEK_Complex:
3536 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3537 /*init*/ true);
3538 return;
3539 case TEK_Scalar: {
3540 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3541 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3542 return;
3543 }
3544 case TEK_Aggregate:
3545 llvm_unreachable("evaluation kind filtered out!");
3546 }
3547 llvm_unreachable("bad evaluation kind");
3548 }
3549
3550 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3551
3552 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3553
3554 // Check for a copy expression. If we don't have a copy expression,
3555 // that means a trivial copy is okay.
3556 const Expr *copyExpr = CatchParam.getInit();
3557 if (!copyExpr) {
3558 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3559 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3560 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3561 return;
3562 }
3563
3564 // We have to call __cxa_get_exception_ptr to get the adjusted
3565 // pointer before copying.
3566 llvm::CallInst *rawAdjustedExn =
3567 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3568
3569 // Cast that to the appropriate type.
3570 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
3571
3572 // The copy expression is defined in terms of an OpaqueValueExpr.
3573 // Find it and map it to the adjusted expression.
3574 CodeGenFunction::OpaqueValueMapping
3575 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3576 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3577
3578 // Call the copy ctor in a terminate scope.
3579 CGF.EHStack.pushTerminate();
3580
3581 // Perform the copy construction.
3582 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
3583 CGF.EmitAggExpr(copyExpr,
3584 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
3585 AggValueSlot::IsNotDestructed,
3586 AggValueSlot::DoesNotNeedGCBarriers,
3587 AggValueSlot::IsNotAliased));
3588
3589 // Leave the terminate scope.
3590 CGF.EHStack.popTerminate();
3591
3592 // Undo the opaque value mapping.
3593 opaque.pop();
3594
3595 // Finally we can call __cxa_begin_catch.
3596 CallBeginCatch(CGF, Exn, true);
3597}
3598
3599/// Begins a catch statement by initializing the catch variable and
3600/// calling __cxa_begin_catch.
3601void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3602 const CXXCatchStmt *S) {
3603 // We have to be very careful with the ordering of cleanups here:
3604 // C++ [except.throw]p4:
3605 // The destruction [of the exception temporary] occurs
3606 // immediately after the destruction of the object declared in
3607 // the exception-declaration in the handler.
3608 //
3609 // So the precise ordering is:
3610 // 1. Construct catch variable.
3611 // 2. __cxa_begin_catch
3612 // 3. Enter __cxa_end_catch cleanup
3613 // 4. Enter dtor cleanup
3614 //
3615 // We do this by using a slightly abnormal initialization process.
3616 // Delegation sequence:
3617 // - ExitCXXTryStmt opens a RunCleanupsScope
3618 // - EmitAutoVarAlloca creates the variable and debug info
3619 // - InitCatchParam initializes the variable from the exception
3620 // - CallBeginCatch calls __cxa_begin_catch
3621 // - CallBeginCatch enters the __cxa_end_catch cleanup
3622 // - EmitAutoVarCleanups enters the variable destructor cleanup
3623 // - EmitCXXTryStmt emits the code for the catch body
3624 // - EmitCXXTryStmt close the RunCleanupsScope
3625
3626 VarDecl *CatchParam = S->getExceptionDecl();
3627 if (!CatchParam) {
3628 llvm::Value *Exn = CGF.getExceptionFromSlot();
3629 CallBeginCatch(CGF, Exn, true);
3630 return;
3631 }
3632
3633 // Emit the local.
3634 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3635 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3636 CGF.EmitAutoVarCleanups(var);
3637}
3638
3639/// Get or define the following function:
3640/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3641/// This code is used only in C++.
3642static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3643 llvm::FunctionType *fnTy =
3644 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3645 llvm::Constant *fnRef =
3646 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3647
3648 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3649 if (fn && fn->empty()) {
3650 fn->setDoesNotThrow();
3651 fn->setDoesNotReturn();
3652
3653 // What we really want is to massively penalize inlining without
3654 // forbidding it completely. The difference between that and
3655 // 'noinline' is negligible.
3656 fn->addFnAttr(llvm::Attribute::NoInline);
3657
3658 // Allow this function to be shared across translation units, but
3659 // we don't want it to turn into an exported symbol.
3660 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3661 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003662 if (CGM.supportsCOMDAT())
3663 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003664
3665 // Set up the function.
3666 llvm::BasicBlock *entry =
3667 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3668 CGBuilderTy builder(entry);
3669
3670 // Pull the exception pointer out of the parameter list.
3671 llvm::Value *exn = &*fn->arg_begin();
3672
3673 // Call __cxa_begin_catch(exn).
3674 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3675 catchCall->setDoesNotThrow();
3676 catchCall->setCallingConv(CGM.getRuntimeCC());
3677
3678 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003679 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003680 termCall->setDoesNotThrow();
3681 termCall->setDoesNotReturn();
3682 termCall->setCallingConv(CGM.getRuntimeCC());
3683
3684 // std::terminate cannot return.
3685 builder.CreateUnreachable();
3686 }
3687
3688 return fnRef;
3689}
3690
3691llvm::CallInst *
3692ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3693 llvm::Value *Exn) {
3694 // In C++, we want to call __cxa_begin_catch() before terminating.
3695 if (Exn) {
3696 assert(CGF.CGM.getLangOpts().CPlusPlus);
3697 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3698 }
3699 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3700}