blob: d32a131c6d0041fd24ffcb29b9816160f13e63c0 [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"
John McCall9c6cb762016-11-28 22:18:33 +000027#include "ConstantBuilder.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000028#include "TargetInfo.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000029#include "clang/AST/Mangle.h"
30#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000031#include "clang/AST/StmtCXX.h"
David Majnemer1162d252014-06-22 19:05:33 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000034#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000035#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Value.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000037
38using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000039using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000040
41namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000042class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000043 /// VTables - All the vtables which have been defined.
44 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
45
John McCall475999d2010-08-22 00:05:51 +000046protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000047 bool UseARMMethodPtrABI;
48 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000049 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000050
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000051 ItaniumMangleContext &getMangleContext() {
52 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
53 }
54
Charles Davis4e786dd2010-05-25 19:52:27 +000055public:
Mark Seabornedf0d382013-07-24 16:25:13 +000056 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
57 bool UseARMMethodPtrABI = false,
58 bool UseARMGuardVarABI = false) :
59 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000060 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000061 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000062
Reid Kleckner40ca9132014-05-13 22:05:45 +000063 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000064
Craig Topper4f12f102014-03-12 06:41:41 +000065 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Reid Klecknerd355ca72014-05-15 01:26:32 +000066 // Structures with either a non-trivial destructor or a non-trivial
67 // copy constructor are always indirect.
68 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
69 // special members.
70 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000071 return RAA_Indirect;
72 return RAA_Default;
73 }
74
John McCall7f416cc2015-09-08 08:05:57 +000075 bool isThisCompleteObject(GlobalDecl GD) const override {
76 // The Itanium ABI has separate complete-object vs. base-object
77 // variants of both constructors and destructors.
78 if (isa<CXXDestructorDecl>(GD.getDecl())) {
79 switch (GD.getDtorType()) {
80 case Dtor_Complete:
81 case Dtor_Deleting:
82 return true;
83
84 case Dtor_Base:
85 return false;
86
87 case Dtor_Comdat:
88 llvm_unreachable("emitting dtor comdat as function?");
89 }
90 llvm_unreachable("bad dtor kind");
91 }
92 if (isa<CXXConstructorDecl>(GD.getDecl())) {
93 switch (GD.getCtorType()) {
94 case Ctor_Complete:
95 return true;
96
97 case Ctor_Base:
98 return false;
99
100 case Ctor_CopyingClosure:
101 case Ctor_DefaultClosure:
102 llvm_unreachable("closure ctors in Itanium ABI?");
103
104 case Ctor_Comdat:
105 llvm_unreachable("emitting ctor comdat as function?");
106 }
107 llvm_unreachable("bad dtor kind");
108 }
109
110 // No other kinds.
111 return false;
112 }
113
Craig Topper4f12f102014-03-12 06:41:41 +0000114 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000115
Craig Topper4f12f102014-03-12 06:41:41 +0000116 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000117
John McCallb92ab1a2016-10-26 23:46:34 +0000118 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000119 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
120 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000121 Address This,
122 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000123 llvm::Value *MemFnPtr,
124 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000125
Craig Topper4f12f102014-03-12 06:41:41 +0000126 llvm::Value *
127 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000128 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000129 llvm::Value *MemPtr,
130 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000131
John McCall7a9aac22010-08-23 01:21:21 +0000132 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
133 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000134 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000135 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000136 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000137
Craig Topper4f12f102014-03-12 06:41:41 +0000138 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000139
David Majnemere2be95b2015-06-23 07:31:01 +0000140 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000141 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000142 CharUnits offset) override;
143 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000144 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
145 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000146
John McCall7a9aac22010-08-23 01:21:21 +0000147 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000148 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000149 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000151
John McCall7a9aac22010-08-23 01:21:21 +0000152 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000153 llvm::Value *Addr,
154 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000155
David Majnemer08681372014-11-01 07:37:17 +0000156 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000157 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000158 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000159
John McCall7f416cc2015-09-08 08:05:57 +0000160 CharUnits getAlignmentOfExnObject() {
Akira Hatanaka68ab7fe2016-03-31 06:36:07 +0000161 unsigned Align = CGM.getContext().getTargetInfo().getExnObjectAlignment();
162 return CGM.getContext().toCharUnitsFromBits(Align);
John McCall7f416cc2015-09-08 08:05:57 +0000163 }
164
David Majnemer442d0a22014-11-25 07:20:20 +0000165 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000166 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000167
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000168 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
169
170 llvm::CallInst *
171 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
172 llvm::Value *Exn) override;
173
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000174 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
175 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000176 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000177 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000178 getAddrOfCXXCatchHandlerType(QualType Ty,
179 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000180 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000181 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000182
David Majnemer1162d252014-06-22 19:05:33 +0000183 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
184 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
185 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000186 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000187 llvm::Type *StdTypeInfoPtrTy) override;
188
189 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
190 QualType SrcRecordTy) override;
191
John McCall7f416cc2015-09-08 08:05:57 +0000192 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000193 QualType SrcRecordTy, QualType DestTy,
194 QualType DestRecordTy,
195 llvm::BasicBlock *CastEnd) override;
196
John McCall7f416cc2015-09-08 08:05:57 +0000197 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000198 QualType SrcRecordTy,
199 QualType DestTy) override;
200
201 bool EmitBadCastCall(CodeGenFunction &CGF) override;
202
Craig Topper4f12f102014-03-12 06:41:41 +0000203 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000204 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000205 const CXXRecordDecl *ClassDecl,
206 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000207
Craig Topper4f12f102014-03-12 06:41:41 +0000208 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000209
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000210 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
211 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000212
Reid Klecknere7de47e2013-07-22 13:51:44 +0000213 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000214 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000215 // Itanium does not emit any destructor variant as an inline thunk.
216 // Delegating may occur as an optimization, but all variants are either
217 // emitted with external linkage or as linkonce if they are inline and used.
218 return false;
219 }
220
Craig Topper4f12f102014-03-12 06:41:41 +0000221 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000222
Reid Kleckner89077a12013-12-17 19:46:40 +0000223 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000224 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000225
Craig Topper4f12f102014-03-12 06:41:41 +0000226 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000227
Reid Kleckner89077a12013-12-17 19:46:40 +0000228 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
229 const CXXConstructorDecl *D,
230 CXXCtorType Type, bool ForVirtualBase,
Craig Topper4f12f102014-03-12 06:41:41 +0000231 bool Delegating,
232 CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000233
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000234 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
235 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000236 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000237
Craig Topper4f12f102014-03-12 06:41:41 +0000238 void emitVTableDefinitions(CodeGenVTables &CGVT,
239 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000240
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000241 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
242 CodeGenFunction::VPtr Vptr) override;
243
244 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
245 return true;
246 }
247
248 llvm::Constant *
249 getVTableAddressPoint(BaseSubobject Base,
250 const CXXRecordDecl *VTableClass) override;
251
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000252 llvm::Value *getVTableAddressPointInStructor(
253 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000254 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
255
256 llvm::Value *getVTableAddressPointInStructorWithVTT(
257 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
258 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000259
260 llvm::Constant *
261 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000262 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000263
264 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000265 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000266
John McCallb92ab1a2016-10-26 23:46:34 +0000267 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
268 Address This, llvm::Type *Ty,
269 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000270
David Majnemer0c0b6d92014-10-31 20:09:12 +0000271 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
272 const CXXDestructorDecl *Dtor,
273 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000274 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000275 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000276
Craig Topper4f12f102014-03-12 06:41:41 +0000277 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000278
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000279 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000280
Hans Wennborgc94391d2014-06-06 20:04:01 +0000281 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
282 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000283 // Allow inlining of thunks by emitting them with available_externally
284 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000285 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000286 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
287 }
288
John McCall7f416cc2015-09-08 08:05:57 +0000289 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000290 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000291
John McCall7f416cc2015-09-08 08:05:57 +0000292 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000293 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000294
David Majnemer196ac332014-09-11 23:05:02 +0000295 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
296 FunctionArgList &Args) const override {
297 assert(!Args.empty() && "expected the arglist to not be empty!");
298 return Args.size() - 1;
299 }
300
Craig Topper4f12f102014-03-12 06:41:41 +0000301 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
302 StringRef GetDeletedVirtualCallName() override
303 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000304
Craig Topper4f12f102014-03-12 06:41:41 +0000305 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000306 Address InitializeArrayCookie(CodeGenFunction &CGF,
307 Address NewPtr,
308 llvm::Value *NumElements,
309 const CXXNewExpr *expr,
310 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000311 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000312 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000313 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000314
John McCallcdf7ef52010-11-06 09:44:32 +0000315 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000316 llvm::GlobalVariable *DeclPtr,
317 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000318 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000319 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000320
321 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000322 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000323 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000324 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000325 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000326 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000327 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000328
329 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000330 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
331 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000332
Craig Topper4f12f102014-03-12 06:41:41 +0000333 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000334
335 /**************************** RTTI Uniqueness ******************************/
336
337protected:
338 /// Returns true if the ABI requires RTTI type_info objects to be unique
339 /// across a program.
340 virtual bool shouldRTTIBeUnique() const { return true; }
341
342public:
343 /// What sort of unique-RTTI behavior should we use?
344 enum RTTIUniquenessKind {
345 /// We are guaranteeing, or need to guarantee, that the RTTI string
346 /// is unique.
347 RUK_Unique,
348
349 /// We are not guaranteeing uniqueness for the RTTI string, so we
350 /// can demote to hidden visibility but must use string comparisons.
351 RUK_NonUniqueHidden,
352
353 /// We are not guaranteeing uniqueness for the RTTI string, so we
354 /// have to use string comparisons, but we also have to emit it with
355 /// non-hidden visibility.
356 RUK_NonUniqueVisible
357 };
358
359 /// Return the required visibility status for the given type and linkage in
360 /// the current ABI.
361 RTTIUniquenessKind
362 classifyRTTIUniqueness(QualType CanTy,
363 llvm::GlobalValue::LinkageTypes Linkage) const;
364 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000365
366 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000367
368 private:
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000369 bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000370 const auto &VtableLayout =
371 CGM.getItaniumVTableContext().getVTableLayout(RD);
372
373 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000374 if (!VtableComponent.isUsedFunctionPointerKind())
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000375 continue;
376
Piotr Padlewski1d02f682015-08-19 20:09:09 +0000377 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000378 if (Method->getCanonicalDecl()->isInlined())
379 return true;
380 }
381 return false;
382 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000383
384 bool isVTableHidden(const CXXRecordDecl *RD) const {
385 const auto &VtableLayout =
386 CGM.getItaniumVTableContext().getVTableLayout(RD);
387
388 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
389 if (VtableComponent.isRTTIKind()) {
390 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
391 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
392 return true;
393 } else if (VtableComponent.isUsedFunctionPointerKind()) {
394 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
395 if (Method->getVisibility() == Visibility::HiddenVisibility &&
396 !Method->isDefined())
397 return true;
398 }
399 }
400 return false;
401 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000402};
John McCall86353412010-08-21 22:46:04 +0000403
404class ARMCXXABI : public ItaniumCXXABI {
405public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000406 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
407 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
408 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000409
Craig Topper4f12f102014-03-12 06:41:41 +0000410 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000411 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
412 isa<CXXDestructorDecl>(GD.getDecl()) &&
413 GD.getDtorType() != Dtor_Deleting));
414 }
John McCall5d865c322010-08-31 07:33:07 +0000415
Craig Topper4f12f102014-03-12 06:41:41 +0000416 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
417 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000418
Craig Topper4f12f102014-03-12 06:41:41 +0000419 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000420 Address InitializeArrayCookie(CodeGenFunction &CGF,
421 Address NewPtr,
422 llvm::Value *NumElements,
423 const CXXNewExpr *expr,
424 QualType ElementType) override;
425 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000426 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000427};
Tim Northovera2ee4332014-03-29 15:09:45 +0000428
429class iOS64CXXABI : public ARMCXXABI {
430public:
John McCalld23b27e2016-09-16 02:40:45 +0000431 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
432 Use32BitVTableOffsetABI = true;
433 }
Tim Northover65f582f2014-03-30 17:32:48 +0000434
435 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000436 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000437};
Dan Gohmanc2853072015-09-03 22:51:53 +0000438
439class WebAssemblyCXXABI final : public ItaniumCXXABI {
440public:
441 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
442 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
443 /*UseARMGuardVarABI=*/true) {}
444
445private:
446 bool HasThisReturn(GlobalDecl GD) const override {
447 return isa<CXXConstructorDecl>(GD.getDecl()) ||
448 (isa<CXXDestructorDecl>(GD.getDecl()) &&
449 GD.getDtorType() != Dtor_Deleting);
450 }
Derek Schuff8179be42016-05-10 17:44:55 +0000451 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000452};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000453}
Charles Davis4e786dd2010-05-25 19:52:27 +0000454
Charles Davis53c59df2010-08-16 03:33:14 +0000455CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000456 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000457 // For IR-generation purposes, there's no significant difference
458 // between the ARM and iOS ABIs.
459 case TargetCXXABI::GenericARM:
460 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000461 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000462 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000463
Tim Northovera2ee4332014-03-29 15:09:45 +0000464 case TargetCXXABI::iOS64:
465 return new iOS64CXXABI(CGM);
466
Tim Northover9bb857a2013-01-31 12:13:10 +0000467 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
468 // include the other 32-bit ARM oddities: constructor/destructor return values
469 // and array cookies.
470 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000471 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
472 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000473
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000474 case TargetCXXABI::GenericMIPS:
475 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
476
Dan Gohmanc2853072015-09-03 22:51:53 +0000477 case TargetCXXABI::WebAssembly:
478 return new WebAssemblyCXXABI(CGM);
479
John McCall57625922013-01-25 23:36:14 +0000480 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000481 if (CGM.getContext().getTargetInfo().getTriple().getArch()
482 == llvm::Triple::le32) {
483 // For PNaCl, use ARM-style method pointers so that PNaCl code
484 // does not assume anything about the alignment of function
485 // pointers.
486 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
487 /* UseARMGuardVarABI = */ false);
488 }
John McCall57625922013-01-25 23:36:14 +0000489 return new ItaniumCXXABI(CGM);
490
491 case TargetCXXABI::Microsoft:
492 llvm_unreachable("Microsoft ABI is not Itanium-based");
493 }
494 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000495}
496
Chris Lattnera5f58b02011-07-09 17:41:47 +0000497llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000498ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
499 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000500 return CGM.PtrDiffTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +0000501 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
John McCall1c456c82010-08-22 06:43:33 +0000502}
503
John McCalld9c6c0b2010-08-22 00:59:17 +0000504/// In the Itanium and ARM ABIs, method pointers have the form:
505/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
506///
507/// In the Itanium ABI:
508/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
509/// - the this-adjustment is (memptr.adj)
510/// - the virtual offset is (memptr.ptr - 1)
511///
512/// In the ARM ABI:
513/// - method pointers are virtual if (memptr.adj & 1) is nonzero
514/// - the this-adjustment is (memptr.adj >> 1)
515/// - the virtual offset is (memptr.ptr)
516/// ARM uses 'adj' for the virtual flag because Thumb functions
517/// may be only single-byte aligned.
518///
519/// If the member is virtual, the adjusted 'this' pointer points
520/// to a vtable pointer from which the virtual offset is applied.
521///
522/// If the member is non-virtual, memptr.ptr is the address of
523/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000524CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000525 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
526 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000527 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000528 CGBuilderTy &Builder = CGF.Builder;
529
530 const FunctionProtoType *FPT =
531 MPT->getPointeeType()->getAs<FunctionProtoType>();
532 const CXXRecordDecl *RD =
533 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
534
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000535 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
536 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000537
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000538 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000539
John McCalld9c6c0b2010-08-22 00:59:17 +0000540 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
541 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
542 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
543
John McCalla1dee5302010-08-22 10:59:02 +0000544 // Extract memptr.adj, which is in the second field.
545 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000546
547 // Compute the true adjustment.
548 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000549 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000550 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000551
552 // Apply the adjustment and cast back to the original struct type
553 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000554 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000555 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
556 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
557 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000558 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000559
560 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000561 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000562
563 // If the LSB in the function pointer is 1, the function pointer points to
564 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000565 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000566 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000567 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
568 else
569 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
570 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000571 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
572
573 // In the virtual path, the adjustment left 'This' pointing to the
574 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000575 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000576 CGF.EmitBlock(FnVirtual);
577
578 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000579 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000580 CharUnits VTablePtrAlign =
581 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
582 CGF.getPointerAlign());
583 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000584 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000585
586 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000587 // On ARM64, to reserve extra space in virtual member function pointers,
588 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000589 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000590 if (!UseARMMethodPtrABI)
591 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000592 if (Use32BitVTableOffsetABI) {
593 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
594 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
595 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000596 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000597
598 // Load the virtual function to call.
599 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000600 llvm::Value *VirtualFn =
601 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
602 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000603 CGF.EmitBranch(FnEnd);
604
605 // In the non-virtual path, the function pointer is actually a
606 // function pointer.
607 CGF.EmitBlock(FnNonVirtual);
608 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000609 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000610
611 // We're done.
612 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000613 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
614 CalleePtr->addIncoming(VirtualFn, FnVirtual);
615 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
616
617 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000618 return Callee;
619}
John McCalla8bbb822010-08-22 03:04:22 +0000620
John McCallc134eb52010-08-31 21:07:20 +0000621/// Compute an l-value by applying the given pointer-to-member to a
622/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000623llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000624 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000625 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000626 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000627
628 CGBuilderTy &Builder = CGF.Builder;
629
John McCallc134eb52010-08-31 21:07:20 +0000630 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000631 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000632
633 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000634 llvm::Value *Addr =
635 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000636
637 // Cast the address to the appropriate pointer type, adopting the
638 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000639 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
640 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000641 return Builder.CreateBitCast(Addr, PType);
642}
643
John McCallc62bb392012-02-15 01:22:51 +0000644/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
645/// conversion.
646///
647/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000648///
649/// Obligatory offset/adjustment diagram:
650/// <-- offset --> <-- adjustment -->
651/// |--------------------------|----------------------|--------------------|
652/// ^Derived address point ^Base address point ^Member address point
653///
654/// So when converting a base member pointer to a derived member pointer,
655/// we add the offset to the adjustment because the address point has
656/// decreased; and conversely, when converting a derived MP to a base MP
657/// we subtract the offset from the adjustment because the address point
658/// has increased.
659///
660/// The standard forbids (at compile time) conversion to and from
661/// virtual bases, which is why we don't have to consider them here.
662///
663/// The standard forbids (at run time) casting a derived MP to a base
664/// MP when the derived MP does not point to a member of the base.
665/// This is why -1 is a reasonable choice for null data member
666/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000667llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000668ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
669 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000670 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000671 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000672 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
673 E->getCastKind() == CK_ReinterpretMemberPointer);
674
675 // Under Itanium, reinterprets don't require any additional processing.
676 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
677
678 // Use constant emission if we can.
679 if (isa<llvm::Constant>(src))
680 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
681
682 llvm::Constant *adj = getMemberPointerAdjustment(E);
683 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000684
685 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000686 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000687
John McCallc62bb392012-02-15 01:22:51 +0000688 const MemberPointerType *destTy =
689 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000690
John McCall7a9aac22010-08-23 01:21:21 +0000691 // For member data pointers, this is just a matter of adding the
692 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000693 if (destTy->isMemberDataPointer()) {
694 llvm::Value *dst;
695 if (isDerivedToBase)
696 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000697 else
John McCallc62bb392012-02-15 01:22:51 +0000698 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000699
700 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000701 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
702 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
703 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000704 }
705
John McCalla1dee5302010-08-22 10:59:02 +0000706 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000707 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000708 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
709 offset <<= 1;
710 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000711 }
712
John McCallc62bb392012-02-15 01:22:51 +0000713 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
714 llvm::Value *dstAdj;
715 if (isDerivedToBase)
716 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000717 else
John McCallc62bb392012-02-15 01:22:51 +0000718 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000719
John McCallc62bb392012-02-15 01:22:51 +0000720 return Builder.CreateInsertValue(src, dstAdj, 1);
721}
722
723llvm::Constant *
724ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
725 llvm::Constant *src) {
726 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
727 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
728 E->getCastKind() == CK_ReinterpretMemberPointer);
729
730 // Under Itanium, reinterprets don't require any additional processing.
731 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
732
733 // If the adjustment is trivial, we don't need to do anything.
734 llvm::Constant *adj = getMemberPointerAdjustment(E);
735 if (!adj) return src;
736
737 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
738
739 const MemberPointerType *destTy =
740 E->getType()->castAs<MemberPointerType>();
741
742 // For member data pointers, this is just a matter of adding the
743 // offset if the source is non-null.
744 if (destTy->isMemberDataPointer()) {
745 // null maps to null.
746 if (src->isAllOnesValue()) return src;
747
748 if (isDerivedToBase)
749 return llvm::ConstantExpr::getNSWSub(src, adj);
750 else
751 return llvm::ConstantExpr::getNSWAdd(src, adj);
752 }
753
754 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000755 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000756 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
757 offset <<= 1;
758 adj = llvm::ConstantInt::get(adj->getType(), offset);
759 }
760
761 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
762 llvm::Constant *dstAdj;
763 if (isDerivedToBase)
764 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
765 else
766 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
767
768 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000769}
John McCall84fa5102010-08-22 04:16:24 +0000770
771llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000772ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000773 // Itanium C++ ABI 2.3:
774 // A NULL pointer is represented as -1.
775 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000776 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000777
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000778 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000779 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000780 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000781}
782
John McCallf3a88602011-02-03 08:15:49 +0000783llvm::Constant *
784ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
785 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000786 // Itanium C++ ABI 2.3:
787 // A pointer to data member is an offset from the base address of
788 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000789 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000790}
791
David Majnemere2be95b2015-06-23 07:31:01 +0000792llvm::Constant *
793ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000794 return BuildMemberPointer(MD, CharUnits::Zero());
795}
796
797llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
798 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000799 assert(MD->isInstance() && "Member function must not be static!");
800 MD = MD->getCanonicalDecl();
801
802 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000803
804 // Get the function pointer (or index if this is a virtual function).
805 llvm::Constant *MemPtr[2];
806 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000807 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000808
Ken Dyckdf016282011-04-09 01:30:02 +0000809 const ASTContext &Context = getContext();
810 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000811 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000812 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000813
Mark Seabornedf0d382013-07-24 16:25:13 +0000814 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000815 // ARM C++ ABI 3.2.1:
816 // This ABI specifies that adj contains twice the this
817 // adjustment, plus 1 if the member function is virtual. The
818 // least significant bit of adj then makes exactly the same
819 // discrimination as the least significant bit of ptr does for
820 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000821 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
822 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000823 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000824 } else {
825 // Itanium C++ ABI 2.3:
826 // For a virtual function, [the pointer field] is 1 plus the
827 // virtual table offset (in bytes) of the function,
828 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000829 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
830 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000831 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000832 }
833 } else {
John McCall2979fe02011-04-12 00:42:48 +0000834 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000835 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000836 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000837 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000838 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000839 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000840 } else {
John McCall2979fe02011-04-12 00:42:48 +0000841 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
842 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000843 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000844 }
John McCall2979fe02011-04-12 00:42:48 +0000845 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000846
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000847 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000848 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
849 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000850 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000851 }
John McCall1c456c82010-08-22 06:43:33 +0000852
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000853 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000854}
855
Richard Smithdafff942012-01-14 04:30:29 +0000856llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
857 QualType MPType) {
858 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
859 const ValueDecl *MPD = MP.getMemberPointerDecl();
860 if (!MPD)
861 return EmitNullMemberPointer(MPT);
862
Reid Kleckner452abac2013-05-09 21:01:17 +0000863 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000864
865 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
866 return BuildMemberPointer(MD, ThisAdjustment);
867
868 CharUnits FieldOffset =
869 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
870 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
871}
872
John McCall131d97d2010-08-22 08:30:07 +0000873/// The comparison algorithm is pretty easy: the member pointers are
874/// the same if they're either bitwise identical *or* both null.
875///
876/// ARM is different here only because null-ness is more complicated.
877llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000878ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
879 llvm::Value *L,
880 llvm::Value *R,
881 const MemberPointerType *MPT,
882 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000883 CGBuilderTy &Builder = CGF.Builder;
884
John McCall131d97d2010-08-22 08:30:07 +0000885 llvm::ICmpInst::Predicate Eq;
886 llvm::Instruction::BinaryOps And, Or;
887 if (Inequality) {
888 Eq = llvm::ICmpInst::ICMP_NE;
889 And = llvm::Instruction::Or;
890 Or = llvm::Instruction::And;
891 } else {
892 Eq = llvm::ICmpInst::ICMP_EQ;
893 And = llvm::Instruction::And;
894 Or = llvm::Instruction::Or;
895 }
896
John McCall7a9aac22010-08-23 01:21:21 +0000897 // Member data pointers are easy because there's a unique null
898 // value, so it just comes down to bitwise equality.
899 if (MPT->isMemberDataPointer())
900 return Builder.CreateICmp(Eq, L, R);
901
902 // For member function pointers, the tautologies are more complex.
903 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000904 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000905 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000906 // (L == R) <==> (L.ptr == R.ptr &&
907 // (L.adj == R.adj ||
908 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000909 // The inequality tautologies have exactly the same structure, except
910 // applying De Morgan's laws.
911
912 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
913 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
914
John McCall131d97d2010-08-22 08:30:07 +0000915 // This condition tests whether L.ptr == R.ptr. This must always be
916 // true for equality to hold.
917 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
918
919 // This condition, together with the assumption that L.ptr == R.ptr,
920 // tests whether the pointers are both null. ARM imposes an extra
921 // condition.
922 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
923 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
924
925 // This condition tests whether L.adj == R.adj. If this isn't
926 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000927 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
928 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000929 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
930
931 // Null member function pointers on ARM clear the low bit of Adj,
932 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000933 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000934 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
935
936 // Compute (l.adj | r.adj) & 1 and test it against zero.
937 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
938 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
939 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
940 "cmp.or.adj");
941 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
942 }
943
944 // Tie together all our conditions.
945 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
946 Result = Builder.CreateBinOp(And, PtrEq, Result,
947 Inequality ? "memptr.ne" : "memptr.eq");
948 return Result;
949}
950
951llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000952ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
953 llvm::Value *MemPtr,
954 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000955 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000956
957 /// For member data pointers, this is just a check against -1.
958 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000959 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000960 llvm::Value *NegativeOne =
961 llvm::Constant::getAllOnesValue(MemPtr->getType());
962 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
963 }
John McCall131d97d2010-08-22 08:30:07 +0000964
Daniel Dunbar914bc412011-04-19 23:10:47 +0000965 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000966 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000967
968 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
969 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
970
Daniel Dunbar914bc412011-04-19 23:10:47 +0000971 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
972 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000973 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000974 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000975 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000976 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000977 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
978 "memptr.isvirtual");
979 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000980 }
981
982 return Result;
983}
John McCall1c456c82010-08-22 06:43:33 +0000984
Reid Kleckner40ca9132014-05-13 22:05:45 +0000985bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
986 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
987 if (!RD)
988 return false;
989
Reid Klecknerd355ca72014-05-15 01:26:32 +0000990 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
991 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
992 // special members.
993 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +0000994 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
995 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +0000996 return true;
997 }
Reid Kleckner40ca9132014-05-13 22:05:45 +0000998 return false;
999}
1000
John McCall614dbdc2010-08-22 21:01:12 +00001001/// The Itanium ABI requires non-zero initialization only for data
1002/// member pointers, for which '0' is a valid offset.
1003bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001004 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001005}
John McCall5d865c322010-08-31 07:33:07 +00001006
John McCall82fb8922012-09-25 10:10:39 +00001007/// The Itanium ABI always places an offset to the complete object
1008/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001009void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1010 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001011 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001012 QualType ElementType,
1013 const CXXDestructorDecl *Dtor) {
1014 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001015 if (UseGlobalDelete) {
1016 // Derive the complete-object pointer, which is what we need
1017 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001018
David Majnemer0c0b6d92014-10-31 20:09:12 +00001019 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001020 auto *ClassDecl =
1021 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1022 llvm::Value *VTable =
1023 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001024
David Majnemer0c0b6d92014-10-31 20:09:12 +00001025 // Track back to entry -2 and pull out the offset there.
1026 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1027 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001028 llvm::Value *Offset =
1029 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001030
1031 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001032 llvm::Value *CompletePtr =
1033 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001034 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1035
1036 // If we're supposed to call the global delete, make sure we do so
1037 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001038 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1039 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001040 }
1041
1042 // FIXME: Provide a source location here even though there's no
1043 // CXXMemberCallExpr for dtor call.
1044 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1045 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1046
1047 if (UseGlobalDelete)
1048 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001049}
1050
David Majnemer442d0a22014-11-25 07:20:20 +00001051void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1052 // void __cxa_rethrow();
1053
1054 llvm::FunctionType *FTy =
1055 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1056
1057 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1058
1059 if (isNoReturn)
1060 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1061 else
1062 CGF.EmitRuntimeCallOrInvoke(Fn);
1063}
1064
David Majnemer7c237072015-03-05 00:46:22 +00001065static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1066 // void *__cxa_allocate_exception(size_t thrown_size);
1067
1068 llvm::FunctionType *FTy =
1069 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1070
1071 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1072}
1073
1074static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1075 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1076 // void (*dest) (void *));
1077
1078 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1079 llvm::FunctionType *FTy =
1080 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1081
1082 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1083}
1084
1085void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1086 QualType ThrowType = E->getSubExpr()->getType();
1087 // Now allocate the exception object.
1088 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1089 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1090
1091 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1092 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1093 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1094
John McCall7f416cc2015-09-08 08:05:57 +00001095 CharUnits ExnAlign = getAlignmentOfExnObject();
1096 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001097
1098 // Now throw the exception.
1099 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1100 /*ForEH=*/true);
1101
1102 // The address of the destructor. If the exception type has a
1103 // trivial destructor (or isn't a record), we just pass null.
1104 llvm::Constant *Dtor = nullptr;
1105 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1106 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1107 if (!Record->hasTrivialDestructor()) {
1108 CXXDestructorDecl *DtorD = Record->getDestructor();
1109 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1110 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1111 }
1112 }
1113 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1114
1115 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1116 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1117}
1118
David Majnemer1162d252014-06-22 19:05:33 +00001119static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1120 // void *__dynamic_cast(const void *sub,
1121 // const abi::__class_type_info *src,
1122 // const abi::__class_type_info *dst,
1123 // std::ptrdiff_t src2dst_offset);
1124
1125 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1126 llvm::Type *PtrDiffTy =
1127 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1128
1129 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1130
1131 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1132
1133 // Mark the function as nounwind readonly.
1134 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1135 llvm::Attribute::ReadOnly };
1136 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1137 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1138
1139 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1140}
1141
1142static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1143 // void __cxa_bad_cast();
1144 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1145 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1146}
1147
1148/// \brief Compute the src2dst_offset hint as described in the
1149/// Itanium C++ ABI [2.9.7]
1150static CharUnits computeOffsetHint(ASTContext &Context,
1151 const CXXRecordDecl *Src,
1152 const CXXRecordDecl *Dst) {
1153 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1154 /*DetectVirtual=*/false);
1155
1156 // If Dst is not derived from Src we can skip the whole computation below and
1157 // return that Src is not a public base of Dst. Record all inheritance paths.
1158 if (!Dst->isDerivedFrom(Src, Paths))
1159 return CharUnits::fromQuantity(-2ULL);
1160
1161 unsigned NumPublicPaths = 0;
1162 CharUnits Offset;
1163
1164 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001165 for (const CXXBasePath &Path : Paths) {
1166 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001167 continue;
1168
1169 ++NumPublicPaths;
1170
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001171 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001172 // If the path contains a virtual base class we can't give any hint.
1173 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001174 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001175 return CharUnits::fromQuantity(-1ULL);
1176
1177 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1178 continue;
1179
1180 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001181 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1182 Offset += L.getBaseClassOffset(
1183 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001184 }
1185 }
1186
1187 // -2: Src is not a public base of Dst.
1188 if (NumPublicPaths == 0)
1189 return CharUnits::fromQuantity(-2ULL);
1190
1191 // -3: Src is a multiple public base type but never a virtual base type.
1192 if (NumPublicPaths > 1)
1193 return CharUnits::fromQuantity(-3ULL);
1194
1195 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1196 // Return the offset of Src from the origin of Dst.
1197 return Offset;
1198}
1199
1200static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1201 // void __cxa_bad_typeid();
1202 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1203
1204 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1205}
1206
1207bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1208 QualType SrcRecordTy) {
1209 return IsDeref;
1210}
1211
1212void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1213 llvm::Value *Fn = getBadTypeidFn(CGF);
1214 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1215 CGF.Builder.CreateUnreachable();
1216}
1217
1218llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1219 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001220 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001221 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001222 auto *ClassDecl =
1223 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001224 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001225 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001226
1227 // Load the type info.
1228 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001229 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001230}
1231
1232bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1233 QualType SrcRecordTy) {
1234 return SrcIsPtr;
1235}
1236
1237llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001238 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001239 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1240 llvm::Type *PtrDiffLTy =
1241 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1242 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1243
1244 llvm::Value *SrcRTTI =
1245 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1246 llvm::Value *DestRTTI =
1247 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1248
1249 // Compute the offset hint.
1250 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1251 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1252 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1253 PtrDiffLTy,
1254 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1255
1256 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001257 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001258 Value = CGF.EmitCastToVoidPtr(Value);
1259
1260 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1261 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1262 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1263
1264 /// C++ [expr.dynamic.cast]p9:
1265 /// A failed cast to reference type throws std::bad_cast
1266 if (DestTy->isReferenceType()) {
1267 llvm::BasicBlock *BadCastBlock =
1268 CGF.createBasicBlock("dynamic_cast.bad_cast");
1269
1270 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1271 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1272
1273 CGF.EmitBlock(BadCastBlock);
1274 EmitBadCastCall(CGF);
1275 }
1276
1277 return Value;
1278}
1279
1280llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001281 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001282 QualType SrcRecordTy,
1283 QualType DestTy) {
1284 llvm::Type *PtrDiffLTy =
1285 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1286 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1287
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001288 auto *ClassDecl =
1289 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001290 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001291 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1292 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001293
1294 // Get the offset-to-top from the vtable.
1295 llvm::Value *OffsetToTop =
1296 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001297 OffsetToTop =
1298 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1299 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001300
1301 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001302 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001303 Value = CGF.EmitCastToVoidPtr(Value);
1304 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1305
1306 return CGF.Builder.CreateBitCast(Value, DestLTy);
1307}
1308
1309bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1310 llvm::Value *Fn = getBadCastFn(CGF);
1311 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1312 CGF.Builder.CreateUnreachable();
1313 return true;
1314}
1315
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001316llvm::Value *
1317ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001318 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001319 const CXXRecordDecl *ClassDecl,
1320 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001321 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001322 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001323 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1324 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001325
1326 llvm::Value *VBaseOffsetPtr =
1327 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1328 "vbase.offset.ptr");
1329 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1330 CGM.PtrDiffTy->getPointerTo());
1331
1332 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001333 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1334 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001335
1336 return VBaseOffset;
1337}
1338
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001339void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1340 // Just make sure we're in sync with TargetCXXABI.
1341 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1342
Rafael Espindolac3cde362013-12-09 14:51:17 +00001343 // The constructor used for constructing this as a base class;
1344 // ignores virtual bases.
1345 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1346
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001347 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001348 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001349 if (!D->getParent()->isAbstract()) {
1350 // We don't need to emit the complete ctor if the class is abstract.
1351 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1352 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001353}
1354
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001355void
1356ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1357 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001358 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001359
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001360 // All parameters are already in place except VTT, which goes after 'this'.
1361 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001362
1363 // Check if we need to add a VTT parameter (which has type void **).
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001364 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1365 ArgTys.insert(ArgTys.begin() + 1,
1366 Context.getPointerType(Context.VoidPtrTy));
John McCall5d865c322010-08-31 07:33:07 +00001367}
1368
Reid Klecknere7de47e2013-07-22 13:51:44 +00001369void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001370 // The destructor used for destructing this as a base class; ignores
1371 // virtual bases.
1372 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001373
1374 // The destructor used for destructing this as a most-derived class;
1375 // call the base destructor and then destructs any virtual bases.
1376 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1377
Rafael Espindolac3cde362013-12-09 14:51:17 +00001378 // The destructor in a virtual table is always a 'deleting'
1379 // destructor, which calls the complete destructor and then uses the
1380 // appropriate operator delete.
1381 if (D->isVirtual())
1382 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001383}
1384
Reid Kleckner89077a12013-12-17 19:46:40 +00001385void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1386 QualType &ResTy,
1387 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001388 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001389 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001390
1391 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001392 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001393 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001394
1395 // FIXME: avoid the fake decl
1396 QualType T = Context.getPointerType(Context.VoidPtrTy);
1397 ImplicitParamDecl *VTTDecl
Craig Topper8a13c412014-05-21 05:09:00 +00001398 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
John McCall5d865c322010-08-31 07:33:07 +00001399 &Context.Idents.get("vtt"), T);
Reid Kleckner89077a12013-12-17 19:46:40 +00001400 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001401 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001402 }
1403}
1404
John McCall5d865c322010-08-31 07:33:07 +00001405void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001406 // Naked functions have no prolog.
1407 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1408 return;
1409
John McCall5d865c322010-08-31 07:33:07 +00001410 /// Initialize the 'this' slot.
1411 EmitThisParam(CGF);
1412
1413 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001414 if (getStructorImplicitParamDecl(CGF)) {
1415 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1416 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001417 }
John McCall5d865c322010-08-31 07:33:07 +00001418
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001419 /// If this is a function that the ABI specifies returns 'this', initialize
1420 /// the return slot to 'this' at the start of the function.
1421 ///
1422 /// Unlike the setting of return types, this is done within the ABI
1423 /// implementation instead of by clients of CGCXXABI because:
1424 /// 1) getThisValue is currently protected
1425 /// 2) in theory, an ABI could implement 'this' returns some other way;
1426 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001427 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001428 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001429}
1430
Reid Kleckner89077a12013-12-17 19:46:40 +00001431unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1432 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1433 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1434 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1435 return 0;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001436
Reid Kleckner89077a12013-12-17 19:46:40 +00001437 // Insert the implicit 'vtt' argument as the second argument.
1438 llvm::Value *VTT =
1439 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1440 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1441 Args.insert(Args.begin() + 1,
1442 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1443 return 1; // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001444}
1445
1446void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1447 const CXXDestructorDecl *DD,
1448 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001449 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001450 GlobalDecl GD(DD, Type);
1451 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1452 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1453
John McCallb92ab1a2016-10-26 23:46:34 +00001454 CGCallee Callee;
1455 if (getContext().getLangOpts().AppleKext &&
1456 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001457 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001458 else
1459 Callee =
1460 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1461 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001462
John McCall7f416cc2015-09-08 08:05:57 +00001463 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001464 This.getPointer(), VTT, VTTTy,
1465 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001466}
1467
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001468void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1469 const CXXRecordDecl *RD) {
1470 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1471 if (VTable->hasInitializer())
1472 return;
1473
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001474 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001475 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1476 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001477 llvm::Constant *RTTI =
1478 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001479
1480 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001481 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001482 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001483 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1484 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001485
1486 // Set the correct linkage.
1487 VTable->setLinkage(Linkage);
1488
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001489 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1490 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001491
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001492 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001493 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001494
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001495 // Use pointer alignment for the vtable. Otherwise we would align them based
1496 // on the size of the initializer which doesn't make sense as only single
1497 // values are read.
1498 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1499 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1500
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001501 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1502 // we will emit the typeinfo for the fundamental types. This is the
1503 // same behaviour as GCC.
1504 const DeclContext *DC = RD->getDeclContext();
1505 if (RD->getIdentifier() &&
1506 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1507 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1508 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1509 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001510 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001511
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001512 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001513 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001514}
1515
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001516bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1517 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1518 if (Vptr.NearestVBase == nullptr)
1519 return false;
1520 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001521}
1522
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001523llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1524 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1525 const CXXRecordDecl *NearestVBase) {
1526
1527 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1528 NeedsVTTParameter(CGF.CurGD)) {
1529 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1530 NearestVBase);
1531 }
1532 return getVTableAddressPoint(Base, VTableClass);
1533}
1534
1535llvm::Constant *
1536ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1537 const CXXRecordDecl *VTableClass) {
1538 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001539
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001540 // Find the appropriate vtable within the vtable group, and the address point
1541 // within that vtable.
1542 VTableLayout::AddressPointLocation AddressPoint =
1543 CGM.getItaniumVTableContext()
1544 .getVTableLayout(VTableClass)
1545 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001546 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001547 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001548 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1549 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001550 };
1551
David Blaikiee3b172a2015-04-02 18:55:21 +00001552 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1553 VTable, Indices);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001554}
1555
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001556llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1557 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1558 const CXXRecordDecl *NearestVBase) {
1559 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1560 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1561
1562 // Get the secondary vpointer index.
1563 uint64_t VirtualPointerIndex =
1564 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1565
1566 /// Load the VTT.
1567 llvm::Value *VTT = CGF.LoadCXXVTT();
1568 if (VirtualPointerIndex)
1569 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1570
1571 // And load the address point from the VTT.
1572 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1573}
1574
1575llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1576 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1577 return getVTableAddressPoint(Base, VTableClass);
1578}
1579
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001580llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1581 CharUnits VPtrOffset) {
1582 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1583
1584 llvm::GlobalVariable *&VTable = VTables[RD];
1585 if (VTable)
1586 return VTable;
1587
Eric Christopherd160c502016-01-29 01:35:53 +00001588 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001589 CGM.addDeferredVTable(RD);
1590
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001591 SmallString<256> Name;
1592 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001593 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001594
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001595 const VTableLayout &VTLayout =
1596 CGM.getItaniumVTableContext().getVTableLayout(RD);
1597 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001598
1599 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001600 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001601 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001602
1603 if (RD->hasAttr<DLLImportAttr>())
1604 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1605 else if (RD->hasAttr<DLLExportAttr>())
1606 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1607
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001608 return VTable;
1609}
1610
John McCallb92ab1a2016-10-26 23:46:34 +00001611CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1612 GlobalDecl GD,
1613 Address This,
1614 llvm::Type *Ty,
1615 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001616 GD = GD.getCanonicalDecl();
1617 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001618 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1619 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001620
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001621 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCallb92ab1a2016-10-26 23:46:34 +00001622 llvm::Value *VFunc;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001623 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
John McCallb92ab1a2016-10-26 23:46:34 +00001624 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001625 MethodDecl->getParent(), VTable,
1626 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1627 } else {
1628 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1629
1630 llvm::Value *VFuncPtr =
1631 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001632 auto *VFuncLoad =
1633 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1634
1635 // Add !invariant.load md to virtual function load to indicate that
1636 // function didn't change inside vtable.
1637 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1638 // help in devirtualization because it will only matter if we will have 2
1639 // the same virtual function loads from the same vtable load, which won't
1640 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1641 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1642 CGM.getCodeGenOpts().StrictVTablePointers)
1643 VFuncLoad->setMetadata(
1644 llvm::LLVMContext::MD_invariant_load,
1645 llvm::MDNode::get(CGM.getLLVMContext(),
1646 llvm::ArrayRef<llvm::Metadata *>()));
1647 VFunc = VFuncLoad;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001648 }
John McCallb92ab1a2016-10-26 23:46:34 +00001649
1650 CGCallee Callee(MethodDecl, VFunc);
1651 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001652}
1653
David Majnemer0c0b6d92014-10-31 20:09:12 +00001654llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1655 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001656 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001657 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001658 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1659
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001660 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1661 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001662 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001663 CGCallee Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001664 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1665 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001666
John McCall7f416cc2015-09-08 08:05:57 +00001667 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1668 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001669 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001670 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001671}
1672
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001673void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001674 CodeGenVTables &VTables = CGM.getVTables();
1675 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001676 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001677}
1678
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001679bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001680 // We don't emit available_externally vtables if we are in -fapple-kext mode
1681 // because kext mode does not permit devirtualization.
1682 if (CGM.getLangOpts().AppleKext)
1683 return false;
1684
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001685 // If we don't have any inline virtual functions, and if vtable is not hidden,
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001686 // then we are safe to emit available_externally copy of vtable.
1687 // FIXME we can still emit a copy of the vtable if we
1688 // can emit definition of the inline functions.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001689 return !hasAnyUsedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001690}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001691static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001692 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001693 int64_t NonVirtualAdjustment,
1694 int64_t VirtualAdjustment,
1695 bool IsReturnAdjustment) {
1696 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001697 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001698
John McCall7f416cc2015-09-08 08:05:57 +00001699 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001700
John McCall7f416cc2015-09-08 08:05:57 +00001701 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001702 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001703 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1704 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001705 }
1706
John McCall7f416cc2015-09-08 08:05:57 +00001707 // Perform the virtual adjustment if we have one.
1708 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001709 if (VirtualAdjustment) {
1710 llvm::Type *PtrDiffTy =
1711 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1712
John McCall7f416cc2015-09-08 08:05:57 +00001713 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001714 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1715
1716 llvm::Value *OffsetPtr =
1717 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1718
1719 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1720
1721 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001722 llvm::Value *Offset =
1723 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001724
1725 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001726 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1727 } else {
1728 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001729 }
1730
John McCall7f416cc2015-09-08 08:05:57 +00001731 // In a derived-to-base conversion, the non-virtual adjustment is
1732 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001733 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001734 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1735 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001736 }
1737
1738 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001739 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001740}
1741
1742llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001743 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001744 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001745 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1746 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001747 /*IsReturnAdjustment=*/false);
1748}
1749
1750llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001751ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001752 const ReturnAdjustment &RA) {
1753 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1754 RA.Virtual.Itanium.VBaseOffsetOffset,
1755 /*IsReturnAdjustment=*/true);
1756}
1757
John McCall5d865c322010-08-31 07:33:07 +00001758void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1759 RValue RV, QualType ResultType) {
1760 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1761 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1762
1763 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001764 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001765 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1766 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1767}
John McCall8ed55a52010-09-02 09:58:18 +00001768
1769/************************** Array allocation cookies **************************/
1770
John McCallb91cd662012-05-01 05:23:51 +00001771CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1772 // The array cookie is a size_t; pad that up to the element alignment.
1773 // The cookie is actually right-justified in that space.
1774 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1775 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001776}
1777
John McCall7f416cc2015-09-08 08:05:57 +00001778Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1779 Address NewPtr,
1780 llvm::Value *NumElements,
1781 const CXXNewExpr *expr,
1782 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001783 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001784
John McCall7f416cc2015-09-08 08:05:57 +00001785 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001786
John McCall9bca9232010-09-02 10:25:57 +00001787 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001788 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001789
1790 // The size of the cookie.
1791 CharUnits CookieSize =
1792 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001793 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001794
1795 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001796 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001797 CharUnits CookieOffset = CookieSize - SizeSize;
1798 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001799 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001800
1801 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001802 Address NumElementsPtr =
1803 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001804 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001805
1806 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001807 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001808 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001809 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001810 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1811 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001812 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001813 llvm::Constant *F =
1814 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001815 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001816 }
John McCall8ed55a52010-09-02 09:58:18 +00001817
1818 // Finally, compute a pointer to the actual data buffer by skipping
1819 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001820 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001821}
1822
John McCallb91cd662012-05-01 05:23:51 +00001823llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001824 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001825 CharUnits cookieSize) {
1826 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001827 Address numElementsPtr = allocPtr;
1828 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001829 if (!numElementsOffset.isZero())
1830 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001831 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001832
John McCall7f416cc2015-09-08 08:05:57 +00001833 unsigned AS = allocPtr.getAddressSpace();
1834 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001835 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001836 return CGF.Builder.CreateLoad(numElementsPtr);
1837 // In asan mode emit a function call instead of a regular load and let the
1838 // run-time deal with it: if the shadow is properly poisoned return the
1839 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1840 // We can't simply ignore this load using nosanitize metadata because
1841 // the metadata may be lost.
1842 llvm::FunctionType *FTy =
1843 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1844 llvm::Constant *F =
1845 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001846 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001847}
1848
John McCallb91cd662012-05-01 05:23:51 +00001849CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001850 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001851 // struct array_cookie {
1852 // std::size_t element_size; // element_size != 0
1853 // std::size_t element_count;
1854 // };
John McCallc19c7062013-01-25 23:36:19 +00001855 // But the base ABI doesn't give anything an alignment greater than
1856 // 8, so we can dismiss this as typical ABI-author blindness to
1857 // actual language complexity and round up to the element alignment.
1858 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1859 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001860}
1861
John McCall7f416cc2015-09-08 08:05:57 +00001862Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1863 Address newPtr,
1864 llvm::Value *numElements,
1865 const CXXNewExpr *expr,
1866 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001867 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001868
John McCall8ed55a52010-09-02 09:58:18 +00001869 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001870 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001871
1872 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001873 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001874 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1875 getContext().getTypeSizeInChars(elementType).getQuantity());
1876 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001877
1878 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001879 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001880 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001881
1882 // Finally, compute a pointer to the actual data buffer by skipping
1883 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001884 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001885 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001886}
1887
John McCallb91cd662012-05-01 05:23:51 +00001888llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001889 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001890 CharUnits cookieSize) {
1891 // The number of elements is at offset sizeof(size_t) relative to
1892 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001893 Address numElementsPtr
1894 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001895
John McCall7f416cc2015-09-08 08:05:57 +00001896 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001897 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001898}
1899
John McCall68ff0372010-09-08 01:44:27 +00001900/*********************** Static local initialization **************************/
1901
1902static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001903 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001904 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001905 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001906 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001907 GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001908 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001909 llvm::AttributeSet::get(CGM.getLLVMContext(),
1910 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001911 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001912}
1913
1914static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001915 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001916 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001917 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001918 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001919 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001920 llvm::AttributeSet::get(CGM.getLLVMContext(),
1921 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001922 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001923}
1924
1925static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001926 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001927 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001928 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001929 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Nick Lewyckyadcec492012-02-13 23:45:02 +00001930 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
Bill Wendling8594fcb2013-01-31 00:30:05 +00001931 llvm::AttributeSet::get(CGM.getLLVMContext(),
1932 llvm::AttributeSet::FunctionIndex,
Bill Wendling207f0532012-12-20 19:27:06 +00001933 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001934}
1935
1936namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001937 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001938 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001939 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001940
Craig Topper4f12f102014-03-12 06:41:41 +00001941 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001942 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1943 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001944 }
1945 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001946}
John McCall68ff0372010-09-08 01:44:27 +00001947
1948/// The ARM code here follows the Itanium code closely enough that we
1949/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001950void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1951 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001952 llvm::GlobalVariable *var,
1953 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001954 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001955
Richard Smith62f19e72016-06-25 00:15:56 +00001956 // Inline variables that weren't instantiated from variable templates have
1957 // partially-ordered initialization within their translation unit.
1958 bool NonTemplateInline =
1959 D.isInline() &&
1960 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1961
1962 // We only need to use thread-safe statics for local non-TLS variables and
1963 // inline variables; other global initialization is always single-threaded
1964 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001965 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001966 (D.isLocalVarDecl() || NonTemplateInline) &&
1967 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001968
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001969 // If we have a global variable with internal linkage and thread-safe statics
1970 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001971 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1972
1973 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00001974 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00001975 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00001976 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00001977 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00001978 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00001979 // Guard variables are 64 bits in the generic ABI and size width on ARM
1980 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00001981 if (UseARMGuardVarABI) {
1982 guardTy = CGF.SizeTy;
1983 guardAlignment = CGF.getSizeAlign();
1984 } else {
1985 guardTy = CGF.Int64Ty;
1986 guardAlignment = CharUnits::fromQuantity(
1987 CGM.getDataLayout().getABITypeAlignment(guardTy));
1988 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001989 }
John McCallb88a5662012-03-30 21:00:39 +00001990 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00001991
John McCallb88a5662012-03-30 21:00:39 +00001992 // Create the guard variable if we don't already have it (as we
1993 // might if we're double-emitting this function body).
1994 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1995 if (!guard) {
1996 // Mangle the name for the guard.
1997 SmallString<256> guardName;
1998 {
1999 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002000 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002001 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002002
John McCallb88a5662012-03-30 21:00:39 +00002003 // Create the guard variable with a zero-initializer.
2004 // Just absorb linkage and visibility from the guarded variable.
2005 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2006 false, var->getLinkage(),
2007 llvm::ConstantInt::get(guardTy, 0),
2008 guardName.str());
2009 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002010 // If the variable is thread-local, so is its guard variable.
2011 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002012 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002013
Yaron Keren5bfa1082015-09-03 20:33:29 +00002014 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2015 // group as the associated data object." In practice, this doesn't work for
2016 // non-ELF object formats, so only do it for ELF.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002017 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002018 if (!D.isLocalVarDecl() && C &&
2019 CGM.getTarget().getTriple().isOSBinFormatELF()) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002020 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002021 // An inline variable's guard function is run from the per-TU
2022 // initialization function, not via a dedicated global ctor function, so
2023 // we can't put it in a comdat.
2024 if (!NonTemplateInline)
2025 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002026 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2027 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002028 }
2029
John McCallb88a5662012-03-30 21:00:39 +00002030 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2031 }
John McCall87590e62012-03-30 07:09:50 +00002032
John McCall7f416cc2015-09-08 08:05:57 +00002033 Address guardAddr = Address(guard, guardAlignment);
2034
John McCall68ff0372010-09-08 01:44:27 +00002035 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002036 //
John McCall68ff0372010-09-08 01:44:27 +00002037 // Itanium C++ ABI 3.3.2:
2038 // The following is pseudo-code showing how these functions can be used:
2039 // if (obj_guard.first_byte == 0) {
2040 // if ( __cxa_guard_acquire (&obj_guard) ) {
2041 // try {
2042 // ... initialize the object ...;
2043 // } catch (...) {
2044 // __cxa_guard_abort (&obj_guard);
2045 // throw;
2046 // }
2047 // ... queue object destructor with __cxa_atexit() ...;
2048 // __cxa_guard_release (&obj_guard);
2049 // }
2050 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002051
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002052 // Load the first byte of the guard variable.
2053 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002054 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002055
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002056 // Itanium ABI:
2057 // An implementation supporting thread-safety on multiprocessor
2058 // systems must also guarantee that references to the initialized
2059 // object do not occur before the load of the initialization flag.
2060 //
2061 // In LLVM, we do this by marking the load Acquire.
2062 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002063 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002064
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002065 // For ARM, we should only check the first bit, rather than the entire byte:
2066 //
2067 // ARM C++ ABI 3.2.3.1:
2068 // To support the potential use of initialization guard variables
2069 // as semaphores that are the target of ARM SWP and LDREX/STREX
2070 // synchronizing instructions we define a static initialization
2071 // guard variable to be a 4-byte aligned, 4-byte word with the
2072 // following inline access protocol.
2073 // #define INITIALIZED 1
2074 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2075 // if (__cxa_guard_acquire(&obj_guard))
2076 // ...
2077 // }
2078 //
2079 // and similarly for ARM64:
2080 //
2081 // ARM64 C++ ABI 3.2.2:
2082 // This ABI instead only specifies the value bit 0 of the static guard
2083 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2084 // variable is not initialized and 1 when it is.
2085 llvm::Value *V =
2086 (UseARMGuardVarABI && !useInt8GuardVariable)
2087 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2088 : LI;
2089 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002090
2091 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2092 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2093
2094 // Check if the first byte of the guard variable is zero.
John McCallb88a5662012-03-30 21:00:39 +00002095 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
John McCall68ff0372010-09-08 01:44:27 +00002096
2097 CGF.EmitBlock(InitCheckBlock);
2098
2099 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002100 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002101 // Call __cxa_guard_acquire.
2102 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002103 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002104
2105 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2106
2107 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2108 InitBlock, EndBlock);
2109
2110 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002111 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002112
2113 CGF.EmitBlock(InitBlock);
2114 }
2115
2116 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002117 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002118
John McCall5aa52592011-06-17 07:33:57 +00002119 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002120 // Pop the guard-abort cleanup if we pushed one.
2121 CGF.PopCleanupBlock();
2122
2123 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002124 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2125 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002126 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002127 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002128 }
2129
2130 CGF.EmitBlock(EndBlock);
2131}
John McCallc84ed6a2012-05-01 06:13:13 +00002132
2133/// Register a global destructor using __cxa_atexit.
2134static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2135 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002136 llvm::Constant *addr,
2137 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002138 const char *Name = "__cxa_atexit";
2139 if (TLS) {
2140 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002141 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002142 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002143
John McCallc84ed6a2012-05-01 06:13:13 +00002144 // We're assuming that the destructor function is something we can
2145 // reasonably call with the default CC. Go ahead and cast it to the
2146 // right prototype.
2147 llvm::Type *dtorTy =
2148 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2149
2150 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2151 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2152 llvm::FunctionType *atexitTy =
2153 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2154
2155 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002156 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002157 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2158 fn->setDoesNotThrow();
2159
2160 // Create a variable that binds the atexit to this shared object.
2161 llvm::Constant *handle =
2162 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2163
2164 llvm::Value *args[] = {
2165 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2166 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2167 handle
2168 };
John McCall882987f2013-02-28 19:01:20 +00002169 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002170}
2171
2172/// Register a global destructor as best as we know how.
2173void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002174 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002175 llvm::Constant *dtor,
2176 llvm::Constant *addr) {
2177 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002178 if (CGM.getCodeGenOpts().CXAAtExit)
2179 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2180
2181 if (D.getTLSKind())
2182 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002183
2184 // In Apple kexts, we want to add a global destructor entry.
2185 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002186 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002187 // Generate a global destructor entry.
2188 return CGM.AddCXXDtorEntry(dtor, addr);
2189 }
2190
David Blaikieebe87e12013-08-27 23:57:18 +00002191 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002192}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002193
David Majnemer9b21c332014-07-11 20:28:10 +00002194static bool isThreadWrapperReplaceable(const VarDecl *VD,
2195 CodeGen::CodeGenModule &CGM) {
2196 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002197 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002198 // the thread wrapper instead of directly referencing the backing variable.
2199 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002200 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002201}
2202
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002203/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002204/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002205/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002206static llvm::GlobalValue::LinkageTypes
2207getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2208 llvm::GlobalValue::LinkageTypes VarLinkage =
2209 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2210
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002211 // For internal linkage variables, we don't need an external or weak wrapper.
2212 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2213 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002214
David Majnemer9b21c332014-07-11 20:28:10 +00002215 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002216 if (isThreadWrapperReplaceable(VD, CGM))
2217 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2218 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2219 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002220 return llvm::GlobalValue::WeakODRLinkage;
2221}
2222
2223llvm::Function *
2224ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002225 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002226 // Mangle the name for the thread_local wrapper function.
2227 SmallString<256> WrapperName;
2228 {
2229 llvm::raw_svector_ostream Out(WrapperName);
2230 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002231 }
2232
Akira Hatanaka26907f92016-01-15 03:34:06 +00002233 // FIXME: If VD is a definition, we should regenerate the function attributes
2234 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002235 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002236 return cast<llvm::Function>(V);
2237
Akira Hatanaka26907f92016-01-15 03:34:06 +00002238 QualType RetQT = VD->getType();
2239 if (RetQT->isReferenceType())
2240 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002241
John McCallc56a8b32016-03-11 04:30:31 +00002242 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2243 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002244
2245 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002246 llvm::Function *Wrapper =
2247 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2248 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002249
2250 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2251
2252 if (VD->hasDefinition())
2253 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2254
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002255 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002256 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2257 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2258 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002259 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002260
2261 if (isThreadWrapperReplaceable(VD, CGM)) {
2262 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2263 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2264 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002265 return Wrapper;
2266}
2267
2268void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002269 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2270 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2271 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002272 llvm::Function *InitFunc = nullptr;
2273 if (!CXXThreadLocalInits.empty()) {
2274 // Generate a guarded initialization function.
2275 llvm::FunctionType *FTy =
2276 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002277 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2278 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002279 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002280 /*TLS=*/true);
2281 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2282 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2283 llvm::GlobalVariable::InternalLinkage,
2284 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2285 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002286
2287 CharUnits GuardAlign = CharUnits::One();
2288 Guard->setAlignment(GuardAlign.getQuantity());
2289
David Majnemerb3341ea2014-10-05 05:05:40 +00002290 CodeGenFunction(CGM)
John McCall7f416cc2015-09-08 08:05:57 +00002291 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2292 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002293 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2294 if (CGM.getTarget().getTriple().isOSDarwin()) {
2295 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2296 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2297 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002298 }
Richard Smith5a99c492015-12-01 01:10:48 +00002299 for (const VarDecl *VD : CXXThreadLocals) {
2300 llvm::GlobalVariable *Var =
2301 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002302
David Majnemer9b21c332014-07-11 20:28:10 +00002303 // Some targets require that all access to thread local variables go through
2304 // the thread wrapper. This means that we cannot attempt to create a thread
2305 // wrapper or a thread helper.
2306 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2307 continue;
2308
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002309 // Mangle the name for the thread_local initialization function.
2310 SmallString<256> InitFnName;
2311 {
2312 llvm::raw_svector_ostream Out(InitFnName);
2313 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002314 }
2315
2316 // If we have a definition for the variable, emit the initialization
2317 // function as an alias to the global Init function (if any). Otherwise,
2318 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002319 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002320 bool InitIsInitFunc = false;
2321 if (VD->hasDefinition()) {
2322 InitIsInitFunc = true;
2323 if (InitFunc)
Rafael Espindola234405b2014-05-17 21:30:14 +00002324 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2325 InitFunc);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002326 } else {
2327 // Emit a weak global function referring to the initialization function.
2328 // This function will not exist if the TU defining the thread_local
2329 // variable in question does not need any dynamic initialization for
2330 // its thread_local variables.
2331 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2332 Init = llvm::Function::Create(
2333 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2334 &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002335 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002336 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002337 }
2338
2339 if (Init)
2340 Init->setVisibility(Var->getVisibility());
2341
2342 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2343 llvm::LLVMContext &Context = CGM.getModule().getContext();
2344 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002345 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002346 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002347 if (Init) {
2348 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2349 if (isThreadWrapperReplaceable(VD, CGM))
2350 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2351 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002352 } else {
2353 // Don't know whether we have an init function. Call it if it exists.
2354 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2355 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2356 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2357 Builder.CreateCondBr(Have, InitBB, ExitBB);
2358
2359 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002360 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002361 Builder.CreateBr(ExitBB);
2362
2363 Builder.SetInsertPoint(ExitBB);
2364 }
2365
2366 // For a reference, the result of the wrapper function is a pointer to
2367 // the referenced object.
2368 llvm::Value *Val = Var;
2369 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002370 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2371 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002372 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002373 if (Val->getType() != Wrapper->getReturnType())
2374 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2375 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002376 Builder.CreateRet(Val);
2377 }
2378}
2379
Richard Smith0f383742014-03-26 22:48:22 +00002380LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2381 const VarDecl *VD,
2382 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002383 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002384 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002385
Manman Renb0b3af72015-12-17 00:42:36 +00002386 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002387 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002388
2389 LValue LV;
2390 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002391 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002392 else
Manman Renb0b3af72015-12-17 00:42:36 +00002393 LV = CGF.MakeAddrLValue(CallVal, LValType,
2394 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002395 // FIXME: need setObjCGCLValueClass?
2396 return LV;
2397}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002398
2399/// Return whether the given global decl needs a VTT parameter, which it does
2400/// if it's a base constructor or destructor with virtual bases.
2401bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2402 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2403
2404 // We don't have any virtual bases, just return early.
2405 if (!MD->getParent()->getNumVBases())
2406 return false;
2407
2408 // Check if we have a base constructor.
2409 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2410 return true;
2411
2412 // Check if we have a base destructor.
2413 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2414 return true;
2415
2416 return false;
2417}
David Majnemere2cb8d12014-07-07 06:20:47 +00002418
2419namespace {
2420class ItaniumRTTIBuilder {
2421 CodeGenModule &CGM; // Per-module state.
2422 llvm::LLVMContext &VMContext;
2423 const ItaniumCXXABI &CXXABI; // Per-module state.
2424
2425 /// Fields - The fields of the RTTI descriptor currently being built.
2426 SmallVector<llvm::Constant *, 16> Fields;
2427
2428 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2429 llvm::GlobalVariable *
2430 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2431
2432 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2433 /// descriptor of the given type.
2434 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2435
2436 /// BuildVTablePointer - Build the vtable pointer for the given type.
2437 void BuildVTablePointer(const Type *Ty);
2438
2439 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2440 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2441 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2442
2443 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2444 /// classes with bases that do not satisfy the abi::__si_class_type_info
2445 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2446 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2447
2448 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2449 /// for pointer types.
2450 void BuildPointerTypeInfo(QualType PointeeTy);
2451
2452 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2453 /// type_info for an object type.
2454 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2455
2456 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2457 /// struct, used for member pointer types.
2458 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2459
2460public:
2461 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2462 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2463
2464 // Pointer type info flags.
2465 enum {
2466 /// PTI_Const - Type has const qualifier.
2467 PTI_Const = 0x1,
2468
2469 /// PTI_Volatile - Type has volatile qualifier.
2470 PTI_Volatile = 0x2,
2471
2472 /// PTI_Restrict - Type has restrict qualifier.
2473 PTI_Restrict = 0x4,
2474
2475 /// PTI_Incomplete - Type is incomplete.
2476 PTI_Incomplete = 0x8,
2477
2478 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2479 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002480 PTI_ContainingClassIncomplete = 0x10,
2481
2482 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2483 //PTI_TransactionSafe = 0x20,
2484
2485 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2486 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002487 };
2488
2489 // VMI type info flags.
2490 enum {
2491 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2492 VMI_NonDiamondRepeat = 0x1,
2493
2494 /// VMI_DiamondShaped - Class is diamond shaped.
2495 VMI_DiamondShaped = 0x2
2496 };
2497
2498 // Base class type info flags.
2499 enum {
2500 /// BCTI_Virtual - Base class is virtual.
2501 BCTI_Virtual = 0x1,
2502
2503 /// BCTI_Public - Base class is public.
2504 BCTI_Public = 0x2
2505 };
2506
2507 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2508 ///
2509 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002510 /// \param DLLExport - true to mark the RTTI value as DLLExport
2511 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2512 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002513};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002514}
David Majnemere2cb8d12014-07-07 06:20:47 +00002515
2516llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2517 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002518 SmallString<256> Name;
2519 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002520 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002521
2522 // We know that the mangled name of the type starts at index 4 of the
2523 // mangled name of the typename, so we can just index into it in order to
2524 // get the mangled name of the type.
2525 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2526 Name.substr(4));
2527
2528 llvm::GlobalVariable *GV =
2529 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2530
2531 GV->setInitializer(Init);
2532
2533 return GV;
2534}
2535
2536llvm::Constant *
2537ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2538 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002539 SmallString<256> Name;
2540 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002541 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002542
2543 // Look for an existing global.
2544 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2545
2546 if (!GV) {
2547 // Create a new global variable.
2548 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2549 /*Constant=*/true,
2550 llvm::GlobalValue::ExternalLinkage, nullptr,
2551 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002552 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2553 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2554 if (RD->hasAttr<DLLImportAttr>())
2555 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2556 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002557 }
2558
2559 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2560}
2561
2562/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2563/// info for that type is defined in the standard library.
2564static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2565 // Itanium C++ ABI 2.9.2:
2566 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2567 // the run-time support library. Specifically, the run-time support
2568 // library should contain type_info objects for the types X, X* and
2569 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2570 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2571 // long, unsigned long, long long, unsigned long long, float, double,
2572 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2573 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002574 //
2575 // GCC also emits RTTI for __int128.
2576 // FIXME: We do not emit RTTI information for decimal types here.
2577
2578 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002579 switch (Ty->getKind()) {
2580 case BuiltinType::Void:
2581 case BuiltinType::NullPtr:
2582 case BuiltinType::Bool:
2583 case BuiltinType::WChar_S:
2584 case BuiltinType::WChar_U:
2585 case BuiltinType::Char_U:
2586 case BuiltinType::Char_S:
2587 case BuiltinType::UChar:
2588 case BuiltinType::SChar:
2589 case BuiltinType::Short:
2590 case BuiltinType::UShort:
2591 case BuiltinType::Int:
2592 case BuiltinType::UInt:
2593 case BuiltinType::Long:
2594 case BuiltinType::ULong:
2595 case BuiltinType::LongLong:
2596 case BuiltinType::ULongLong:
2597 case BuiltinType::Half:
2598 case BuiltinType::Float:
2599 case BuiltinType::Double:
2600 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002601 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002602 case BuiltinType::Char16:
2603 case BuiltinType::Char32:
2604 case BuiltinType::Int128:
2605 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002606 return true;
2607
Alexey Bader954ba212016-04-08 13:40:33 +00002608#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2609 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002610#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002611 case BuiltinType::OCLSampler:
2612 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002613 case BuiltinType::OCLClkEvent:
2614 case BuiltinType::OCLQueue:
2615 case BuiltinType::OCLNDRange:
2616 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002617 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002618
2619 case BuiltinType::Dependent:
2620#define BUILTIN_TYPE(Id, SingletonId)
2621#define PLACEHOLDER_TYPE(Id, SingletonId) \
2622 case BuiltinType::Id:
2623#include "clang/AST/BuiltinTypes.def"
2624 llvm_unreachable("asking for RRTI for a placeholder type!");
2625
2626 case BuiltinType::ObjCId:
2627 case BuiltinType::ObjCClass:
2628 case BuiltinType::ObjCSel:
2629 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2630 }
2631
2632 llvm_unreachable("Invalid BuiltinType Kind!");
2633}
2634
2635static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2636 QualType PointeeTy = PointerTy->getPointeeType();
2637 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2638 if (!BuiltinTy)
2639 return false;
2640
2641 // Check the qualifiers.
2642 Qualifiers Quals = PointeeTy.getQualifiers();
2643 Quals.removeConst();
2644
2645 if (!Quals.empty())
2646 return false;
2647
2648 return TypeInfoIsInStandardLibrary(BuiltinTy);
2649}
2650
2651/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2652/// information for the given type exists in the standard library.
2653static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2654 // Type info for builtin types is defined in the standard library.
2655 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2656 return TypeInfoIsInStandardLibrary(BuiltinTy);
2657
2658 // Type info for some pointer types to builtin types is defined in the
2659 // standard library.
2660 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2661 return TypeInfoIsInStandardLibrary(PointerTy);
2662
2663 return false;
2664}
2665
2666/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2667/// the given type exists somewhere else, and that we should not emit the type
2668/// information in this translation unit. Assumes that it is not a
2669/// standard-library type.
2670static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2671 QualType Ty) {
2672 ASTContext &Context = CGM.getContext();
2673
2674 // If RTTI is disabled, assume it might be disabled in the
2675 // translation unit that defines any potential key function, too.
2676 if (!Context.getLangOpts().RTTI) return false;
2677
2678 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2679 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2680 if (!RD->hasDefinition())
2681 return false;
2682
2683 if (!RD->isDynamicClass())
2684 return false;
2685
2686 // FIXME: this may need to be reconsidered if the key function
2687 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002688 // N.B. We must always emit the RTTI data ourselves if there exists a key
2689 // function.
2690 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002691 if (CGM.getVTables().isVTableExternal(RD))
David Majnemerbe9022c2015-08-06 20:56:55 +00002692 return IsDLLImport ? false : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002693
David Majnemerbe9022c2015-08-06 20:56:55 +00002694 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002695 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002696 }
2697
2698 return false;
2699}
2700
2701/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2702static bool IsIncompleteClassType(const RecordType *RecordTy) {
2703 return !RecordTy->getDecl()->isCompleteDefinition();
2704}
2705
2706/// ContainsIncompleteClassType - Returns whether the given type contains an
2707/// incomplete class type. This is true if
2708///
2709/// * The given type is an incomplete class type.
2710/// * The given type is a pointer type whose pointee type contains an
2711/// incomplete class type.
2712/// * The given type is a member pointer type whose class is an incomplete
2713/// class type.
2714/// * The given type is a member pointer type whoise pointee type contains an
2715/// incomplete class type.
2716/// is an indirect or direct pointer to an incomplete class type.
2717static bool ContainsIncompleteClassType(QualType Ty) {
2718 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2719 if (IsIncompleteClassType(RecordTy))
2720 return true;
2721 }
2722
2723 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2724 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2725
2726 if (const MemberPointerType *MemberPointerTy =
2727 dyn_cast<MemberPointerType>(Ty)) {
2728 // Check if the class type is incomplete.
2729 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2730 if (IsIncompleteClassType(ClassType))
2731 return true;
2732
2733 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2734 }
2735
2736 return false;
2737}
2738
2739// CanUseSingleInheritance - Return whether the given record decl has a "single,
2740// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2741// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2742static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2743 // Check the number of bases.
2744 if (RD->getNumBases() != 1)
2745 return false;
2746
2747 // Get the base.
2748 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2749
2750 // Check that the base is not virtual.
2751 if (Base->isVirtual())
2752 return false;
2753
2754 // Check that the base is public.
2755 if (Base->getAccessSpecifier() != AS_public)
2756 return false;
2757
2758 // Check that the class is dynamic iff the base is.
2759 const CXXRecordDecl *BaseDecl =
2760 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2761 if (!BaseDecl->isEmpty() &&
2762 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2763 return false;
2764
2765 return true;
2766}
2767
2768void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2769 // abi::__class_type_info.
2770 static const char * const ClassTypeInfo =
2771 "_ZTVN10__cxxabiv117__class_type_infoE";
2772 // abi::__si_class_type_info.
2773 static const char * const SIClassTypeInfo =
2774 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2775 // abi::__vmi_class_type_info.
2776 static const char * const VMIClassTypeInfo =
2777 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2778
2779 const char *VTableName = nullptr;
2780
2781 switch (Ty->getTypeClass()) {
2782#define TYPE(Class, Base)
2783#define ABSTRACT_TYPE(Class, Base)
2784#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2785#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2786#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2787#include "clang/AST/TypeNodes.def"
2788 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2789
2790 case Type::LValueReference:
2791 case Type::RValueReference:
2792 llvm_unreachable("References shouldn't get here");
2793
2794 case Type::Auto:
2795 llvm_unreachable("Undeduced auto type shouldn't get here");
2796
Xiuli Pan9c14e282016-01-09 12:53:17 +00002797 case Type::Pipe:
2798 llvm_unreachable("Pipe types shouldn't get here");
2799
David Majnemere2cb8d12014-07-07 06:20:47 +00002800 case Type::Builtin:
2801 // GCC treats vector and complex types as fundamental types.
2802 case Type::Vector:
2803 case Type::ExtVector:
2804 case Type::Complex:
2805 case Type::Atomic:
2806 // FIXME: GCC treats block pointers as fundamental types?!
2807 case Type::BlockPointer:
2808 // abi::__fundamental_type_info.
2809 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2810 break;
2811
2812 case Type::ConstantArray:
2813 case Type::IncompleteArray:
2814 case Type::VariableArray:
2815 // abi::__array_type_info.
2816 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2817 break;
2818
2819 case Type::FunctionNoProto:
2820 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002821 // abi::__function_type_info.
2822 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002823 break;
2824
2825 case Type::Enum:
2826 // abi::__enum_type_info.
2827 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2828 break;
2829
2830 case Type::Record: {
2831 const CXXRecordDecl *RD =
2832 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2833
2834 if (!RD->hasDefinition() || !RD->getNumBases()) {
2835 VTableName = ClassTypeInfo;
2836 } else if (CanUseSingleInheritance(RD)) {
2837 VTableName = SIClassTypeInfo;
2838 } else {
2839 VTableName = VMIClassTypeInfo;
2840 }
2841
2842 break;
2843 }
2844
2845 case Type::ObjCObject:
2846 // Ignore protocol qualifiers.
2847 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2848
2849 // Handle id and Class.
2850 if (isa<BuiltinType>(Ty)) {
2851 VTableName = ClassTypeInfo;
2852 break;
2853 }
2854
2855 assert(isa<ObjCInterfaceType>(Ty));
2856 // Fall through.
2857
2858 case Type::ObjCInterface:
2859 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2860 VTableName = SIClassTypeInfo;
2861 } else {
2862 VTableName = ClassTypeInfo;
2863 }
2864 break;
2865
2866 case Type::ObjCObjectPointer:
2867 case Type::Pointer:
2868 // abi::__pointer_type_info.
2869 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2870 break;
2871
2872 case Type::MemberPointer:
2873 // abi::__pointer_to_member_type_info.
2874 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2875 break;
2876 }
2877
2878 llvm::Constant *VTable =
2879 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2880
2881 llvm::Type *PtrDiffTy =
2882 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2883
2884 // The vtable address point is 2.
2885 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002886 VTable =
2887 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002888 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2889
2890 Fields.push_back(VTable);
2891}
2892
2893/// \brief Return the linkage that the type info and type info name constants
2894/// should have for the given type.
2895static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2896 QualType Ty) {
2897 // Itanium C++ ABI 2.9.5p7:
2898 // In addition, it and all of the intermediate abi::__pointer_type_info
2899 // structs in the chain down to the abi::__class_type_info for the
2900 // incomplete class type must be prevented from resolving to the
2901 // corresponding type_info structs for the complete class type, possibly
2902 // by making them local static objects. Finally, a dummy class RTTI is
2903 // generated for the incomplete type that will not resolve to the final
2904 // complete class RTTI (because the latter need not exist), possibly by
2905 // making it a local static object.
2906 if (ContainsIncompleteClassType(Ty))
2907 return llvm::GlobalValue::InternalLinkage;
2908
2909 switch (Ty->getLinkage()) {
2910 case NoLinkage:
2911 case InternalLinkage:
2912 case UniqueExternalLinkage:
2913 return llvm::GlobalValue::InternalLinkage;
2914
2915 case VisibleNoLinkage:
2916 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002917 // RTTI is not enabled, which means that this type info struct is going
2918 // to be used for exception handling. Give it linkonce_odr linkage.
2919 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00002920 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00002921
2922 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2923 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2924 if (RD->hasAttr<WeakAttr>())
2925 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002926 if (CGM.getTriple().isWindowsItaniumEnvironment())
2927 if (RD->hasAttr<DLLImportAttr>())
2928 return llvm::GlobalValue::ExternalLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002929 if (RD->isDynamicClass()) {
2930 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2931 // MinGW won't export the RTTI information when there is a key function.
2932 // Make sure we emit our own copy instead of attempting to dllimport it.
2933 if (RD->hasAttr<DLLImportAttr>() &&
2934 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2935 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2936 return LT;
2937 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002938 }
2939
2940 return llvm::GlobalValue::LinkOnceODRLinkage;
2941 }
2942
2943 llvm_unreachable("Invalid linkage!");
2944}
2945
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002946llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
2947 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00002948 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00002949 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00002950
2951 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002952 SmallString<256> Name;
2953 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002954 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002955
2956 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2957 if (OldGV && !OldGV->isDeclaration()) {
2958 assert(!OldGV->hasAvailableExternallyLinkage() &&
2959 "available_externally typeinfos not yet implemented");
2960
2961 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2962 }
2963
2964 // Check if there is already an external RTTI descriptor for this type.
2965 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2966 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2967 return GetAddrOfExternalRTTIDescriptor(Ty);
2968
2969 // Emit the standard library with external linkage.
2970 llvm::GlobalVariable::LinkageTypes Linkage;
2971 if (IsStdLib)
2972 Linkage = llvm::GlobalValue::ExternalLinkage;
2973 else
2974 Linkage = getTypeInfoLinkage(CGM, Ty);
2975
2976 // Add the vtable pointer.
2977 BuildVTablePointer(cast<Type>(Ty));
2978
2979 // And the name.
2980 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2981 llvm::Constant *TypeNameField;
2982
2983 // If we're supposed to demote the visibility, be sure to set a flag
2984 // to use a string comparison for type_info comparisons.
2985 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2986 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2987 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2988 // The flag is the sign bit, which on ARM64 is defined to be clear
2989 // for global pointers. This is very ARM64-specific.
2990 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2991 llvm::Constant *flag =
2992 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2993 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2994 TypeNameField =
2995 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2996 } else {
2997 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2998 }
2999 Fields.push_back(TypeNameField);
3000
3001 switch (Ty->getTypeClass()) {
3002#define TYPE(Class, Base)
3003#define ABSTRACT_TYPE(Class, Base)
3004#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3005#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3006#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3007#include "clang/AST/TypeNodes.def"
3008 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3009
3010 // GCC treats vector types as fundamental types.
3011 case Type::Builtin:
3012 case Type::Vector:
3013 case Type::ExtVector:
3014 case Type::Complex:
3015 case Type::BlockPointer:
3016 // Itanium C++ ABI 2.9.5p4:
3017 // abi::__fundamental_type_info adds no data members to std::type_info.
3018 break;
3019
3020 case Type::LValueReference:
3021 case Type::RValueReference:
3022 llvm_unreachable("References shouldn't get here");
3023
3024 case Type::Auto:
3025 llvm_unreachable("Undeduced auto type shouldn't get here");
3026
Xiuli Pan9c14e282016-01-09 12:53:17 +00003027 case Type::Pipe:
3028 llvm_unreachable("Pipe type shouldn't get here");
3029
David Majnemere2cb8d12014-07-07 06:20:47 +00003030 case Type::ConstantArray:
3031 case Type::IncompleteArray:
3032 case Type::VariableArray:
3033 // Itanium C++ ABI 2.9.5p5:
3034 // abi::__array_type_info adds no data members to std::type_info.
3035 break;
3036
3037 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003038 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003039 // Itanium C++ ABI 2.9.5p5:
3040 // abi::__function_type_info adds no data members to std::type_info.
3041 break;
3042
3043 case Type::Enum:
3044 // Itanium C++ ABI 2.9.5p5:
3045 // abi::__enum_type_info adds no data members to std::type_info.
3046 break;
3047
3048 case Type::Record: {
3049 const CXXRecordDecl *RD =
3050 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3051 if (!RD->hasDefinition() || !RD->getNumBases()) {
3052 // We don't need to emit any fields.
3053 break;
3054 }
3055
3056 if (CanUseSingleInheritance(RD))
3057 BuildSIClassTypeInfo(RD);
3058 else
3059 BuildVMIClassTypeInfo(RD);
3060
3061 break;
3062 }
3063
3064 case Type::ObjCObject:
3065 case Type::ObjCInterface:
3066 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3067 break;
3068
3069 case Type::ObjCObjectPointer:
3070 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3071 break;
3072
3073 case Type::Pointer:
3074 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3075 break;
3076
3077 case Type::MemberPointer:
3078 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3079 break;
3080
3081 case Type::Atomic:
3082 // No fields, at least for the moment.
3083 break;
3084 }
3085
3086 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3087
Rafael Espindolacb92c192015-01-15 23:18:01 +00003088 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003089 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003090 new llvm::GlobalVariable(M, Init->getType(),
3091 /*Constant=*/true, Linkage, Init, Name);
3092
David Majnemere2cb8d12014-07-07 06:20:47 +00003093 // If there's already an old global variable, replace it with the new one.
3094 if (OldGV) {
3095 GV->takeName(OldGV);
3096 llvm::Constant *NewPtr =
3097 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3098 OldGV->replaceAllUsesWith(NewPtr);
3099 OldGV->eraseFromParent();
3100 }
3101
Yaron Keren04da2382015-07-29 15:42:28 +00003102 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3103 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3104
David Majnemere2cb8d12014-07-07 06:20:47 +00003105 // The Itanium ABI specifies that type_info objects must be globally
3106 // unique, with one exception: if the type is an incomplete class
3107 // type or a (possibly indirect) pointer to one. That exception
3108 // affects the general case of comparing type_info objects produced
3109 // by the typeid operator, which is why the comparison operators on
3110 // std::type_info generally use the type_info name pointers instead
3111 // of the object addresses. However, the language's built-in uses
3112 // of RTTI generally require class types to be complete, even when
3113 // manipulating pointers to those class types. This allows the
3114 // implementation of dynamic_cast to rely on address equality tests,
3115 // which is much faster.
3116
3117 // All of this is to say that it's important that both the type_info
3118 // object and the type_info name be uniqued when weakly emitted.
3119
3120 // Give the type_info object and name the formal visibility of the
3121 // type itself.
3122 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3123 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3124 // If the linkage is local, only default visibility makes sense.
3125 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3126 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3127 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3128 else
3129 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003130
David Majnemere2cb8d12014-07-07 06:20:47 +00003131 TypeName->setVisibility(llvmVisibility);
3132 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003133
3134 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3135 auto RD = Ty->getAsCXXRecordDecl();
3136 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3137 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3138 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Saleem Abdulrasool317dcc32016-12-05 22:40:20 +00003139 } else if (CGM.getLangOpts().RTTI && RD && RD->hasAttr<DLLImportAttr>()) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003140 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3141 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3142
3143 // Because the typename and the typeinfo are DLL import, convert them to
3144 // declarations rather than definitions. The initializers still need to
3145 // be constructed to calculate the type for the declarations.
3146 TypeName->setInitializer(nullptr);
3147 GV->setInitializer(nullptr);
3148 }
3149 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003150
3151 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3152}
3153
David Majnemere2cb8d12014-07-07 06:20:47 +00003154/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3155/// for the given Objective-C object type.
3156void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3157 // Drop qualifiers.
3158 const Type *T = OT->getBaseType().getTypePtr();
3159 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3160
3161 // The builtin types are abi::__class_type_infos and don't require
3162 // extra fields.
3163 if (isa<BuiltinType>(T)) return;
3164
3165 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3166 ObjCInterfaceDecl *Super = Class->getSuperClass();
3167
3168 // Root classes are also __class_type_info.
3169 if (!Super) return;
3170
3171 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3172
3173 // Everything else is single inheritance.
3174 llvm::Constant *BaseTypeInfo =
3175 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3176 Fields.push_back(BaseTypeInfo);
3177}
3178
3179/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3180/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3181void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3182 // Itanium C++ ABI 2.9.5p6b:
3183 // It adds to abi::__class_type_info a single member pointing to the
3184 // type_info structure for the base type,
3185 llvm::Constant *BaseTypeInfo =
3186 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3187 Fields.push_back(BaseTypeInfo);
3188}
3189
3190namespace {
3191 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3192 /// a class hierarchy.
3193 struct SeenBases {
3194 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3195 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3196 };
3197}
3198
3199/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3200/// abi::__vmi_class_type_info.
3201///
3202static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3203 SeenBases &Bases) {
3204
3205 unsigned Flags = 0;
3206
3207 const CXXRecordDecl *BaseDecl =
3208 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3209
3210 if (Base->isVirtual()) {
3211 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003212 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003213 // If this virtual base has been seen before, then the class is diamond
3214 // shaped.
3215 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3216 } else {
3217 if (Bases.NonVirtualBases.count(BaseDecl))
3218 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3219 }
3220 } else {
3221 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003222 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003223 // If this non-virtual base has been seen before, then the class has non-
3224 // diamond shaped repeated inheritance.
3225 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3226 } else {
3227 if (Bases.VirtualBases.count(BaseDecl))
3228 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3229 }
3230 }
3231
3232 // Walk all bases.
3233 for (const auto &I : BaseDecl->bases())
3234 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3235
3236 return Flags;
3237}
3238
3239static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3240 unsigned Flags = 0;
3241 SeenBases Bases;
3242
3243 // Walk all bases.
3244 for (const auto &I : RD->bases())
3245 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3246
3247 return Flags;
3248}
3249
3250/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3251/// classes with bases that do not satisfy the abi::__si_class_type_info
3252/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3253void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3254 llvm::Type *UnsignedIntLTy =
3255 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3256
3257 // Itanium C++ ABI 2.9.5p6c:
3258 // __flags is a word with flags describing details about the class
3259 // structure, which may be referenced by using the __flags_masks
3260 // enumeration. These flags refer to both direct and indirect bases.
3261 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3262 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3263
3264 // Itanium C++ ABI 2.9.5p6c:
3265 // __base_count is a word with the number of direct proper base class
3266 // descriptions that follow.
3267 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3268
3269 if (!RD->getNumBases())
3270 return;
3271
David Majnemere2cb8d12014-07-07 06:20:47 +00003272 // Now add the base class descriptions.
3273
3274 // Itanium C++ ABI 2.9.5p6c:
3275 // __base_info[] is an array of base class descriptions -- one for every
3276 // direct proper base. Each description is of the type:
3277 //
3278 // struct abi::__base_class_type_info {
3279 // public:
3280 // const __class_type_info *__base_type;
3281 // long __offset_flags;
3282 //
3283 // enum __offset_flags_masks {
3284 // __virtual_mask = 0x1,
3285 // __public_mask = 0x2,
3286 // __offset_shift = 8
3287 // };
3288 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003289
3290 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3291 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3292 // LLP64 platforms.
3293 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3294 // LLP64 platforms.
3295 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3296 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3297 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3298 OffsetFlagsTy = CGM.getContext().LongLongTy;
3299 llvm::Type *OffsetFlagsLTy =
3300 CGM.getTypes().ConvertType(OffsetFlagsTy);
3301
David Majnemere2cb8d12014-07-07 06:20:47 +00003302 for (const auto &Base : RD->bases()) {
3303 // The __base_type member points to the RTTI for the base type.
3304 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3305
3306 const CXXRecordDecl *BaseDecl =
3307 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3308
3309 int64_t OffsetFlags = 0;
3310
3311 // All but the lower 8 bits of __offset_flags are a signed offset.
3312 // For a non-virtual base, this is the offset in the object of the base
3313 // subobject. For a virtual base, this is the offset in the virtual table of
3314 // the virtual base offset for the virtual base referenced (negative).
3315 CharUnits Offset;
3316 if (Base.isVirtual())
3317 Offset =
3318 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3319 else {
3320 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3321 Offset = Layout.getBaseClassOffset(BaseDecl);
3322 };
3323
3324 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3325
3326 // The low-order byte of __offset_flags contains flags, as given by the
3327 // masks from the enumeration __offset_flags_masks.
3328 if (Base.isVirtual())
3329 OffsetFlags |= BCTI_Virtual;
3330 if (Base.getAccessSpecifier() == AS_public)
3331 OffsetFlags |= BCTI_Public;
3332
Reid Klecknerd8b04662016-08-25 22:16:30 +00003333 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003334 }
3335}
3336
Richard Smitha7d93782016-12-01 03:32:42 +00003337/// Compute the flags for a __pbase_type_info, and remove the corresponding
3338/// pieces from \p Type.
3339static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3340 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003341
Richard Smitha7d93782016-12-01 03:32:42 +00003342 if (Type.isConstQualified())
3343 Flags |= ItaniumRTTIBuilder::PTI_Const;
3344 if (Type.isVolatileQualified())
3345 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3346 if (Type.isRestrictQualified())
3347 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3348 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003349
3350 // Itanium C++ ABI 2.9.5p7:
3351 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3352 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003353 if (ContainsIncompleteClassType(Type))
3354 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3355
3356 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3357 if (Proto->isNothrow(Ctx)) {
3358 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
3359 Type = Ctx.getFunctionType(
3360 Proto->getReturnType(), Proto->getParamTypes(),
3361 Proto->getExtProtoInfo().withExceptionSpec(EST_None));
3362 }
3363 }
3364
3365 return Flags;
3366}
3367
3368/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3369/// used for pointer types.
3370void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3371 // Itanium C++ ABI 2.9.5p7:
3372 // __flags is a flag word describing the cv-qualification and other
3373 // attributes of the type pointed to
3374 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003375
3376 llvm::Type *UnsignedIntLTy =
3377 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3378 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3379
3380 // Itanium C++ ABI 2.9.5p7:
3381 // __pointee is a pointer to the std::type_info derivation for the
3382 // unqualified type being pointed to.
3383 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003384 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003385 Fields.push_back(PointeeTypeInfo);
3386}
3387
3388/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3389/// struct, used for member pointer types.
3390void
3391ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3392 QualType PointeeTy = Ty->getPointeeType();
3393
David Majnemere2cb8d12014-07-07 06:20:47 +00003394 // Itanium C++ ABI 2.9.5p7:
3395 // __flags is a flag word describing the cv-qualification and other
3396 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003397 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003398
3399 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003400 if (IsIncompleteClassType(ClassType))
3401 Flags |= PTI_ContainingClassIncomplete;
3402
3403 llvm::Type *UnsignedIntLTy =
3404 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3405 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3406
3407 // Itanium C++ ABI 2.9.5p7:
3408 // __pointee is a pointer to the std::type_info derivation for the
3409 // unqualified type being pointed to.
3410 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003411 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003412 Fields.push_back(PointeeTypeInfo);
3413
3414 // Itanium C++ ABI 2.9.5p9:
3415 // __context is a pointer to an abi::__class_type_info corresponding to the
3416 // class type containing the member pointed to
3417 // (e.g., the "A" in "int A::*").
3418 Fields.push_back(
3419 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3420}
3421
David Majnemer443250f2015-03-17 20:35:00 +00003422llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003423 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3424}
3425
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003426void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3427 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003428 QualType PointerType = getContext().getPointerType(Type);
3429 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003430 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3431 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3432 DLLExport);
3433 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3434 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003435}
3436
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003437void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003438 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003439 QualType FundamentalTypes[] = {
3440 getContext().VoidTy, getContext().NullPtrTy,
3441 getContext().BoolTy, getContext().WCharTy,
3442 getContext().CharTy, getContext().UnsignedCharTy,
3443 getContext().SignedCharTy, getContext().ShortTy,
3444 getContext().UnsignedShortTy, getContext().IntTy,
3445 getContext().UnsignedIntTy, getContext().LongTy,
3446 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003447 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3448 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003449 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003450 getContext().LongDoubleTy, getContext().Float128Ty,
3451 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003452 };
3453 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003454 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003455}
3456
3457/// What sort of uniqueness rules should we use for the RTTI for the
3458/// given type?
3459ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3460 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3461 if (shouldRTTIBeUnique())
3462 return RUK_Unique;
3463
3464 // It's only necessary for linkonce_odr or weak_odr linkage.
3465 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3466 Linkage != llvm::GlobalValue::WeakODRLinkage)
3467 return RUK_Unique;
3468
3469 // It's only necessary with default visibility.
3470 if (CanTy->getVisibility() != DefaultVisibility)
3471 return RUK_Unique;
3472
3473 // If we're not required to publish this symbol, hide it.
3474 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3475 return RUK_NonUniqueHidden;
3476
3477 // If we're required to publish this symbol, as we might be under an
3478 // explicit instantiation, leave it with default visibility but
3479 // enable string-comparisons.
3480 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3481 return RUK_NonUniqueVisible;
3482}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003483
Rafael Espindola1e4df922014-09-16 15:18:21 +00003484// Find out how to codegen the complete destructor and constructor
3485namespace {
3486enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3487}
3488static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3489 const CXXMethodDecl *MD) {
3490 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3491 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003492
Rafael Espindola1e4df922014-09-16 15:18:21 +00003493 // The complete and base structors are not equivalent if there are any virtual
3494 // bases, so emit separate functions.
3495 if (MD->getParent()->getNumVBases())
3496 return StructorCodegen::Emit;
3497
3498 GlobalDecl AliasDecl;
3499 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3500 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3501 } else {
3502 const auto *CD = cast<CXXConstructorDecl>(MD);
3503 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3504 }
3505 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3506
3507 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3508 return StructorCodegen::RAUW;
3509
3510 // FIXME: Should we allow available_externally aliases?
3511 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3512 return StructorCodegen::RAUW;
3513
Rafael Espindola0806f982014-09-16 20:19:43 +00003514 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3515 // Only ELF supports COMDATs with arbitrary names (C5/D5).
3516 if (CGM.getTarget().getTriple().isOSBinFormatELF())
3517 return StructorCodegen::COMDAT;
3518 return StructorCodegen::Emit;
3519 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003520
3521 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003522}
3523
Rafael Espindola1e4df922014-09-16 15:18:21 +00003524static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3525 GlobalDecl AliasDecl,
3526 GlobalDecl TargetDecl) {
3527 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3528
3529 StringRef MangledName = CGM.getMangledName(AliasDecl);
3530 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3531 if (Entry && !Entry->isDeclaration())
3532 return;
3533
3534 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003535
3536 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003537 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003538
3539 // Switch any previous uses to the alias.
3540 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003541 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003542 "declaration exists with different type");
3543 Alias->takeName(Entry);
3544 Entry->replaceAllUsesWith(Alias);
3545 Entry->eraseFromParent();
3546 } else {
3547 Alias->setName(MangledName);
3548 }
3549
3550 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003551 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003552}
3553
3554void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3555 StructorType Type) {
3556 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3557 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3558
3559 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3560
3561 if (Type == StructorType::Complete) {
3562 GlobalDecl CompleteDecl;
3563 GlobalDecl BaseDecl;
3564 if (CD) {
3565 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3566 BaseDecl = GlobalDecl(CD, Ctor_Base);
3567 } else {
3568 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3569 BaseDecl = GlobalDecl(DD, Dtor_Base);
3570 }
3571
3572 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3573 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3574 return;
3575 }
3576
3577 if (CGType == StructorCodegen::RAUW) {
3578 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003579 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003580 CGM.addReplacement(MangledName, Aliasee);
3581 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003582 }
3583 }
3584
3585 // The base destructor is equivalent to the base destructor of its
3586 // base class if there is exactly one non-virtual base class with a
3587 // non-trivial destructor, there are no fields with a non-trivial
3588 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003589 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3590 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003591 return;
3592
Rafael Espindola1e4df922014-09-16 15:18:21 +00003593 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003594
Rafael Espindola1e4df922014-09-16 15:18:21 +00003595 if (CGType == StructorCodegen::COMDAT) {
3596 SmallString<256> Buffer;
3597 llvm::raw_svector_ostream Out(Buffer);
3598 if (DD)
3599 getMangleContext().mangleCXXDtorComdat(DD, Out);
3600 else
3601 getMangleContext().mangleCXXCtorComdat(CD, Out);
3602 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3603 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003604 } else {
3605 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003606 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003607}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003608
3609static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3610 // void *__cxa_begin_catch(void*);
3611 llvm::FunctionType *FTy = llvm::FunctionType::get(
3612 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3613
3614 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3615}
3616
3617static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3618 // void __cxa_end_catch();
3619 llvm::FunctionType *FTy =
3620 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3621
3622 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3623}
3624
3625static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3626 // void *__cxa_get_exception_ptr(void*);
3627 llvm::FunctionType *FTy = llvm::FunctionType::get(
3628 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3629
3630 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3631}
3632
3633namespace {
3634 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3635 /// exception type lets us state definitively that the thrown exception
3636 /// type does not have a destructor. In particular:
3637 /// - Catch-alls tell us nothing, so we have to conservatively
3638 /// assume that the thrown exception might have a destructor.
3639 /// - Catches by reference behave according to their base types.
3640 /// - Catches of non-record types will only trigger for exceptions
3641 /// of non-record types, which never have destructors.
3642 /// - Catches of record types can trigger for arbitrary subclasses
3643 /// of the caught type, so we have to assume the actual thrown
3644 /// exception type might have a throwing destructor, even if the
3645 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003646 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003647 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3648 bool MightThrow;
3649
3650 void Emit(CodeGenFunction &CGF, Flags flags) override {
3651 if (!MightThrow) {
3652 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3653 return;
3654 }
3655
3656 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3657 }
3658 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003659}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003660
3661/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3662/// __cxa_end_catch.
3663///
3664/// \param EndMightThrow - true if __cxa_end_catch might throw
3665static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3666 llvm::Value *Exn,
3667 bool EndMightThrow) {
3668 llvm::CallInst *call =
3669 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3670
3671 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3672
3673 return call;
3674}
3675
3676/// A "special initializer" callback for initializing a catch
3677/// parameter during catch initialization.
3678static void InitCatchParam(CodeGenFunction &CGF,
3679 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003680 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003681 SourceLocation Loc) {
3682 // Load the exception from where the landing pad saved it.
3683 llvm::Value *Exn = CGF.getExceptionFromSlot();
3684
3685 CanQualType CatchType =
3686 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3687 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3688
3689 // If we're catching by reference, we can just cast the object
3690 // pointer to the appropriate pointer.
3691 if (isa<ReferenceType>(CatchType)) {
3692 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3693 bool EndCatchMightThrow = CaughtType->isRecordType();
3694
3695 // __cxa_begin_catch returns the adjusted object pointer.
3696 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3697
3698 // We have no way to tell the personality function that we're
3699 // catching by reference, so if we're catching a pointer,
3700 // __cxa_begin_catch will actually return that pointer by value.
3701 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3702 QualType PointeeType = PT->getPointeeType();
3703
3704 // When catching by reference, generally we should just ignore
3705 // this by-value pointer and use the exception object instead.
3706 if (!PointeeType->isRecordType()) {
3707
3708 // Exn points to the struct _Unwind_Exception header, which
3709 // we have to skip past in order to reach the exception data.
3710 unsigned HeaderSize =
3711 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3712 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3713
3714 // However, if we're catching a pointer-to-record type that won't
3715 // work, because the personality function might have adjusted
3716 // the pointer. There's actually no way for us to fully satisfy
3717 // the language/ABI contract here: we can't use Exn because it
3718 // might have the wrong adjustment, but we can't use the by-value
3719 // pointer because it's off by a level of abstraction.
3720 //
3721 // The current solution is to dump the adjusted pointer into an
3722 // alloca, which breaks language semantics (because changing the
3723 // pointer doesn't change the exception) but at least works.
3724 // The better solution would be to filter out non-exact matches
3725 // and rethrow them, but this is tricky because the rethrow
3726 // really needs to be catchable by other sites at this landing
3727 // pad. The best solution is to fix the personality function.
3728 } else {
3729 // Pull the pointer for the reference type off.
3730 llvm::Type *PtrTy =
3731 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3732
3733 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003734 Address ExnPtrTmp =
3735 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003736 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3737 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3738
3739 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003740 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003741 }
3742 }
3743
3744 llvm::Value *ExnCast =
3745 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3746 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3747 return;
3748 }
3749
3750 // Scalars and complexes.
3751 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3752 if (TEK != TEK_Aggregate) {
3753 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3754
3755 // If the catch type is a pointer type, __cxa_begin_catch returns
3756 // the pointer by value.
3757 if (CatchType->hasPointerRepresentation()) {
3758 llvm::Value *CastExn =
3759 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3760
3761 switch (CatchType.getQualifiers().getObjCLifetime()) {
3762 case Qualifiers::OCL_Strong:
3763 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3764 // fallthrough
3765
3766 case Qualifiers::OCL_None:
3767 case Qualifiers::OCL_ExplicitNone:
3768 case Qualifiers::OCL_Autoreleasing:
3769 CGF.Builder.CreateStore(CastExn, ParamAddr);
3770 return;
3771
3772 case Qualifiers::OCL_Weak:
3773 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3774 return;
3775 }
3776 llvm_unreachable("bad ownership qualifier!");
3777 }
3778
3779 // Otherwise, it returns a pointer into the exception object.
3780
3781 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3782 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3783
3784 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003785 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003786 switch (TEK) {
3787 case TEK_Complex:
3788 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3789 /*init*/ true);
3790 return;
3791 case TEK_Scalar: {
3792 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3793 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3794 return;
3795 }
3796 case TEK_Aggregate:
3797 llvm_unreachable("evaluation kind filtered out!");
3798 }
3799 llvm_unreachable("bad evaluation kind");
3800 }
3801
3802 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003803 auto catchRD = CatchType->getAsCXXRecordDecl();
3804 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003805
3806 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3807
3808 // Check for a copy expression. If we don't have a copy expression,
3809 // that means a trivial copy is okay.
3810 const Expr *copyExpr = CatchParam.getInit();
3811 if (!copyExpr) {
3812 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003813 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3814 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003815 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3816 return;
3817 }
3818
3819 // We have to call __cxa_get_exception_ptr to get the adjusted
3820 // pointer before copying.
3821 llvm::CallInst *rawAdjustedExn =
3822 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3823
3824 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003825 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3826 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003827
3828 // The copy expression is defined in terms of an OpaqueValueExpr.
3829 // Find it and map it to the adjusted expression.
3830 CodeGenFunction::OpaqueValueMapping
3831 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3832 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3833
3834 // Call the copy ctor in a terminate scope.
3835 CGF.EHStack.pushTerminate();
3836
3837 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003838 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003839 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003840 AggValueSlot::IsNotDestructed,
3841 AggValueSlot::DoesNotNeedGCBarriers,
3842 AggValueSlot::IsNotAliased));
3843
3844 // Leave the terminate scope.
3845 CGF.EHStack.popTerminate();
3846
3847 // Undo the opaque value mapping.
3848 opaque.pop();
3849
3850 // Finally we can call __cxa_begin_catch.
3851 CallBeginCatch(CGF, Exn, true);
3852}
3853
3854/// Begins a catch statement by initializing the catch variable and
3855/// calling __cxa_begin_catch.
3856void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3857 const CXXCatchStmt *S) {
3858 // We have to be very careful with the ordering of cleanups here:
3859 // C++ [except.throw]p4:
3860 // The destruction [of the exception temporary] occurs
3861 // immediately after the destruction of the object declared in
3862 // the exception-declaration in the handler.
3863 //
3864 // So the precise ordering is:
3865 // 1. Construct catch variable.
3866 // 2. __cxa_begin_catch
3867 // 3. Enter __cxa_end_catch cleanup
3868 // 4. Enter dtor cleanup
3869 //
3870 // We do this by using a slightly abnormal initialization process.
3871 // Delegation sequence:
3872 // - ExitCXXTryStmt opens a RunCleanupsScope
3873 // - EmitAutoVarAlloca creates the variable and debug info
3874 // - InitCatchParam initializes the variable from the exception
3875 // - CallBeginCatch calls __cxa_begin_catch
3876 // - CallBeginCatch enters the __cxa_end_catch cleanup
3877 // - EmitAutoVarCleanups enters the variable destructor cleanup
3878 // - EmitCXXTryStmt emits the code for the catch body
3879 // - EmitCXXTryStmt close the RunCleanupsScope
3880
3881 VarDecl *CatchParam = S->getExceptionDecl();
3882 if (!CatchParam) {
3883 llvm::Value *Exn = CGF.getExceptionFromSlot();
3884 CallBeginCatch(CGF, Exn, true);
3885 return;
3886 }
3887
3888 // Emit the local.
3889 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3890 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3891 CGF.EmitAutoVarCleanups(var);
3892}
3893
3894/// Get or define the following function:
3895/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3896/// This code is used only in C++.
3897static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3898 llvm::FunctionType *fnTy =
3899 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3900 llvm::Constant *fnRef =
3901 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3902
3903 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3904 if (fn && fn->empty()) {
3905 fn->setDoesNotThrow();
3906 fn->setDoesNotReturn();
3907
3908 // What we really want is to massively penalize inlining without
3909 // forbidding it completely. The difference between that and
3910 // 'noinline' is negligible.
3911 fn->addFnAttr(llvm::Attribute::NoInline);
3912
3913 // Allow this function to be shared across translation units, but
3914 // we don't want it to turn into an exported symbol.
3915 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3916 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003917 if (CGM.supportsCOMDAT())
3918 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003919
3920 // Set up the function.
3921 llvm::BasicBlock *entry =
3922 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003923 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003924
3925 // Pull the exception pointer out of the parameter list.
3926 llvm::Value *exn = &*fn->arg_begin();
3927
3928 // Call __cxa_begin_catch(exn).
3929 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3930 catchCall->setDoesNotThrow();
3931 catchCall->setCallingConv(CGM.getRuntimeCC());
3932
3933 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003934 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003935 termCall->setDoesNotThrow();
3936 termCall->setDoesNotReturn();
3937 termCall->setCallingConv(CGM.getRuntimeCC());
3938
3939 // std::terminate cannot return.
3940 builder.CreateUnreachable();
3941 }
3942
3943 return fnRef;
3944}
3945
3946llvm::CallInst *
3947ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3948 llvm::Value *Exn) {
3949 // In C++, we want to call __cxa_begin_catch() before terminating.
3950 if (Exn) {
3951 assert(CGF.CGM.getLangOpts().CPlusPlus);
3952 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3953 }
3954 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3955}