blob: de9fd042a9e4501574527f29dc5327a1a21547eb [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000022#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000023#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000024#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000025#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000026#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000027#include "TargetInfo.h"
John McCall5ad74072017-03-02 20:04:19 +000028#include "clang/CodeGen/ConstantInitBuilder.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
George Burgess IVf203dbf2017-02-22 20:28:02 +0000210 AddedStructorArgs
211 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
212 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000213
Reid Klecknere7de47e2013-07-22 13:51:44 +0000214 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000215 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000216 // Itanium does not emit any destructor variant as an inline thunk.
217 // Delegating may occur as an optimization, but all variants are either
218 // emitted with external linkage or as linkonce if they are inline and used.
219 return false;
220 }
221
Craig Topper4f12f102014-03-12 06:41:41 +0000222 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000223
Reid Kleckner89077a12013-12-17 19:46:40 +0000224 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000225 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000226
Craig Topper4f12f102014-03-12 06:41:41 +0000227 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000228
George Burgess IVf203dbf2017-02-22 20:28:02 +0000229 AddedStructorArgs
230 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
231 CXXCtorType Type, bool ForVirtualBase,
232 bool Delegating, 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);
Shoaib Meenaicef66e52017-07-24 17:16:27 +0000287
288 // Propagate dllexport storage, to enable the linker to generate import
289 // thunks as necessary (e.g. when a parent class has a key function and a
290 // child class doesn't, and the construction vtable for the parent in the
291 // child needs to reference the parent's thunks).
292 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
293 if (MD->hasAttr<DLLExportAttr>())
294 Thunk->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000295 }
296
John McCall7f416cc2015-09-08 08:05:57 +0000297 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000298 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000299
John McCall7f416cc2015-09-08 08:05:57 +0000300 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000301 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000302
David Majnemer196ac332014-09-11 23:05:02 +0000303 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
304 FunctionArgList &Args) const override {
305 assert(!Args.empty() && "expected the arglist to not be empty!");
306 return Args.size() - 1;
307 }
308
Craig Topper4f12f102014-03-12 06:41:41 +0000309 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
310 StringRef GetDeletedVirtualCallName() override
311 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000312
Craig Topper4f12f102014-03-12 06:41:41 +0000313 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000314 Address InitializeArrayCookie(CodeGenFunction &CGF,
315 Address NewPtr,
316 llvm::Value *NumElements,
317 const CXXNewExpr *expr,
318 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000319 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000320 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000321 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000322
John McCallcdf7ef52010-11-06 09:44:32 +0000323 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000324 llvm::GlobalVariable *DeclPtr,
325 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000326 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000327 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000328
329 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000330 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000331 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000332 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000333 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000334 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000335 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000336
337 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000338 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
339 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000340
Craig Topper4f12f102014-03-12 06:41:41 +0000341 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000342
343 /**************************** RTTI Uniqueness ******************************/
344
345protected:
346 /// Returns true if the ABI requires RTTI type_info objects to be unique
347 /// across a program.
348 virtual bool shouldRTTIBeUnique() const { return true; }
349
350public:
351 /// What sort of unique-RTTI behavior should we use?
352 enum RTTIUniquenessKind {
353 /// We are guaranteeing, or need to guarantee, that the RTTI string
354 /// is unique.
355 RUK_Unique,
356
357 /// We are not guaranteeing uniqueness for the RTTI string, so we
358 /// can demote to hidden visibility but must use string comparisons.
359 RUK_NonUniqueHidden,
360
361 /// We are not guaranteeing uniqueness for the RTTI string, so we
362 /// have to use string comparisons, but we also have to emit it with
363 /// non-hidden visibility.
364 RUK_NonUniqueVisible
365 };
366
367 /// Return the required visibility status for the given type and linkage in
368 /// the current ABI.
369 RTTIUniquenessKind
370 classifyRTTIUniqueness(QualType CanTy,
371 llvm::GlobalValue::LinkageTypes Linkage) const;
372 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000373
374 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000375
376 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000377 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
378 const auto &VtableLayout =
379 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000380
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000381 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
382 // Skip empty slot.
383 if (!VtableComponent.isUsedFunctionPointerKind())
384 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000385
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000386 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
387 if (!Method->getCanonicalDecl()->isInlined())
388 continue;
389
390 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
391 auto *Entry = CGM.GetGlobalValue(Name);
392 // This checks if virtual inline function has already been emitted.
393 // Note that it is possible that this inline function would be emitted
394 // after trying to emit vtable speculatively. Because of this we do
395 // an extra pass after emitting all deferred vtables to find and emit
396 // these vtables opportunistically.
397 if (!Entry || Entry->isDeclaration())
398 return true;
399 }
400 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000401 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000402
403 bool isVTableHidden(const CXXRecordDecl *RD) const {
404 const auto &VtableLayout =
405 CGM.getItaniumVTableContext().getVTableLayout(RD);
406
407 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
408 if (VtableComponent.isRTTIKind()) {
409 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
410 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
411 return true;
412 } else if (VtableComponent.isUsedFunctionPointerKind()) {
413 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
414 if (Method->getVisibility() == Visibility::HiddenVisibility &&
415 !Method->isDefined())
416 return true;
417 }
418 }
419 return false;
420 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000421};
John McCall86353412010-08-21 22:46:04 +0000422
423class ARMCXXABI : public ItaniumCXXABI {
424public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000425 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
426 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
427 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000428
Craig Topper4f12f102014-03-12 06:41:41 +0000429 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000430 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
431 isa<CXXDestructorDecl>(GD.getDecl()) &&
432 GD.getDtorType() != Dtor_Deleting));
433 }
John McCall5d865c322010-08-31 07:33:07 +0000434
Craig Topper4f12f102014-03-12 06:41:41 +0000435 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
436 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000437
Craig Topper4f12f102014-03-12 06:41:41 +0000438 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000439 Address InitializeArrayCookie(CodeGenFunction &CGF,
440 Address NewPtr,
441 llvm::Value *NumElements,
442 const CXXNewExpr *expr,
443 QualType ElementType) override;
444 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000445 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000446};
Tim Northovera2ee4332014-03-29 15:09:45 +0000447
448class iOS64CXXABI : public ARMCXXABI {
449public:
John McCalld23b27e2016-09-16 02:40:45 +0000450 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
451 Use32BitVTableOffsetABI = true;
452 }
Tim Northover65f582f2014-03-30 17:32:48 +0000453
454 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000455 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000456};
Dan Gohmanc2853072015-09-03 22:51:53 +0000457
458class WebAssemblyCXXABI final : public ItaniumCXXABI {
459public:
460 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
461 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
462 /*UseARMGuardVarABI=*/true) {}
463
464private:
465 bool HasThisReturn(GlobalDecl GD) const override {
466 return isa<CXXConstructorDecl>(GD.getDecl()) ||
467 (isa<CXXDestructorDecl>(GD.getDecl()) &&
468 GD.getDtorType() != Dtor_Deleting);
469 }
Derek Schuff8179be42016-05-10 17:44:55 +0000470 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000471};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000472}
Charles Davis4e786dd2010-05-25 19:52:27 +0000473
Charles Davis53c59df2010-08-16 03:33:14 +0000474CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000475 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000476 // For IR-generation purposes, there's no significant difference
477 // between the ARM and iOS ABIs.
478 case TargetCXXABI::GenericARM:
479 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000480 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000481 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000482
Tim Northovera2ee4332014-03-29 15:09:45 +0000483 case TargetCXXABI::iOS64:
484 return new iOS64CXXABI(CGM);
485
Tim Northover9bb857a2013-01-31 12:13:10 +0000486 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
487 // include the other 32-bit ARM oddities: constructor/destructor return values
488 // and array cookies.
489 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000490 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
491 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000492
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000493 case TargetCXXABI::GenericMIPS:
494 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
495
Dan Gohmanc2853072015-09-03 22:51:53 +0000496 case TargetCXXABI::WebAssembly:
497 return new WebAssemblyCXXABI(CGM);
498
John McCall57625922013-01-25 23:36:14 +0000499 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000500 if (CGM.getContext().getTargetInfo().getTriple().getArch()
501 == llvm::Triple::le32) {
502 // For PNaCl, use ARM-style method pointers so that PNaCl code
503 // does not assume anything about the alignment of function
504 // pointers.
505 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
506 /* UseARMGuardVarABI = */ false);
507 }
John McCall57625922013-01-25 23:36:14 +0000508 return new ItaniumCXXABI(CGM);
509
510 case TargetCXXABI::Microsoft:
511 llvm_unreachable("Microsoft ABI is not Itanium-based");
512 }
513 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000514}
515
Chris Lattnera5f58b02011-07-09 17:41:47 +0000516llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000517ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
518 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000519 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000520 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000521}
522
John McCalld9c6c0b2010-08-22 00:59:17 +0000523/// In the Itanium and ARM ABIs, method pointers have the form:
524/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
525///
526/// In the Itanium ABI:
527/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
528/// - the this-adjustment is (memptr.adj)
529/// - the virtual offset is (memptr.ptr - 1)
530///
531/// In the ARM ABI:
532/// - method pointers are virtual if (memptr.adj & 1) is nonzero
533/// - the this-adjustment is (memptr.adj >> 1)
534/// - the virtual offset is (memptr.ptr)
535/// ARM uses 'adj' for the virtual flag because Thumb functions
536/// may be only single-byte aligned.
537///
538/// If the member is virtual, the adjusted 'this' pointer points
539/// to a vtable pointer from which the virtual offset is applied.
540///
541/// If the member is non-virtual, memptr.ptr is the address of
542/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000543CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000544 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
545 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000546 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000547 CGBuilderTy &Builder = CGF.Builder;
548
549 const FunctionProtoType *FPT =
550 MPT->getPointeeType()->getAs<FunctionProtoType>();
551 const CXXRecordDecl *RD =
552 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
553
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000554 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
555 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000556
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000557 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000558
John McCalld9c6c0b2010-08-22 00:59:17 +0000559 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
560 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
561 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
562
John McCalla1dee5302010-08-22 10:59:02 +0000563 // Extract memptr.adj, which is in the second field.
564 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000565
566 // Compute the true adjustment.
567 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000568 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000569 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000570
571 // Apply the adjustment and cast back to the original struct type
572 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000573 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000574 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
575 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
576 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000577 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000578
579 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000580 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000581
582 // If the LSB in the function pointer is 1, the function pointer points to
583 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000584 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000585 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000586 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
587 else
588 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
589 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000590 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
591
592 // In the virtual path, the adjustment left 'This' pointing to the
593 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000594 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000595 CGF.EmitBlock(FnVirtual);
596
597 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000598 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000599 CharUnits VTablePtrAlign =
600 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
601 CGF.getPointerAlign());
602 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000603 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000604
605 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000606 // On ARM64, to reserve extra space in virtual member function pointers,
607 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000608 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000609 if (!UseARMMethodPtrABI)
610 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000611 if (Use32BitVTableOffsetABI) {
612 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
613 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
614 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000615 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000616
617 // Load the virtual function to call.
618 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000619 llvm::Value *VirtualFn =
620 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
621 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000622 CGF.EmitBranch(FnEnd);
623
624 // In the non-virtual path, the function pointer is actually a
625 // function pointer.
626 CGF.EmitBlock(FnNonVirtual);
627 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000628 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000629
630 // We're done.
631 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000632 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
633 CalleePtr->addIncoming(VirtualFn, FnVirtual);
634 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
635
636 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000637 return Callee;
638}
John McCalla8bbb822010-08-22 03:04:22 +0000639
John McCallc134eb52010-08-31 21:07:20 +0000640/// Compute an l-value by applying the given pointer-to-member to a
641/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000642llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000643 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000644 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000645 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000646
647 CGBuilderTy &Builder = CGF.Builder;
648
John McCallc134eb52010-08-31 21:07:20 +0000649 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000650 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000651
652 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000653 llvm::Value *Addr =
654 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000655
656 // Cast the address to the appropriate pointer type, adopting the
657 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000658 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
659 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000660 return Builder.CreateBitCast(Addr, PType);
661}
662
John McCallc62bb392012-02-15 01:22:51 +0000663/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
664/// conversion.
665///
666/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000667///
668/// Obligatory offset/adjustment diagram:
669/// <-- offset --> <-- adjustment -->
670/// |--------------------------|----------------------|--------------------|
671/// ^Derived address point ^Base address point ^Member address point
672///
673/// So when converting a base member pointer to a derived member pointer,
674/// we add the offset to the adjustment because the address point has
675/// decreased; and conversely, when converting a derived MP to a base MP
676/// we subtract the offset from the adjustment because the address point
677/// has increased.
678///
679/// The standard forbids (at compile time) conversion to and from
680/// virtual bases, which is why we don't have to consider them here.
681///
682/// The standard forbids (at run time) casting a derived MP to a base
683/// MP when the derived MP does not point to a member of the base.
684/// This is why -1 is a reasonable choice for null data member
685/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000686llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000687ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
688 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000689 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000690 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000691 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
692 E->getCastKind() == CK_ReinterpretMemberPointer);
693
694 // Under Itanium, reinterprets don't require any additional processing.
695 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
696
697 // Use constant emission if we can.
698 if (isa<llvm::Constant>(src))
699 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
700
701 llvm::Constant *adj = getMemberPointerAdjustment(E);
702 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000703
704 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000705 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000706
John McCallc62bb392012-02-15 01:22:51 +0000707 const MemberPointerType *destTy =
708 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000709
John McCall7a9aac22010-08-23 01:21:21 +0000710 // For member data pointers, this is just a matter of adding the
711 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000712 if (destTy->isMemberDataPointer()) {
713 llvm::Value *dst;
714 if (isDerivedToBase)
715 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000716 else
John McCallc62bb392012-02-15 01:22:51 +0000717 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000718
719 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000720 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
721 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
722 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000723 }
724
John McCalla1dee5302010-08-22 10:59:02 +0000725 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000726 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000727 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
728 offset <<= 1;
729 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000730 }
731
John McCallc62bb392012-02-15 01:22:51 +0000732 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
733 llvm::Value *dstAdj;
734 if (isDerivedToBase)
735 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000736 else
John McCallc62bb392012-02-15 01:22:51 +0000737 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000738
John McCallc62bb392012-02-15 01:22:51 +0000739 return Builder.CreateInsertValue(src, dstAdj, 1);
740}
741
742llvm::Constant *
743ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
744 llvm::Constant *src) {
745 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
746 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
747 E->getCastKind() == CK_ReinterpretMemberPointer);
748
749 // Under Itanium, reinterprets don't require any additional processing.
750 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
751
752 // If the adjustment is trivial, we don't need to do anything.
753 llvm::Constant *adj = getMemberPointerAdjustment(E);
754 if (!adj) return src;
755
756 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
757
758 const MemberPointerType *destTy =
759 E->getType()->castAs<MemberPointerType>();
760
761 // For member data pointers, this is just a matter of adding the
762 // offset if the source is non-null.
763 if (destTy->isMemberDataPointer()) {
764 // null maps to null.
765 if (src->isAllOnesValue()) return src;
766
767 if (isDerivedToBase)
768 return llvm::ConstantExpr::getNSWSub(src, adj);
769 else
770 return llvm::ConstantExpr::getNSWAdd(src, adj);
771 }
772
773 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000774 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000775 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
776 offset <<= 1;
777 adj = llvm::ConstantInt::get(adj->getType(), offset);
778 }
779
780 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
781 llvm::Constant *dstAdj;
782 if (isDerivedToBase)
783 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
784 else
785 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
786
787 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000788}
John McCall84fa5102010-08-22 04:16:24 +0000789
790llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000791ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000792 // Itanium C++ ABI 2.3:
793 // A NULL pointer is represented as -1.
794 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000795 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000796
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000797 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000798 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000799 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000800}
801
John McCallf3a88602011-02-03 08:15:49 +0000802llvm::Constant *
803ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
804 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000805 // Itanium C++ ABI 2.3:
806 // A pointer to data member is an offset from the base address of
807 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000808 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000809}
810
David Majnemere2be95b2015-06-23 07:31:01 +0000811llvm::Constant *
812ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000813 return BuildMemberPointer(MD, CharUnits::Zero());
814}
815
816llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
817 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000818 assert(MD->isInstance() && "Member function must not be static!");
819 MD = MD->getCanonicalDecl();
820
821 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000822
823 // Get the function pointer (or index if this is a virtual function).
824 llvm::Constant *MemPtr[2];
825 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000826 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000827
Ken Dyckdf016282011-04-09 01:30:02 +0000828 const ASTContext &Context = getContext();
829 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000830 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000831 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000832
Mark Seabornedf0d382013-07-24 16:25:13 +0000833 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000834 // ARM C++ ABI 3.2.1:
835 // This ABI specifies that adj contains twice the this
836 // adjustment, plus 1 if the member function is virtual. The
837 // least significant bit of adj then makes exactly the same
838 // discrimination as the least significant bit of ptr does for
839 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000840 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
841 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000842 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000843 } else {
844 // Itanium C++ ABI 2.3:
845 // For a virtual function, [the pointer field] is 1 plus the
846 // virtual table offset (in bytes) of the function,
847 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000848 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
849 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000850 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000851 }
852 } else {
John McCall2979fe02011-04-12 00:42:48 +0000853 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000854 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000855 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000856 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000857 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000858 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000859 } else {
John McCall2979fe02011-04-12 00:42:48 +0000860 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
861 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000862 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000863 }
John McCall2979fe02011-04-12 00:42:48 +0000864 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000865
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000866 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000867 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
868 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000869 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000870 }
John McCall1c456c82010-08-22 06:43:33 +0000871
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000872 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000873}
874
Richard Smithdafff942012-01-14 04:30:29 +0000875llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
876 QualType MPType) {
877 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
878 const ValueDecl *MPD = MP.getMemberPointerDecl();
879 if (!MPD)
880 return EmitNullMemberPointer(MPT);
881
Reid Kleckner452abac2013-05-09 21:01:17 +0000882 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000883
884 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
885 return BuildMemberPointer(MD, ThisAdjustment);
886
887 CharUnits FieldOffset =
888 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
889 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
890}
891
John McCall131d97d2010-08-22 08:30:07 +0000892/// The comparison algorithm is pretty easy: the member pointers are
893/// the same if they're either bitwise identical *or* both null.
894///
895/// ARM is different here only because null-ness is more complicated.
896llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000897ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
898 llvm::Value *L,
899 llvm::Value *R,
900 const MemberPointerType *MPT,
901 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000902 CGBuilderTy &Builder = CGF.Builder;
903
John McCall131d97d2010-08-22 08:30:07 +0000904 llvm::ICmpInst::Predicate Eq;
905 llvm::Instruction::BinaryOps And, Or;
906 if (Inequality) {
907 Eq = llvm::ICmpInst::ICMP_NE;
908 And = llvm::Instruction::Or;
909 Or = llvm::Instruction::And;
910 } else {
911 Eq = llvm::ICmpInst::ICMP_EQ;
912 And = llvm::Instruction::And;
913 Or = llvm::Instruction::Or;
914 }
915
John McCall7a9aac22010-08-23 01:21:21 +0000916 // Member data pointers are easy because there's a unique null
917 // value, so it just comes down to bitwise equality.
918 if (MPT->isMemberDataPointer())
919 return Builder.CreateICmp(Eq, L, R);
920
921 // For member function pointers, the tautologies are more complex.
922 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000923 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000924 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000925 // (L == R) <==> (L.ptr == R.ptr &&
926 // (L.adj == R.adj ||
927 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000928 // The inequality tautologies have exactly the same structure, except
929 // applying De Morgan's laws.
930
931 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
932 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
933
John McCall131d97d2010-08-22 08:30:07 +0000934 // This condition tests whether L.ptr == R.ptr. This must always be
935 // true for equality to hold.
936 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
937
938 // This condition, together with the assumption that L.ptr == R.ptr,
939 // tests whether the pointers are both null. ARM imposes an extra
940 // condition.
941 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
942 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
943
944 // This condition tests whether L.adj == R.adj. If this isn't
945 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000946 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
947 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000948 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
949
950 // Null member function pointers on ARM clear the low bit of Adj,
951 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000952 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000953 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
954
955 // Compute (l.adj | r.adj) & 1 and test it against zero.
956 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
957 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
958 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
959 "cmp.or.adj");
960 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
961 }
962
963 // Tie together all our conditions.
964 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
965 Result = Builder.CreateBinOp(And, PtrEq, Result,
966 Inequality ? "memptr.ne" : "memptr.eq");
967 return Result;
968}
969
970llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000971ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
972 llvm::Value *MemPtr,
973 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000974 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000975
976 /// For member data pointers, this is just a check against -1.
977 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000978 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000979 llvm::Value *NegativeOne =
980 llvm::Constant::getAllOnesValue(MemPtr->getType());
981 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
982 }
John McCall131d97d2010-08-22 08:30:07 +0000983
Daniel Dunbar914bc412011-04-19 23:10:47 +0000984 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000985 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000986
987 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
988 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
989
Daniel Dunbar914bc412011-04-19 23:10:47 +0000990 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
991 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000992 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000993 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +0000994 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000995 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +0000996 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
997 "memptr.isvirtual");
998 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +0000999 }
1000
1001 return Result;
1002}
John McCall1c456c82010-08-22 06:43:33 +00001003
Reid Kleckner40ca9132014-05-13 22:05:45 +00001004bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1005 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1006 if (!RD)
1007 return false;
1008
Reid Klecknerd355ca72014-05-15 01:26:32 +00001009 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
1010 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
1011 // special members.
1012 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +00001013 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1014 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001015 return true;
1016 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001017 return false;
1018}
1019
John McCall614dbdc2010-08-22 21:01:12 +00001020/// The Itanium ABI requires non-zero initialization only for data
1021/// member pointers, for which '0' is a valid offset.
1022bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001023 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001024}
John McCall5d865c322010-08-31 07:33:07 +00001025
John McCall82fb8922012-09-25 10:10:39 +00001026/// The Itanium ABI always places an offset to the complete object
1027/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001028void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1029 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001030 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001031 QualType ElementType,
1032 const CXXDestructorDecl *Dtor) {
1033 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001034 if (UseGlobalDelete) {
1035 // Derive the complete-object pointer, which is what we need
1036 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001037
David Majnemer0c0b6d92014-10-31 20:09:12 +00001038 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001039 auto *ClassDecl =
1040 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1041 llvm::Value *VTable =
1042 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001043
David Majnemer0c0b6d92014-10-31 20:09:12 +00001044 // Track back to entry -2 and pull out the offset there.
1045 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1046 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001047 llvm::Value *Offset =
1048 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001049
1050 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001051 llvm::Value *CompletePtr =
1052 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001053 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1054
1055 // If we're supposed to call the global delete, make sure we do so
1056 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001057 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1058 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001059 }
1060
1061 // FIXME: Provide a source location here even though there's no
1062 // CXXMemberCallExpr for dtor call.
1063 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1064 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1065
1066 if (UseGlobalDelete)
1067 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001068}
1069
David Majnemer442d0a22014-11-25 07:20:20 +00001070void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1071 // void __cxa_rethrow();
1072
1073 llvm::FunctionType *FTy =
1074 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1075
1076 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1077
1078 if (isNoReturn)
1079 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1080 else
1081 CGF.EmitRuntimeCallOrInvoke(Fn);
1082}
1083
David Majnemer7c237072015-03-05 00:46:22 +00001084static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1085 // void *__cxa_allocate_exception(size_t thrown_size);
1086
1087 llvm::FunctionType *FTy =
1088 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1089
1090 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1091}
1092
1093static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1094 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1095 // void (*dest) (void *));
1096
1097 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1098 llvm::FunctionType *FTy =
1099 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1100
1101 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1102}
1103
1104void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1105 QualType ThrowType = E->getSubExpr()->getType();
1106 // Now allocate the exception object.
1107 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1108 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1109
1110 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1111 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1112 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1113
John McCall7f416cc2015-09-08 08:05:57 +00001114 CharUnits ExnAlign = getAlignmentOfExnObject();
1115 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001116
1117 // Now throw the exception.
1118 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1119 /*ForEH=*/true);
1120
1121 // The address of the destructor. If the exception type has a
1122 // trivial destructor (or isn't a record), we just pass null.
1123 llvm::Constant *Dtor = nullptr;
1124 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1125 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1126 if (!Record->hasTrivialDestructor()) {
1127 CXXDestructorDecl *DtorD = Record->getDestructor();
1128 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1129 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1130 }
1131 }
1132 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1133
1134 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1135 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1136}
1137
David Majnemer1162d252014-06-22 19:05:33 +00001138static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1139 // void *__dynamic_cast(const void *sub,
1140 // const abi::__class_type_info *src,
1141 // const abi::__class_type_info *dst,
1142 // std::ptrdiff_t src2dst_offset);
1143
1144 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1145 llvm::Type *PtrDiffTy =
1146 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1147
1148 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1149
1150 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1151
1152 // Mark the function as nounwind readonly.
1153 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1154 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001155 llvm::AttributeList Attrs = llvm::AttributeList::get(
1156 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001157
1158 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1159}
1160
1161static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1162 // void __cxa_bad_cast();
1163 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1164 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1165}
1166
1167/// \brief Compute the src2dst_offset hint as described in the
1168/// Itanium C++ ABI [2.9.7]
1169static CharUnits computeOffsetHint(ASTContext &Context,
1170 const CXXRecordDecl *Src,
1171 const CXXRecordDecl *Dst) {
1172 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1173 /*DetectVirtual=*/false);
1174
1175 // If Dst is not derived from Src we can skip the whole computation below and
1176 // return that Src is not a public base of Dst. Record all inheritance paths.
1177 if (!Dst->isDerivedFrom(Src, Paths))
1178 return CharUnits::fromQuantity(-2ULL);
1179
1180 unsigned NumPublicPaths = 0;
1181 CharUnits Offset;
1182
1183 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001184 for (const CXXBasePath &Path : Paths) {
1185 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001186 continue;
1187
1188 ++NumPublicPaths;
1189
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001190 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001191 // If the path contains a virtual base class we can't give any hint.
1192 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001193 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001194 return CharUnits::fromQuantity(-1ULL);
1195
1196 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1197 continue;
1198
1199 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001200 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1201 Offset += L.getBaseClassOffset(
1202 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001203 }
1204 }
1205
1206 // -2: Src is not a public base of Dst.
1207 if (NumPublicPaths == 0)
1208 return CharUnits::fromQuantity(-2ULL);
1209
1210 // -3: Src is a multiple public base type but never a virtual base type.
1211 if (NumPublicPaths > 1)
1212 return CharUnits::fromQuantity(-3ULL);
1213
1214 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1215 // Return the offset of Src from the origin of Dst.
1216 return Offset;
1217}
1218
1219static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1220 // void __cxa_bad_typeid();
1221 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1222
1223 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1224}
1225
1226bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1227 QualType SrcRecordTy) {
1228 return IsDeref;
1229}
1230
1231void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1232 llvm::Value *Fn = getBadTypeidFn(CGF);
1233 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1234 CGF.Builder.CreateUnreachable();
1235}
1236
1237llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1238 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001239 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001240 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001241 auto *ClassDecl =
1242 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001243 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001244 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001245
1246 // Load the type info.
1247 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001248 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001249}
1250
1251bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1252 QualType SrcRecordTy) {
1253 return SrcIsPtr;
1254}
1255
1256llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001257 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001258 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1259 llvm::Type *PtrDiffLTy =
1260 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1261 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1262
1263 llvm::Value *SrcRTTI =
1264 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1265 llvm::Value *DestRTTI =
1266 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1267
1268 // Compute the offset hint.
1269 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1270 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1271 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1272 PtrDiffLTy,
1273 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1274
1275 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001276 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001277 Value = CGF.EmitCastToVoidPtr(Value);
1278
1279 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1280 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1281 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1282
1283 /// C++ [expr.dynamic.cast]p9:
1284 /// A failed cast to reference type throws std::bad_cast
1285 if (DestTy->isReferenceType()) {
1286 llvm::BasicBlock *BadCastBlock =
1287 CGF.createBasicBlock("dynamic_cast.bad_cast");
1288
1289 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1290 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1291
1292 CGF.EmitBlock(BadCastBlock);
1293 EmitBadCastCall(CGF);
1294 }
1295
1296 return Value;
1297}
1298
1299llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001300 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001301 QualType SrcRecordTy,
1302 QualType DestTy) {
1303 llvm::Type *PtrDiffLTy =
1304 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1305 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1306
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001307 auto *ClassDecl =
1308 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001309 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001310 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1311 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001312
1313 // Get the offset-to-top from the vtable.
1314 llvm::Value *OffsetToTop =
1315 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001316 OffsetToTop =
1317 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1318 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001319
1320 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001321 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001322 Value = CGF.EmitCastToVoidPtr(Value);
1323 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1324
1325 return CGF.Builder.CreateBitCast(Value, DestLTy);
1326}
1327
1328bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1329 llvm::Value *Fn = getBadCastFn(CGF);
1330 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1331 CGF.Builder.CreateUnreachable();
1332 return true;
1333}
1334
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001335llvm::Value *
1336ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001337 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001338 const CXXRecordDecl *ClassDecl,
1339 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001340 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001341 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001342 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1343 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001344
1345 llvm::Value *VBaseOffsetPtr =
1346 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1347 "vbase.offset.ptr");
1348 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1349 CGM.PtrDiffTy->getPointerTo());
1350
1351 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001352 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1353 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001354
1355 return VBaseOffset;
1356}
1357
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001358void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1359 // Just make sure we're in sync with TargetCXXABI.
1360 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1361
Rafael Espindolac3cde362013-12-09 14:51:17 +00001362 // The constructor used for constructing this as a base class;
1363 // ignores virtual bases.
1364 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1365
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001366 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001367 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001368 if (!D->getParent()->isAbstract()) {
1369 // We don't need to emit the complete ctor if the class is abstract.
1370 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1371 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001372}
1373
George Burgess IVf203dbf2017-02-22 20:28:02 +00001374CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001375ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1376 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001377 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001378
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001379 // All parameters are already in place except VTT, which goes after 'this'.
1380 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001381
1382 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001383 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001384 ArgTys.insert(ArgTys.begin() + 1,
1385 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001386 return AddedStructorArgs::prefix(1);
1387 }
1388 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001389}
1390
Reid Klecknere7de47e2013-07-22 13:51:44 +00001391void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001392 // The destructor used for destructing this as a base class; ignores
1393 // virtual bases.
1394 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001395
1396 // The destructor used for destructing this as a most-derived class;
1397 // call the base destructor and then destructs any virtual bases.
1398 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1399
Rafael Espindolac3cde362013-12-09 14:51:17 +00001400 // The destructor in a virtual table is always a 'deleting'
1401 // destructor, which calls the complete destructor and then uses the
1402 // appropriate operator delete.
1403 if (D->isVirtual())
1404 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001405}
1406
Reid Kleckner89077a12013-12-17 19:46:40 +00001407void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1408 QualType &ResTy,
1409 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001410 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001411 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001412
1413 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001414 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001415 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001416
1417 // FIXME: avoid the fake decl
1418 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001419 auto *VTTDecl = ImplicitParamDecl::Create(
1420 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1421 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001422 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001423 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001424 }
1425}
1426
John McCall5d865c322010-08-31 07:33:07 +00001427void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001428 // Naked functions have no prolog.
1429 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1430 return;
1431
John McCall5d865c322010-08-31 07:33:07 +00001432 /// Initialize the 'this' slot.
1433 EmitThisParam(CGF);
1434
1435 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001436 if (getStructorImplicitParamDecl(CGF)) {
1437 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1438 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001439 }
John McCall5d865c322010-08-31 07:33:07 +00001440
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001441 /// If this is a function that the ABI specifies returns 'this', initialize
1442 /// the return slot to 'this' at the start of the function.
1443 ///
1444 /// Unlike the setting of return types, this is done within the ABI
1445 /// implementation instead of by clients of CGCXXABI because:
1446 /// 1) getThisValue is currently protected
1447 /// 2) in theory, an ABI could implement 'this' returns some other way;
1448 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001449 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001450 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001451}
1452
George Burgess IVf203dbf2017-02-22 20:28:02 +00001453CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001454 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1455 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1456 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001457 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001458
Reid Kleckner89077a12013-12-17 19:46:40 +00001459 // Insert the implicit 'vtt' argument as the second argument.
1460 llvm::Value *VTT =
1461 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1462 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1463 Args.insert(Args.begin() + 1,
1464 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001465 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001466}
1467
1468void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1469 const CXXDestructorDecl *DD,
1470 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001471 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001472 GlobalDecl GD(DD, Type);
1473 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1474 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1475
John McCallb92ab1a2016-10-26 23:46:34 +00001476 CGCallee Callee;
1477 if (getContext().getLangOpts().AppleKext &&
1478 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001479 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001480 else
1481 Callee =
1482 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1483 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001484
John McCall7f416cc2015-09-08 08:05:57 +00001485 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001486 This.getPointer(), VTT, VTTTy,
1487 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001488}
1489
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001490void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1491 const CXXRecordDecl *RD) {
1492 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1493 if (VTable->hasInitializer())
1494 return;
1495
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001496 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001497 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1498 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001499 llvm::Constant *RTTI =
1500 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001501
1502 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001503 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001504 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001505 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1506 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001507
1508 // Set the correct linkage.
1509 VTable->setLinkage(Linkage);
1510
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001511 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1512 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001513
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001514 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001515 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001516
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001517 // Use pointer alignment for the vtable. Otherwise we would align them based
1518 // on the size of the initializer which doesn't make sense as only single
1519 // values are read.
1520 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1521 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1522
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001523 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1524 // we will emit the typeinfo for the fundamental types. This is the
1525 // same behaviour as GCC.
1526 const DeclContext *DC = RD->getDeclContext();
1527 if (RD->getIdentifier() &&
1528 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1529 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1530 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1531 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001532 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001533
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001534 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001535 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001536}
1537
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001538bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1539 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1540 if (Vptr.NearestVBase == nullptr)
1541 return false;
1542 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001543}
1544
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001545llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1546 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1547 const CXXRecordDecl *NearestVBase) {
1548
1549 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1550 NeedsVTTParameter(CGF.CurGD)) {
1551 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1552 NearestVBase);
1553 }
1554 return getVTableAddressPoint(Base, VTableClass);
1555}
1556
1557llvm::Constant *
1558ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1559 const CXXRecordDecl *VTableClass) {
1560 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001561
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001562 // Find the appropriate vtable within the vtable group, and the address point
1563 // within that vtable.
1564 VTableLayout::AddressPointLocation AddressPoint =
1565 CGM.getItaniumVTableContext()
1566 .getVTableLayout(VTableClass)
1567 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001568 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001569 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001570 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1571 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001572 };
1573
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001574 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1575 Indices, /*InBounds=*/true,
1576 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001577}
1578
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001579llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1580 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1581 const CXXRecordDecl *NearestVBase) {
1582 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1583 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1584
1585 // Get the secondary vpointer index.
1586 uint64_t VirtualPointerIndex =
1587 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1588
1589 /// Load the VTT.
1590 llvm::Value *VTT = CGF.LoadCXXVTT();
1591 if (VirtualPointerIndex)
1592 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1593
1594 // And load the address point from the VTT.
1595 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1596}
1597
1598llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1599 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1600 return getVTableAddressPoint(Base, VTableClass);
1601}
1602
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001603llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1604 CharUnits VPtrOffset) {
1605 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1606
1607 llvm::GlobalVariable *&VTable = VTables[RD];
1608 if (VTable)
1609 return VTable;
1610
Eric Christopherd160c502016-01-29 01:35:53 +00001611 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001612 CGM.addDeferredVTable(RD);
1613
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001614 SmallString<256> Name;
1615 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001616 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001617
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001618 const VTableLayout &VTLayout =
1619 CGM.getItaniumVTableContext().getVTableLayout(RD);
1620 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001621
1622 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001623 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001624 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001625
1626 if (RD->hasAttr<DLLImportAttr>())
1627 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1628 else if (RD->hasAttr<DLLExportAttr>())
1629 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1630
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001631 return VTable;
1632}
1633
John McCallb92ab1a2016-10-26 23:46:34 +00001634CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1635 GlobalDecl GD,
1636 Address This,
1637 llvm::Type *Ty,
1638 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001639 GD = GD.getCanonicalDecl();
1640 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001641 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1642 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001643
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001644 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCallb92ab1a2016-10-26 23:46:34 +00001645 llvm::Value *VFunc;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001646 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
John McCallb92ab1a2016-10-26 23:46:34 +00001647 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001648 MethodDecl->getParent(), VTable,
1649 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1650 } else {
1651 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1652
1653 llvm::Value *VFuncPtr =
1654 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001655 auto *VFuncLoad =
1656 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1657
1658 // Add !invariant.load md to virtual function load to indicate that
1659 // function didn't change inside vtable.
1660 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1661 // help in devirtualization because it will only matter if we will have 2
1662 // the same virtual function loads from the same vtable load, which won't
1663 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1664 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1665 CGM.getCodeGenOpts().StrictVTablePointers)
1666 VFuncLoad->setMetadata(
1667 llvm::LLVMContext::MD_invariant_load,
1668 llvm::MDNode::get(CGM.getLLVMContext(),
1669 llvm::ArrayRef<llvm::Metadata *>()));
1670 VFunc = VFuncLoad;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001671 }
John McCallb92ab1a2016-10-26 23:46:34 +00001672
1673 CGCallee Callee(MethodDecl, VFunc);
1674 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001675}
1676
David Majnemer0c0b6d92014-10-31 20:09:12 +00001677llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1678 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001679 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001680 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001681 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1682
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001683 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1684 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001685 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001686 CGCallee Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001687 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1688 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001689
John McCall7f416cc2015-09-08 08:05:57 +00001690 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1691 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001692 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001693 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001694}
1695
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001696void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001697 CodeGenVTables &VTables = CGM.getVTables();
1698 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001699 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001700}
1701
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001702bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001703 // We don't emit available_externally vtables if we are in -fapple-kext mode
1704 // because kext mode does not permit devirtualization.
1705 if (CGM.getLangOpts().AppleKext)
1706 return false;
1707
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001708 // If we don't have any not emitted inline virtual function, and if vtable is
1709 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001710 // FIXME we can still emit a copy of the vtable if we
1711 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001712 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001713}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001714static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001715 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001716 int64_t NonVirtualAdjustment,
1717 int64_t VirtualAdjustment,
1718 bool IsReturnAdjustment) {
1719 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001720 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001721
John McCall7f416cc2015-09-08 08:05:57 +00001722 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001723
John McCall7f416cc2015-09-08 08:05:57 +00001724 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001725 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001726 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1727 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001728 }
1729
John McCall7f416cc2015-09-08 08:05:57 +00001730 // Perform the virtual adjustment if we have one.
1731 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001732 if (VirtualAdjustment) {
1733 llvm::Type *PtrDiffTy =
1734 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1735
John McCall7f416cc2015-09-08 08:05:57 +00001736 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001737 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1738
1739 llvm::Value *OffsetPtr =
1740 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1741
1742 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1743
1744 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001745 llvm::Value *Offset =
1746 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001747
1748 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001749 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1750 } else {
1751 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001752 }
1753
John McCall7f416cc2015-09-08 08:05:57 +00001754 // In a derived-to-base conversion, the non-virtual adjustment is
1755 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001756 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001757 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1758 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001759 }
1760
1761 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001762 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001763}
1764
1765llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001766 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001767 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001768 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1769 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001770 /*IsReturnAdjustment=*/false);
1771}
1772
1773llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001774ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001775 const ReturnAdjustment &RA) {
1776 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1777 RA.Virtual.Itanium.VBaseOffsetOffset,
1778 /*IsReturnAdjustment=*/true);
1779}
1780
John McCall5d865c322010-08-31 07:33:07 +00001781void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1782 RValue RV, QualType ResultType) {
1783 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1784 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1785
1786 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001787 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001788 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1789 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1790}
John McCall8ed55a52010-09-02 09:58:18 +00001791
1792/************************** Array allocation cookies **************************/
1793
John McCallb91cd662012-05-01 05:23:51 +00001794CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1795 // The array cookie is a size_t; pad that up to the element alignment.
1796 // The cookie is actually right-justified in that space.
1797 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1798 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001799}
1800
John McCall7f416cc2015-09-08 08:05:57 +00001801Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1802 Address NewPtr,
1803 llvm::Value *NumElements,
1804 const CXXNewExpr *expr,
1805 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001806 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001807
John McCall7f416cc2015-09-08 08:05:57 +00001808 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001809
John McCall9bca9232010-09-02 10:25:57 +00001810 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001811 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001812
1813 // The size of the cookie.
1814 CharUnits CookieSize =
1815 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001816 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001817
1818 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001819 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001820 CharUnits CookieOffset = CookieSize - SizeSize;
1821 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001822 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001823
1824 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001825 Address NumElementsPtr =
1826 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001827 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001828
1829 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001830 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001831 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001832 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001833 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1834 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001835 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001836 llvm::Constant *F =
1837 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001838 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001839 }
John McCall8ed55a52010-09-02 09:58:18 +00001840
1841 // Finally, compute a pointer to the actual data buffer by skipping
1842 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001843 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001844}
1845
John McCallb91cd662012-05-01 05:23:51 +00001846llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001847 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001848 CharUnits cookieSize) {
1849 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001850 Address numElementsPtr = allocPtr;
1851 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001852 if (!numElementsOffset.isZero())
1853 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001854 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001855
John McCall7f416cc2015-09-08 08:05:57 +00001856 unsigned AS = allocPtr.getAddressSpace();
1857 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001858 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001859 return CGF.Builder.CreateLoad(numElementsPtr);
1860 // In asan mode emit a function call instead of a regular load and let the
1861 // run-time deal with it: if the shadow is properly poisoned return the
1862 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1863 // We can't simply ignore this load using nosanitize metadata because
1864 // the metadata may be lost.
1865 llvm::FunctionType *FTy =
1866 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1867 llvm::Constant *F =
1868 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001869 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001870}
1871
John McCallb91cd662012-05-01 05:23:51 +00001872CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001873 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001874 // struct array_cookie {
1875 // std::size_t element_size; // element_size != 0
1876 // std::size_t element_count;
1877 // };
John McCallc19c7062013-01-25 23:36:19 +00001878 // But the base ABI doesn't give anything an alignment greater than
1879 // 8, so we can dismiss this as typical ABI-author blindness to
1880 // actual language complexity and round up to the element alignment.
1881 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1882 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001883}
1884
John McCall7f416cc2015-09-08 08:05:57 +00001885Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1886 Address newPtr,
1887 llvm::Value *numElements,
1888 const CXXNewExpr *expr,
1889 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001890 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001891
John McCall8ed55a52010-09-02 09:58:18 +00001892 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001893 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001894
1895 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001896 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001897 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1898 getContext().getTypeSizeInChars(elementType).getQuantity());
1899 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001900
1901 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001902 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001903 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001904
1905 // Finally, compute a pointer to the actual data buffer by skipping
1906 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001907 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001908 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001909}
1910
John McCallb91cd662012-05-01 05:23:51 +00001911llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001912 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001913 CharUnits cookieSize) {
1914 // The number of elements is at offset sizeof(size_t) relative to
1915 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001916 Address numElementsPtr
1917 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001918
John McCall7f416cc2015-09-08 08:05:57 +00001919 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001920 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001921}
1922
John McCall68ff0372010-09-08 01:44:27 +00001923/*********************** Static local initialization **************************/
1924
1925static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001926 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001927 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001928 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001929 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001930 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001931 return CGM.CreateRuntimeFunction(
1932 FTy, "__cxa_guard_acquire",
1933 llvm::AttributeList::get(CGM.getLLVMContext(),
1934 llvm::AttributeList::FunctionIndex,
1935 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001936}
1937
1938static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001939 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001940 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001941 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001942 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001943 return CGM.CreateRuntimeFunction(
1944 FTy, "__cxa_guard_release",
1945 llvm::AttributeList::get(CGM.getLLVMContext(),
1946 llvm::AttributeList::FunctionIndex,
1947 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001948}
1949
1950static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001951 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001952 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001953 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001954 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001955 return CGM.CreateRuntimeFunction(
1956 FTy, "__cxa_guard_abort",
1957 llvm::AttributeList::get(CGM.getLLVMContext(),
1958 llvm::AttributeList::FunctionIndex,
1959 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001960}
1961
1962namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001963 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001964 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001965 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001966
Craig Topper4f12f102014-03-12 06:41:41 +00001967 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001968 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1969 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001970 }
1971 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001972}
John McCall68ff0372010-09-08 01:44:27 +00001973
1974/// The ARM code here follows the Itanium code closely enough that we
1975/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001976void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1977 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001978 llvm::GlobalVariable *var,
1979 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001980 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001981
Richard Smith62f19e72016-06-25 00:15:56 +00001982 // Inline variables that weren't instantiated from variable templates have
1983 // partially-ordered initialization within their translation unit.
1984 bool NonTemplateInline =
1985 D.isInline() &&
1986 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1987
1988 // We only need to use thread-safe statics for local non-TLS variables and
1989 // inline variables; other global initialization is always single-threaded
1990 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001991 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001992 (D.isLocalVarDecl() || NonTemplateInline) &&
1993 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001994
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001995 // If we have a global variable with internal linkage and thread-safe statics
1996 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001997 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1998
1999 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002000 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002001 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002002 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002003 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002004 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002005 // Guard variables are 64 bits in the generic ABI and size width on ARM
2006 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002007 if (UseARMGuardVarABI) {
2008 guardTy = CGF.SizeTy;
2009 guardAlignment = CGF.getSizeAlign();
2010 } else {
2011 guardTy = CGF.Int64Ty;
2012 guardAlignment = CharUnits::fromQuantity(
2013 CGM.getDataLayout().getABITypeAlignment(guardTy));
2014 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002015 }
John McCallb88a5662012-03-30 21:00:39 +00002016 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002017
John McCallb88a5662012-03-30 21:00:39 +00002018 // Create the guard variable if we don't already have it (as we
2019 // might if we're double-emitting this function body).
2020 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2021 if (!guard) {
2022 // Mangle the name for the guard.
2023 SmallString<256> guardName;
2024 {
2025 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002026 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002027 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002028
John McCallb88a5662012-03-30 21:00:39 +00002029 // Create the guard variable with a zero-initializer.
2030 // Just absorb linkage and visibility from the guarded variable.
2031 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2032 false, var->getLinkage(),
2033 llvm::ConstantInt::get(guardTy, 0),
2034 guardName.str());
2035 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002036 // If the variable is thread-local, so is its guard variable.
2037 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002038 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002039
Yaron Keren5bfa1082015-09-03 20:33:29 +00002040 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2041 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002042 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002043 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002044 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002045 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2046 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002047 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002048 // An inline variable's guard function is run from the per-TU
2049 // initialization function, not via a dedicated global ctor function, so
2050 // we can't put it in a comdat.
2051 if (!NonTemplateInline)
2052 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002053 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2054 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002055 }
2056
John McCallb88a5662012-03-30 21:00:39 +00002057 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2058 }
John McCall87590e62012-03-30 07:09:50 +00002059
John McCall7f416cc2015-09-08 08:05:57 +00002060 Address guardAddr = Address(guard, guardAlignment);
2061
John McCall68ff0372010-09-08 01:44:27 +00002062 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002063 //
John McCall68ff0372010-09-08 01:44:27 +00002064 // Itanium C++ ABI 3.3.2:
2065 // The following is pseudo-code showing how these functions can be used:
2066 // if (obj_guard.first_byte == 0) {
2067 // if ( __cxa_guard_acquire (&obj_guard) ) {
2068 // try {
2069 // ... initialize the object ...;
2070 // } catch (...) {
2071 // __cxa_guard_abort (&obj_guard);
2072 // throw;
2073 // }
2074 // ... queue object destructor with __cxa_atexit() ...;
2075 // __cxa_guard_release (&obj_guard);
2076 // }
2077 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002078
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002079 // Load the first byte of the guard variable.
2080 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002081 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002082
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002083 // Itanium ABI:
2084 // An implementation supporting thread-safety on multiprocessor
2085 // systems must also guarantee that references to the initialized
2086 // object do not occur before the load of the initialization flag.
2087 //
2088 // In LLVM, we do this by marking the load Acquire.
2089 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002090 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002091
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002092 // For ARM, we should only check the first bit, rather than the entire byte:
2093 //
2094 // ARM C++ ABI 3.2.3.1:
2095 // To support the potential use of initialization guard variables
2096 // as semaphores that are the target of ARM SWP and LDREX/STREX
2097 // synchronizing instructions we define a static initialization
2098 // guard variable to be a 4-byte aligned, 4-byte word with the
2099 // following inline access protocol.
2100 // #define INITIALIZED 1
2101 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2102 // if (__cxa_guard_acquire(&obj_guard))
2103 // ...
2104 // }
2105 //
2106 // and similarly for ARM64:
2107 //
2108 // ARM64 C++ ABI 3.2.2:
2109 // This ABI instead only specifies the value bit 0 of the static guard
2110 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2111 // variable is not initialized and 1 when it is.
2112 llvm::Value *V =
2113 (UseARMGuardVarABI && !useInt8GuardVariable)
2114 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2115 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002116 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002117
2118 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2119 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2120
2121 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002122 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2123 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002124
2125 CGF.EmitBlock(InitCheckBlock);
2126
2127 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002128 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002129 // Call __cxa_guard_acquire.
2130 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002131 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002132
2133 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2134
2135 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2136 InitBlock, EndBlock);
2137
2138 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002139 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002140
2141 CGF.EmitBlock(InitBlock);
2142 }
2143
2144 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002145 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002146
John McCall5aa52592011-06-17 07:33:57 +00002147 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002148 // Pop the guard-abort cleanup if we pushed one.
2149 CGF.PopCleanupBlock();
2150
2151 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002152 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2153 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002154 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002155 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002156 }
2157
2158 CGF.EmitBlock(EndBlock);
2159}
John McCallc84ed6a2012-05-01 06:13:13 +00002160
2161/// Register a global destructor using __cxa_atexit.
2162static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2163 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002164 llvm::Constant *addr,
2165 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002166 const char *Name = "__cxa_atexit";
2167 if (TLS) {
2168 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002169 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002170 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002171
John McCallc84ed6a2012-05-01 06:13:13 +00002172 // We're assuming that the destructor function is something we can
2173 // reasonably call with the default CC. Go ahead and cast it to the
2174 // right prototype.
2175 llvm::Type *dtorTy =
2176 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2177
2178 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2179 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2180 llvm::FunctionType *atexitTy =
2181 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2182
2183 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002184 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002185 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2186 fn->setDoesNotThrow();
2187
2188 // Create a variable that binds the atexit to this shared object.
2189 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002190 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2191 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2192 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002193
2194 llvm::Value *args[] = {
2195 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2196 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2197 handle
2198 };
John McCall882987f2013-02-28 19:01:20 +00002199 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002200}
2201
2202/// Register a global destructor as best as we know how.
2203void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002204 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002205 llvm::Constant *dtor,
2206 llvm::Constant *addr) {
2207 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002208 if (CGM.getCodeGenOpts().CXAAtExit)
2209 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2210
2211 if (D.getTLSKind())
2212 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002213
2214 // In Apple kexts, we want to add a global destructor entry.
2215 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002216 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002217 // Generate a global destructor entry.
2218 return CGM.AddCXXDtorEntry(dtor, addr);
2219 }
2220
David Blaikieebe87e12013-08-27 23:57:18 +00002221 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002222}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002223
David Majnemer9b21c332014-07-11 20:28:10 +00002224static bool isThreadWrapperReplaceable(const VarDecl *VD,
2225 CodeGen::CodeGenModule &CGM) {
2226 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002227 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002228 // the thread wrapper instead of directly referencing the backing variable.
2229 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002230 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002231}
2232
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002233/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002234/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002235/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002236static llvm::GlobalValue::LinkageTypes
2237getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2238 llvm::GlobalValue::LinkageTypes VarLinkage =
2239 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2240
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002241 // For internal linkage variables, we don't need an external or weak wrapper.
2242 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2243 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002244
David Majnemer9b21c332014-07-11 20:28:10 +00002245 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002246 if (isThreadWrapperReplaceable(VD, CGM))
2247 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2248 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2249 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002250 return llvm::GlobalValue::WeakODRLinkage;
2251}
2252
2253llvm::Function *
2254ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002255 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002256 // Mangle the name for the thread_local wrapper function.
2257 SmallString<256> WrapperName;
2258 {
2259 llvm::raw_svector_ostream Out(WrapperName);
2260 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002261 }
2262
Akira Hatanaka26907f92016-01-15 03:34:06 +00002263 // FIXME: If VD is a definition, we should regenerate the function attributes
2264 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002265 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002266 return cast<llvm::Function>(V);
2267
Akira Hatanaka26907f92016-01-15 03:34:06 +00002268 QualType RetQT = VD->getType();
2269 if (RetQT->isReferenceType())
2270 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002271
John McCallc56a8b32016-03-11 04:30:31 +00002272 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2273 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002274
2275 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002276 llvm::Function *Wrapper =
2277 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2278 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002279
2280 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2281
2282 if (VD->hasDefinition())
2283 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2284
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002285 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002286 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2287 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2288 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002289 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002290
2291 if (isThreadWrapperReplaceable(VD, CGM)) {
2292 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2293 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2294 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002295 return Wrapper;
2296}
2297
2298void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002299 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2300 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2301 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002302 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002303
2304 // Separate initializers into those with ordered (or partially-ordered)
2305 // initialization and those with unordered initialization.
2306 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2307 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2308 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2309 if (isTemplateInstantiation(
2310 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2311 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2312 CXXThreadLocalInits[I];
2313 else
2314 OrderedInits.push_back(CXXThreadLocalInits[I]);
2315 }
2316
2317 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002318 // Generate a guarded initialization function.
2319 llvm::FunctionType *FTy =
2320 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002321 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2322 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002323 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002324 /*TLS=*/true);
2325 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2326 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2327 llvm::GlobalVariable::InternalLinkage,
2328 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2329 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002330
2331 CharUnits GuardAlign = CharUnits::One();
2332 Guard->setAlignment(GuardAlign.getQuantity());
2333
Richard Smithfbe23692017-01-13 00:43:31 +00002334 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2335 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002336 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2337 if (CGM.getTarget().getTriple().isOSDarwin()) {
2338 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2339 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2340 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002341 }
Richard Smithfbe23692017-01-13 00:43:31 +00002342
2343 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002344 for (const VarDecl *VD : CXXThreadLocals) {
2345 llvm::GlobalVariable *Var =
2346 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002347 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002348
David Majnemer9b21c332014-07-11 20:28:10 +00002349 // Some targets require that all access to thread local variables go through
2350 // the thread wrapper. This means that we cannot attempt to create a thread
2351 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002352 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2353 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002354 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002355 }
David Majnemer9b21c332014-07-11 20:28:10 +00002356
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002357 // Mangle the name for the thread_local initialization function.
2358 SmallString<256> InitFnName;
2359 {
2360 llvm::raw_svector_ostream Out(InitFnName);
2361 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002362 }
2363
2364 // If we have a definition for the variable, emit the initialization
2365 // function as an alias to the global Init function (if any). Otherwise,
2366 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002367 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002368 bool InitIsInitFunc = false;
2369 if (VD->hasDefinition()) {
2370 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002371 llvm::Function *InitFuncToUse = InitFunc;
2372 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2373 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2374 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002375 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002376 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002377 } else {
2378 // Emit a weak global function referring to the initialization function.
2379 // This function will not exist if the TU defining the thread_local
2380 // variable in question does not need any dynamic initialization for
2381 // its thread_local variables.
2382 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002383 Init = llvm::Function::Create(FnTy,
2384 llvm::GlobalVariable::ExternalWeakLinkage,
2385 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002386 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002387 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002388 }
2389
2390 if (Init)
2391 Init->setVisibility(Var->getVisibility());
2392
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002393 llvm::LLVMContext &Context = CGM.getModule().getContext();
2394 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002395 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002396 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002397 if (Init) {
2398 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2399 if (isThreadWrapperReplaceable(VD, CGM))
2400 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2401 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002402 } else {
2403 // Don't know whether we have an init function. Call it if it exists.
2404 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2405 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2406 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2407 Builder.CreateCondBr(Have, InitBB, ExitBB);
2408
2409 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002410 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002411 Builder.CreateBr(ExitBB);
2412
2413 Builder.SetInsertPoint(ExitBB);
2414 }
2415
2416 // For a reference, the result of the wrapper function is a pointer to
2417 // the referenced object.
2418 llvm::Value *Val = Var;
2419 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002420 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2421 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002422 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002423 if (Val->getType() != Wrapper->getReturnType())
2424 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2425 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002426 Builder.CreateRet(Val);
2427 }
2428}
2429
Richard Smith0f383742014-03-26 22:48:22 +00002430LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2431 const VarDecl *VD,
2432 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002433 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002434 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002435
Manman Renb0b3af72015-12-17 00:42:36 +00002436 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002437 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002438
2439 LValue LV;
2440 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002441 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002442 else
Manman Renb0b3af72015-12-17 00:42:36 +00002443 LV = CGF.MakeAddrLValue(CallVal, LValType,
2444 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002445 // FIXME: need setObjCGCLValueClass?
2446 return LV;
2447}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002448
2449/// Return whether the given global decl needs a VTT parameter, which it does
2450/// if it's a base constructor or destructor with virtual bases.
2451bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2452 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2453
2454 // We don't have any virtual bases, just return early.
2455 if (!MD->getParent()->getNumVBases())
2456 return false;
2457
2458 // Check if we have a base constructor.
2459 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2460 return true;
2461
2462 // Check if we have a base destructor.
2463 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2464 return true;
2465
2466 return false;
2467}
David Majnemere2cb8d12014-07-07 06:20:47 +00002468
2469namespace {
2470class ItaniumRTTIBuilder {
2471 CodeGenModule &CGM; // Per-module state.
2472 llvm::LLVMContext &VMContext;
2473 const ItaniumCXXABI &CXXABI; // Per-module state.
2474
2475 /// Fields - The fields of the RTTI descriptor currently being built.
2476 SmallVector<llvm::Constant *, 16> Fields;
2477
2478 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2479 llvm::GlobalVariable *
2480 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2481
2482 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2483 /// descriptor of the given type.
2484 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2485
2486 /// BuildVTablePointer - Build the vtable pointer for the given type.
2487 void BuildVTablePointer(const Type *Ty);
2488
2489 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2490 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2491 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2492
2493 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2494 /// classes with bases that do not satisfy the abi::__si_class_type_info
2495 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2496 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2497
2498 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2499 /// for pointer types.
2500 void BuildPointerTypeInfo(QualType PointeeTy);
2501
2502 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2503 /// type_info for an object type.
2504 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2505
2506 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2507 /// struct, used for member pointer types.
2508 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2509
2510public:
2511 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2512 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2513
2514 // Pointer type info flags.
2515 enum {
2516 /// PTI_Const - Type has const qualifier.
2517 PTI_Const = 0x1,
2518
2519 /// PTI_Volatile - Type has volatile qualifier.
2520 PTI_Volatile = 0x2,
2521
2522 /// PTI_Restrict - Type has restrict qualifier.
2523 PTI_Restrict = 0x4,
2524
2525 /// PTI_Incomplete - Type is incomplete.
2526 PTI_Incomplete = 0x8,
2527
2528 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2529 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002530 PTI_ContainingClassIncomplete = 0x10,
2531
2532 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2533 //PTI_TransactionSafe = 0x20,
2534
2535 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2536 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002537 };
2538
2539 // VMI type info flags.
2540 enum {
2541 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2542 VMI_NonDiamondRepeat = 0x1,
2543
2544 /// VMI_DiamondShaped - Class is diamond shaped.
2545 VMI_DiamondShaped = 0x2
2546 };
2547
2548 // Base class type info flags.
2549 enum {
2550 /// BCTI_Virtual - Base class is virtual.
2551 BCTI_Virtual = 0x1,
2552
2553 /// BCTI_Public - Base class is public.
2554 BCTI_Public = 0x2
2555 };
2556
2557 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2558 ///
2559 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002560 /// \param DLLExport - true to mark the RTTI value as DLLExport
2561 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2562 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002563};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002564}
David Majnemere2cb8d12014-07-07 06:20:47 +00002565
2566llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2567 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002568 SmallString<256> Name;
2569 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002570 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002571
2572 // We know that the mangled name of the type starts at index 4 of the
2573 // mangled name of the typename, so we can just index into it in order to
2574 // get the mangled name of the type.
2575 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2576 Name.substr(4));
2577
2578 llvm::GlobalVariable *GV =
2579 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2580
2581 GV->setInitializer(Init);
2582
2583 return GV;
2584}
2585
2586llvm::Constant *
2587ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2588 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002589 SmallString<256> Name;
2590 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002591 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002592
2593 // Look for an existing global.
2594 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2595
2596 if (!GV) {
2597 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002598 // Note for the future: If we would ever like to do deferred emission of
2599 // RTTI, check if emitting vtables opportunistically need any adjustment.
2600
David Majnemere2cb8d12014-07-07 06:20:47 +00002601 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2602 /*Constant=*/true,
2603 llvm::GlobalValue::ExternalLinkage, nullptr,
2604 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002605 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2606 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2607 if (RD->hasAttr<DLLImportAttr>())
2608 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2609 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002610 }
2611
2612 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2613}
2614
2615/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2616/// info for that type is defined in the standard library.
2617static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2618 // Itanium C++ ABI 2.9.2:
2619 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2620 // the run-time support library. Specifically, the run-time support
2621 // library should contain type_info objects for the types X, X* and
2622 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2623 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2624 // long, unsigned long, long long, unsigned long long, float, double,
2625 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2626 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002627 //
2628 // GCC also emits RTTI for __int128.
2629 // FIXME: We do not emit RTTI information for decimal types here.
2630
2631 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002632 switch (Ty->getKind()) {
2633 case BuiltinType::Void:
2634 case BuiltinType::NullPtr:
2635 case BuiltinType::Bool:
2636 case BuiltinType::WChar_S:
2637 case BuiltinType::WChar_U:
2638 case BuiltinType::Char_U:
2639 case BuiltinType::Char_S:
2640 case BuiltinType::UChar:
2641 case BuiltinType::SChar:
2642 case BuiltinType::Short:
2643 case BuiltinType::UShort:
2644 case BuiltinType::Int:
2645 case BuiltinType::UInt:
2646 case BuiltinType::Long:
2647 case BuiltinType::ULong:
2648 case BuiltinType::LongLong:
2649 case BuiltinType::ULongLong:
2650 case BuiltinType::Half:
2651 case BuiltinType::Float:
2652 case BuiltinType::Double:
2653 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002654 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002655 case BuiltinType::Char16:
2656 case BuiltinType::Char32:
2657 case BuiltinType::Int128:
2658 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002659 return true;
2660
Alexey Bader954ba212016-04-08 13:40:33 +00002661#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2662 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002663#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002664 case BuiltinType::OCLSampler:
2665 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002666 case BuiltinType::OCLClkEvent:
2667 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002668 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002669 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002670
2671 case BuiltinType::Dependent:
2672#define BUILTIN_TYPE(Id, SingletonId)
2673#define PLACEHOLDER_TYPE(Id, SingletonId) \
2674 case BuiltinType::Id:
2675#include "clang/AST/BuiltinTypes.def"
2676 llvm_unreachable("asking for RRTI for a placeholder type!");
2677
2678 case BuiltinType::ObjCId:
2679 case BuiltinType::ObjCClass:
2680 case BuiltinType::ObjCSel:
2681 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2682 }
2683
2684 llvm_unreachable("Invalid BuiltinType Kind!");
2685}
2686
2687static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2688 QualType PointeeTy = PointerTy->getPointeeType();
2689 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2690 if (!BuiltinTy)
2691 return false;
2692
2693 // Check the qualifiers.
2694 Qualifiers Quals = PointeeTy.getQualifiers();
2695 Quals.removeConst();
2696
2697 if (!Quals.empty())
2698 return false;
2699
2700 return TypeInfoIsInStandardLibrary(BuiltinTy);
2701}
2702
2703/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2704/// information for the given type exists in the standard library.
2705static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2706 // Type info for builtin types is defined in the standard library.
2707 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2708 return TypeInfoIsInStandardLibrary(BuiltinTy);
2709
2710 // Type info for some pointer types to builtin types is defined in the
2711 // standard library.
2712 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2713 return TypeInfoIsInStandardLibrary(PointerTy);
2714
2715 return false;
2716}
2717
2718/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2719/// the given type exists somewhere else, and that we should not emit the type
2720/// information in this translation unit. Assumes that it is not a
2721/// standard-library type.
2722static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2723 QualType Ty) {
2724 ASTContext &Context = CGM.getContext();
2725
2726 // If RTTI is disabled, assume it might be disabled in the
2727 // translation unit that defines any potential key function, too.
2728 if (!Context.getLangOpts().RTTI) return false;
2729
2730 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2731 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2732 if (!RD->hasDefinition())
2733 return false;
2734
2735 if (!RD->isDynamicClass())
2736 return false;
2737
2738 // FIXME: this may need to be reconsidered if the key function
2739 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002740 // N.B. We must always emit the RTTI data ourselves if there exists a key
2741 // function.
2742 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002743 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002744 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2745 ? false
2746 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002747
David Majnemerbe9022c2015-08-06 20:56:55 +00002748 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002749 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002750 }
2751
2752 return false;
2753}
2754
2755/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2756static bool IsIncompleteClassType(const RecordType *RecordTy) {
2757 return !RecordTy->getDecl()->isCompleteDefinition();
2758}
2759
2760/// ContainsIncompleteClassType - Returns whether the given type contains an
2761/// incomplete class type. This is true if
2762///
2763/// * The given type is an incomplete class type.
2764/// * The given type is a pointer type whose pointee type contains an
2765/// incomplete class type.
2766/// * The given type is a member pointer type whose class is an incomplete
2767/// class type.
2768/// * The given type is a member pointer type whoise pointee type contains an
2769/// incomplete class type.
2770/// is an indirect or direct pointer to an incomplete class type.
2771static bool ContainsIncompleteClassType(QualType Ty) {
2772 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2773 if (IsIncompleteClassType(RecordTy))
2774 return true;
2775 }
2776
2777 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2778 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2779
2780 if (const MemberPointerType *MemberPointerTy =
2781 dyn_cast<MemberPointerType>(Ty)) {
2782 // Check if the class type is incomplete.
2783 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2784 if (IsIncompleteClassType(ClassType))
2785 return true;
2786
2787 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2788 }
2789
2790 return false;
2791}
2792
2793// CanUseSingleInheritance - Return whether the given record decl has a "single,
2794// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2795// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2796static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2797 // Check the number of bases.
2798 if (RD->getNumBases() != 1)
2799 return false;
2800
2801 // Get the base.
2802 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2803
2804 // Check that the base is not virtual.
2805 if (Base->isVirtual())
2806 return false;
2807
2808 // Check that the base is public.
2809 if (Base->getAccessSpecifier() != AS_public)
2810 return false;
2811
2812 // Check that the class is dynamic iff the base is.
2813 const CXXRecordDecl *BaseDecl =
2814 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2815 if (!BaseDecl->isEmpty() &&
2816 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2817 return false;
2818
2819 return true;
2820}
2821
2822void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2823 // abi::__class_type_info.
2824 static const char * const ClassTypeInfo =
2825 "_ZTVN10__cxxabiv117__class_type_infoE";
2826 // abi::__si_class_type_info.
2827 static const char * const SIClassTypeInfo =
2828 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2829 // abi::__vmi_class_type_info.
2830 static const char * const VMIClassTypeInfo =
2831 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2832
2833 const char *VTableName = nullptr;
2834
2835 switch (Ty->getTypeClass()) {
2836#define TYPE(Class, Base)
2837#define ABSTRACT_TYPE(Class, Base)
2838#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2839#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2840#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2841#include "clang/AST/TypeNodes.def"
2842 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2843
2844 case Type::LValueReference:
2845 case Type::RValueReference:
2846 llvm_unreachable("References shouldn't get here");
2847
2848 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002849 case Type::DeducedTemplateSpecialization:
2850 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002851
Xiuli Pan9c14e282016-01-09 12:53:17 +00002852 case Type::Pipe:
2853 llvm_unreachable("Pipe types shouldn't get here");
2854
David Majnemere2cb8d12014-07-07 06:20:47 +00002855 case Type::Builtin:
2856 // GCC treats vector and complex types as fundamental types.
2857 case Type::Vector:
2858 case Type::ExtVector:
2859 case Type::Complex:
2860 case Type::Atomic:
2861 // FIXME: GCC treats block pointers as fundamental types?!
2862 case Type::BlockPointer:
2863 // abi::__fundamental_type_info.
2864 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2865 break;
2866
2867 case Type::ConstantArray:
2868 case Type::IncompleteArray:
2869 case Type::VariableArray:
2870 // abi::__array_type_info.
2871 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2872 break;
2873
2874 case Type::FunctionNoProto:
2875 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002876 // abi::__function_type_info.
2877 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002878 break;
2879
2880 case Type::Enum:
2881 // abi::__enum_type_info.
2882 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2883 break;
2884
2885 case Type::Record: {
2886 const CXXRecordDecl *RD =
2887 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2888
2889 if (!RD->hasDefinition() || !RD->getNumBases()) {
2890 VTableName = ClassTypeInfo;
2891 } else if (CanUseSingleInheritance(RD)) {
2892 VTableName = SIClassTypeInfo;
2893 } else {
2894 VTableName = VMIClassTypeInfo;
2895 }
2896
2897 break;
2898 }
2899
2900 case Type::ObjCObject:
2901 // Ignore protocol qualifiers.
2902 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2903
2904 // Handle id and Class.
2905 if (isa<BuiltinType>(Ty)) {
2906 VTableName = ClassTypeInfo;
2907 break;
2908 }
2909
2910 assert(isa<ObjCInterfaceType>(Ty));
2911 // Fall through.
2912
2913 case Type::ObjCInterface:
2914 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2915 VTableName = SIClassTypeInfo;
2916 } else {
2917 VTableName = ClassTypeInfo;
2918 }
2919 break;
2920
2921 case Type::ObjCObjectPointer:
2922 case Type::Pointer:
2923 // abi::__pointer_type_info.
2924 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2925 break;
2926
2927 case Type::MemberPointer:
2928 // abi::__pointer_to_member_type_info.
2929 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2930 break;
2931 }
2932
2933 llvm::Constant *VTable =
2934 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2935
2936 llvm::Type *PtrDiffTy =
2937 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2938
2939 // The vtable address point is 2.
2940 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002941 VTable =
2942 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002943 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2944
2945 Fields.push_back(VTable);
2946}
2947
2948/// \brief Return the linkage that the type info and type info name constants
2949/// should have for the given type.
2950static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2951 QualType Ty) {
2952 // Itanium C++ ABI 2.9.5p7:
2953 // In addition, it and all of the intermediate abi::__pointer_type_info
2954 // structs in the chain down to the abi::__class_type_info for the
2955 // incomplete class type must be prevented from resolving to the
2956 // corresponding type_info structs for the complete class type, possibly
2957 // by making them local static objects. Finally, a dummy class RTTI is
2958 // generated for the incomplete type that will not resolve to the final
2959 // complete class RTTI (because the latter need not exist), possibly by
2960 // making it a local static object.
2961 if (ContainsIncompleteClassType(Ty))
2962 return llvm::GlobalValue::InternalLinkage;
2963
2964 switch (Ty->getLinkage()) {
2965 case NoLinkage:
2966 case InternalLinkage:
2967 case UniqueExternalLinkage:
2968 return llvm::GlobalValue::InternalLinkage;
2969
2970 case VisibleNoLinkage:
Richard Smith1283e982017-07-07 20:04:28 +00002971 case ModuleInternalLinkage:
2972 case ModuleLinkage:
David Majnemere2cb8d12014-07-07 06:20:47 +00002973 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002974 // RTTI is not enabled, which means that this type info struct is going
2975 // to be used for exception handling. Give it linkonce_odr linkage.
2976 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00002977 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00002978
2979 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2980 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2981 if (RD->hasAttr<WeakAttr>())
2982 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002983 if (CGM.getTriple().isWindowsItaniumEnvironment())
Shoaib Meenai61118e72017-07-04 01:02:19 +00002984 if (RD->hasAttr<DLLImportAttr>() &&
2985 ShouldUseExternalRTTIDescriptor(CGM, Ty))
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002986 return llvm::GlobalValue::ExternalLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002987 if (RD->isDynamicClass()) {
2988 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2989 // MinGW won't export the RTTI information when there is a key function.
2990 // Make sure we emit our own copy instead of attempting to dllimport it.
2991 if (RD->hasAttr<DLLImportAttr>() &&
2992 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2993 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2994 return LT;
2995 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002996 }
2997
2998 return llvm::GlobalValue::LinkOnceODRLinkage;
2999 }
3000
3001 llvm_unreachable("Invalid linkage!");
3002}
3003
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003004llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3005 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003006 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003007 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003008
3009 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003010 SmallString<256> Name;
3011 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003012 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003013
3014 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3015 if (OldGV && !OldGV->isDeclaration()) {
3016 assert(!OldGV->hasAvailableExternallyLinkage() &&
3017 "available_externally typeinfos not yet implemented");
3018
3019 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3020 }
3021
3022 // Check if there is already an external RTTI descriptor for this type.
3023 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3024 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3025 return GetAddrOfExternalRTTIDescriptor(Ty);
3026
3027 // Emit the standard library with external linkage.
3028 llvm::GlobalVariable::LinkageTypes Linkage;
3029 if (IsStdLib)
3030 Linkage = llvm::GlobalValue::ExternalLinkage;
3031 else
3032 Linkage = getTypeInfoLinkage(CGM, Ty);
3033
3034 // Add the vtable pointer.
3035 BuildVTablePointer(cast<Type>(Ty));
3036
3037 // And the name.
3038 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3039 llvm::Constant *TypeNameField;
3040
3041 // If we're supposed to demote the visibility, be sure to set a flag
3042 // to use a string comparison for type_info comparisons.
3043 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3044 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3045 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3046 // The flag is the sign bit, which on ARM64 is defined to be clear
3047 // for global pointers. This is very ARM64-specific.
3048 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3049 llvm::Constant *flag =
3050 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3051 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3052 TypeNameField =
3053 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3054 } else {
3055 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3056 }
3057 Fields.push_back(TypeNameField);
3058
3059 switch (Ty->getTypeClass()) {
3060#define TYPE(Class, Base)
3061#define ABSTRACT_TYPE(Class, Base)
3062#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3063#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3064#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3065#include "clang/AST/TypeNodes.def"
3066 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3067
3068 // GCC treats vector types as fundamental types.
3069 case Type::Builtin:
3070 case Type::Vector:
3071 case Type::ExtVector:
3072 case Type::Complex:
3073 case Type::BlockPointer:
3074 // Itanium C++ ABI 2.9.5p4:
3075 // abi::__fundamental_type_info adds no data members to std::type_info.
3076 break;
3077
3078 case Type::LValueReference:
3079 case Type::RValueReference:
3080 llvm_unreachable("References shouldn't get here");
3081
3082 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003083 case Type::DeducedTemplateSpecialization:
3084 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003085
Xiuli Pan9c14e282016-01-09 12:53:17 +00003086 case Type::Pipe:
3087 llvm_unreachable("Pipe type shouldn't get here");
3088
David Majnemere2cb8d12014-07-07 06:20:47 +00003089 case Type::ConstantArray:
3090 case Type::IncompleteArray:
3091 case Type::VariableArray:
3092 // Itanium C++ ABI 2.9.5p5:
3093 // abi::__array_type_info adds no data members to std::type_info.
3094 break;
3095
3096 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003097 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003098 // Itanium C++ ABI 2.9.5p5:
3099 // abi::__function_type_info adds no data members to std::type_info.
3100 break;
3101
3102 case Type::Enum:
3103 // Itanium C++ ABI 2.9.5p5:
3104 // abi::__enum_type_info adds no data members to std::type_info.
3105 break;
3106
3107 case Type::Record: {
3108 const CXXRecordDecl *RD =
3109 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3110 if (!RD->hasDefinition() || !RD->getNumBases()) {
3111 // We don't need to emit any fields.
3112 break;
3113 }
3114
3115 if (CanUseSingleInheritance(RD))
3116 BuildSIClassTypeInfo(RD);
3117 else
3118 BuildVMIClassTypeInfo(RD);
3119
3120 break;
3121 }
3122
3123 case Type::ObjCObject:
3124 case Type::ObjCInterface:
3125 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3126 break;
3127
3128 case Type::ObjCObjectPointer:
3129 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3130 break;
3131
3132 case Type::Pointer:
3133 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3134 break;
3135
3136 case Type::MemberPointer:
3137 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3138 break;
3139
3140 case Type::Atomic:
3141 // No fields, at least for the moment.
3142 break;
3143 }
3144
3145 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3146
Rafael Espindolacb92c192015-01-15 23:18:01 +00003147 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003148 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003149 new llvm::GlobalVariable(M, Init->getType(),
3150 /*Constant=*/true, Linkage, Init, Name);
3151
David Majnemere2cb8d12014-07-07 06:20:47 +00003152 // If there's already an old global variable, replace it with the new one.
3153 if (OldGV) {
3154 GV->takeName(OldGV);
3155 llvm::Constant *NewPtr =
3156 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3157 OldGV->replaceAllUsesWith(NewPtr);
3158 OldGV->eraseFromParent();
3159 }
3160
Yaron Keren04da2382015-07-29 15:42:28 +00003161 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3162 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3163
David Majnemere2cb8d12014-07-07 06:20:47 +00003164 // The Itanium ABI specifies that type_info objects must be globally
3165 // unique, with one exception: if the type is an incomplete class
3166 // type or a (possibly indirect) pointer to one. That exception
3167 // affects the general case of comparing type_info objects produced
3168 // by the typeid operator, which is why the comparison operators on
3169 // std::type_info generally use the type_info name pointers instead
3170 // of the object addresses. However, the language's built-in uses
3171 // of RTTI generally require class types to be complete, even when
3172 // manipulating pointers to those class types. This allows the
3173 // implementation of dynamic_cast to rely on address equality tests,
3174 // which is much faster.
3175
3176 // All of this is to say that it's important that both the type_info
3177 // object and the type_info name be uniqued when weakly emitted.
3178
3179 // Give the type_info object and name the formal visibility of the
3180 // type itself.
3181 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3182 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3183 // If the linkage is local, only default visibility makes sense.
3184 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3185 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3186 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3187 else
3188 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003189
David Majnemere2cb8d12014-07-07 06:20:47 +00003190 TypeName->setVisibility(llvmVisibility);
3191 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003192
3193 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3194 auto RD = Ty->getAsCXXRecordDecl();
3195 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3196 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3197 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003198 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3199 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003200 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3201 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3202
3203 // Because the typename and the typeinfo are DLL import, convert them to
3204 // declarations rather than definitions. The initializers still need to
3205 // be constructed to calculate the type for the declarations.
3206 TypeName->setInitializer(nullptr);
3207 GV->setInitializer(nullptr);
3208 }
3209 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003210
3211 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3212}
3213
David Majnemere2cb8d12014-07-07 06:20:47 +00003214/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3215/// for the given Objective-C object type.
3216void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3217 // Drop qualifiers.
3218 const Type *T = OT->getBaseType().getTypePtr();
3219 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3220
3221 // The builtin types are abi::__class_type_infos and don't require
3222 // extra fields.
3223 if (isa<BuiltinType>(T)) return;
3224
3225 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3226 ObjCInterfaceDecl *Super = Class->getSuperClass();
3227
3228 // Root classes are also __class_type_info.
3229 if (!Super) return;
3230
3231 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3232
3233 // Everything else is single inheritance.
3234 llvm::Constant *BaseTypeInfo =
3235 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3236 Fields.push_back(BaseTypeInfo);
3237}
3238
3239/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3240/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3241void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3242 // Itanium C++ ABI 2.9.5p6b:
3243 // It adds to abi::__class_type_info a single member pointing to the
3244 // type_info structure for the base type,
3245 llvm::Constant *BaseTypeInfo =
3246 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3247 Fields.push_back(BaseTypeInfo);
3248}
3249
3250namespace {
3251 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3252 /// a class hierarchy.
3253 struct SeenBases {
3254 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3255 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3256 };
3257}
3258
3259/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3260/// abi::__vmi_class_type_info.
3261///
3262static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3263 SeenBases &Bases) {
3264
3265 unsigned Flags = 0;
3266
3267 const CXXRecordDecl *BaseDecl =
3268 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3269
3270 if (Base->isVirtual()) {
3271 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003272 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003273 // If this virtual base has been seen before, then the class is diamond
3274 // shaped.
3275 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3276 } else {
3277 if (Bases.NonVirtualBases.count(BaseDecl))
3278 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3279 }
3280 } else {
3281 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003282 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003283 // If this non-virtual base has been seen before, then the class has non-
3284 // diamond shaped repeated inheritance.
3285 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3286 } else {
3287 if (Bases.VirtualBases.count(BaseDecl))
3288 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3289 }
3290 }
3291
3292 // Walk all bases.
3293 for (const auto &I : BaseDecl->bases())
3294 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3295
3296 return Flags;
3297}
3298
3299static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3300 unsigned Flags = 0;
3301 SeenBases Bases;
3302
3303 // Walk all bases.
3304 for (const auto &I : RD->bases())
3305 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3306
3307 return Flags;
3308}
3309
3310/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3311/// classes with bases that do not satisfy the abi::__si_class_type_info
3312/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3313void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3314 llvm::Type *UnsignedIntLTy =
3315 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3316
3317 // Itanium C++ ABI 2.9.5p6c:
3318 // __flags is a word with flags describing details about the class
3319 // structure, which may be referenced by using the __flags_masks
3320 // enumeration. These flags refer to both direct and indirect bases.
3321 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3322 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3323
3324 // Itanium C++ ABI 2.9.5p6c:
3325 // __base_count is a word with the number of direct proper base class
3326 // descriptions that follow.
3327 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3328
3329 if (!RD->getNumBases())
3330 return;
3331
David Majnemere2cb8d12014-07-07 06:20:47 +00003332 // Now add the base class descriptions.
3333
3334 // Itanium C++ ABI 2.9.5p6c:
3335 // __base_info[] is an array of base class descriptions -- one for every
3336 // direct proper base. Each description is of the type:
3337 //
3338 // struct abi::__base_class_type_info {
3339 // public:
3340 // const __class_type_info *__base_type;
3341 // long __offset_flags;
3342 //
3343 // enum __offset_flags_masks {
3344 // __virtual_mask = 0x1,
3345 // __public_mask = 0x2,
3346 // __offset_shift = 8
3347 // };
3348 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003349
3350 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3351 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3352 // LLP64 platforms.
3353 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3354 // LLP64 platforms.
3355 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3356 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3357 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3358 OffsetFlagsTy = CGM.getContext().LongLongTy;
3359 llvm::Type *OffsetFlagsLTy =
3360 CGM.getTypes().ConvertType(OffsetFlagsTy);
3361
David Majnemere2cb8d12014-07-07 06:20:47 +00003362 for (const auto &Base : RD->bases()) {
3363 // The __base_type member points to the RTTI for the base type.
3364 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3365
3366 const CXXRecordDecl *BaseDecl =
3367 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3368
3369 int64_t OffsetFlags = 0;
3370
3371 // All but the lower 8 bits of __offset_flags are a signed offset.
3372 // For a non-virtual base, this is the offset in the object of the base
3373 // subobject. For a virtual base, this is the offset in the virtual table of
3374 // the virtual base offset for the virtual base referenced (negative).
3375 CharUnits Offset;
3376 if (Base.isVirtual())
3377 Offset =
3378 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3379 else {
3380 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3381 Offset = Layout.getBaseClassOffset(BaseDecl);
3382 };
3383
3384 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3385
3386 // The low-order byte of __offset_flags contains flags, as given by the
3387 // masks from the enumeration __offset_flags_masks.
3388 if (Base.isVirtual())
3389 OffsetFlags |= BCTI_Virtual;
3390 if (Base.getAccessSpecifier() == AS_public)
3391 OffsetFlags |= BCTI_Public;
3392
Reid Klecknerd8b04662016-08-25 22:16:30 +00003393 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003394 }
3395}
3396
Richard Smitha7d93782016-12-01 03:32:42 +00003397/// Compute the flags for a __pbase_type_info, and remove the corresponding
3398/// pieces from \p Type.
3399static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3400 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003401
Richard Smitha7d93782016-12-01 03:32:42 +00003402 if (Type.isConstQualified())
3403 Flags |= ItaniumRTTIBuilder::PTI_Const;
3404 if (Type.isVolatileQualified())
3405 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3406 if (Type.isRestrictQualified())
3407 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3408 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003409
3410 // Itanium C++ ABI 2.9.5p7:
3411 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3412 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003413 if (ContainsIncompleteClassType(Type))
3414 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3415
3416 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3417 if (Proto->isNothrow(Ctx)) {
3418 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
3419 Type = Ctx.getFunctionType(
3420 Proto->getReturnType(), Proto->getParamTypes(),
3421 Proto->getExtProtoInfo().withExceptionSpec(EST_None));
3422 }
3423 }
3424
3425 return Flags;
3426}
3427
3428/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3429/// used for pointer types.
3430void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3431 // Itanium C++ ABI 2.9.5p7:
3432 // __flags is a flag word describing the cv-qualification and other
3433 // attributes of the type pointed to
3434 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003435
3436 llvm::Type *UnsignedIntLTy =
3437 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3438 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3439
3440 // Itanium C++ ABI 2.9.5p7:
3441 // __pointee is a pointer to the std::type_info derivation for the
3442 // unqualified type being pointed to.
3443 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003444 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003445 Fields.push_back(PointeeTypeInfo);
3446}
3447
3448/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3449/// struct, used for member pointer types.
3450void
3451ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3452 QualType PointeeTy = Ty->getPointeeType();
3453
David Majnemere2cb8d12014-07-07 06:20:47 +00003454 // Itanium C++ ABI 2.9.5p7:
3455 // __flags is a flag word describing the cv-qualification and other
3456 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003457 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003458
3459 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003460 if (IsIncompleteClassType(ClassType))
3461 Flags |= PTI_ContainingClassIncomplete;
3462
3463 llvm::Type *UnsignedIntLTy =
3464 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3465 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3466
3467 // Itanium C++ ABI 2.9.5p7:
3468 // __pointee is a pointer to the std::type_info derivation for the
3469 // unqualified type being pointed to.
3470 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003471 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003472 Fields.push_back(PointeeTypeInfo);
3473
3474 // Itanium C++ ABI 2.9.5p9:
3475 // __context is a pointer to an abi::__class_type_info corresponding to the
3476 // class type containing the member pointed to
3477 // (e.g., the "A" in "int A::*").
3478 Fields.push_back(
3479 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3480}
3481
David Majnemer443250f2015-03-17 20:35:00 +00003482llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003483 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3484}
3485
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003486void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3487 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003488 QualType PointerType = getContext().getPointerType(Type);
3489 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003490 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3491 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3492 DLLExport);
3493 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3494 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003495}
3496
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003497void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003498 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003499 QualType FundamentalTypes[] = {
3500 getContext().VoidTy, getContext().NullPtrTy,
3501 getContext().BoolTy, getContext().WCharTy,
3502 getContext().CharTy, getContext().UnsignedCharTy,
3503 getContext().SignedCharTy, getContext().ShortTy,
3504 getContext().UnsignedShortTy, getContext().IntTy,
3505 getContext().UnsignedIntTy, getContext().LongTy,
3506 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003507 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3508 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003509 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003510 getContext().LongDoubleTy, getContext().Float128Ty,
3511 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003512 };
3513 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003514 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003515}
3516
3517/// What sort of uniqueness rules should we use for the RTTI for the
3518/// given type?
3519ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3520 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3521 if (shouldRTTIBeUnique())
3522 return RUK_Unique;
3523
3524 // It's only necessary for linkonce_odr or weak_odr linkage.
3525 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3526 Linkage != llvm::GlobalValue::WeakODRLinkage)
3527 return RUK_Unique;
3528
3529 // It's only necessary with default visibility.
3530 if (CanTy->getVisibility() != DefaultVisibility)
3531 return RUK_Unique;
3532
3533 // If we're not required to publish this symbol, hide it.
3534 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3535 return RUK_NonUniqueHidden;
3536
3537 // If we're required to publish this symbol, as we might be under an
3538 // explicit instantiation, leave it with default visibility but
3539 // enable string-comparisons.
3540 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3541 return RUK_NonUniqueVisible;
3542}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003543
Rafael Espindola1e4df922014-09-16 15:18:21 +00003544// Find out how to codegen the complete destructor and constructor
3545namespace {
3546enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3547}
3548static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3549 const CXXMethodDecl *MD) {
3550 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3551 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003552
Rafael Espindola1e4df922014-09-16 15:18:21 +00003553 // The complete and base structors are not equivalent if there are any virtual
3554 // bases, so emit separate functions.
3555 if (MD->getParent()->getNumVBases())
3556 return StructorCodegen::Emit;
3557
3558 GlobalDecl AliasDecl;
3559 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3560 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3561 } else {
3562 const auto *CD = cast<CXXConstructorDecl>(MD);
3563 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3564 }
3565 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3566
3567 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3568 return StructorCodegen::RAUW;
3569
3570 // FIXME: Should we allow available_externally aliases?
3571 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3572 return StructorCodegen::RAUW;
3573
Rafael Espindola0806f982014-09-16 20:19:43 +00003574 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003575 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3576 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3577 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003578 return StructorCodegen::COMDAT;
3579 return StructorCodegen::Emit;
3580 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003581
3582 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003583}
3584
Rafael Espindola1e4df922014-09-16 15:18:21 +00003585static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3586 GlobalDecl AliasDecl,
3587 GlobalDecl TargetDecl) {
3588 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3589
3590 StringRef MangledName = CGM.getMangledName(AliasDecl);
3591 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3592 if (Entry && !Entry->isDeclaration())
3593 return;
3594
3595 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003596
3597 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003598 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003599
3600 // Switch any previous uses to the alias.
3601 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003602 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003603 "declaration exists with different type");
3604 Alias->takeName(Entry);
3605 Entry->replaceAllUsesWith(Alias);
3606 Entry->eraseFromParent();
3607 } else {
3608 Alias->setName(MangledName);
3609 }
3610
3611 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003612 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003613}
3614
3615void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3616 StructorType Type) {
3617 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3618 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3619
3620 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3621
3622 if (Type == StructorType::Complete) {
3623 GlobalDecl CompleteDecl;
3624 GlobalDecl BaseDecl;
3625 if (CD) {
3626 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3627 BaseDecl = GlobalDecl(CD, Ctor_Base);
3628 } else {
3629 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3630 BaseDecl = GlobalDecl(DD, Dtor_Base);
3631 }
3632
3633 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3634 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3635 return;
3636 }
3637
3638 if (CGType == StructorCodegen::RAUW) {
3639 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003640 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003641 CGM.addReplacement(MangledName, Aliasee);
3642 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003643 }
3644 }
3645
3646 // The base destructor is equivalent to the base destructor of its
3647 // base class if there is exactly one non-virtual base class with a
3648 // non-trivial destructor, there are no fields with a non-trivial
3649 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003650 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3651 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003652 return;
3653
Rafael Espindola1e4df922014-09-16 15:18:21 +00003654 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003655
Rafael Espindola1e4df922014-09-16 15:18:21 +00003656 if (CGType == StructorCodegen::COMDAT) {
3657 SmallString<256> Buffer;
3658 llvm::raw_svector_ostream Out(Buffer);
3659 if (DD)
3660 getMangleContext().mangleCXXDtorComdat(DD, Out);
3661 else
3662 getMangleContext().mangleCXXCtorComdat(CD, Out);
3663 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3664 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003665 } else {
3666 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003667 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003668}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003669
3670static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3671 // void *__cxa_begin_catch(void*);
3672 llvm::FunctionType *FTy = llvm::FunctionType::get(
3673 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3674
3675 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3676}
3677
3678static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3679 // void __cxa_end_catch();
3680 llvm::FunctionType *FTy =
3681 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3682
3683 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3684}
3685
3686static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3687 // void *__cxa_get_exception_ptr(void*);
3688 llvm::FunctionType *FTy = llvm::FunctionType::get(
3689 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3690
3691 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3692}
3693
3694namespace {
3695 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3696 /// exception type lets us state definitively that the thrown exception
3697 /// type does not have a destructor. In particular:
3698 /// - Catch-alls tell us nothing, so we have to conservatively
3699 /// assume that the thrown exception might have a destructor.
3700 /// - Catches by reference behave according to their base types.
3701 /// - Catches of non-record types will only trigger for exceptions
3702 /// of non-record types, which never have destructors.
3703 /// - Catches of record types can trigger for arbitrary subclasses
3704 /// of the caught type, so we have to assume the actual thrown
3705 /// exception type might have a throwing destructor, even if the
3706 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003707 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003708 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3709 bool MightThrow;
3710
3711 void Emit(CodeGenFunction &CGF, Flags flags) override {
3712 if (!MightThrow) {
3713 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3714 return;
3715 }
3716
3717 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3718 }
3719 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003720}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003721
3722/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3723/// __cxa_end_catch.
3724///
3725/// \param EndMightThrow - true if __cxa_end_catch might throw
3726static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3727 llvm::Value *Exn,
3728 bool EndMightThrow) {
3729 llvm::CallInst *call =
3730 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3731
3732 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3733
3734 return call;
3735}
3736
3737/// A "special initializer" callback for initializing a catch
3738/// parameter during catch initialization.
3739static void InitCatchParam(CodeGenFunction &CGF,
3740 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003741 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003742 SourceLocation Loc) {
3743 // Load the exception from where the landing pad saved it.
3744 llvm::Value *Exn = CGF.getExceptionFromSlot();
3745
3746 CanQualType CatchType =
3747 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3748 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3749
3750 // If we're catching by reference, we can just cast the object
3751 // pointer to the appropriate pointer.
3752 if (isa<ReferenceType>(CatchType)) {
3753 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3754 bool EndCatchMightThrow = CaughtType->isRecordType();
3755
3756 // __cxa_begin_catch returns the adjusted object pointer.
3757 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3758
3759 // We have no way to tell the personality function that we're
3760 // catching by reference, so if we're catching a pointer,
3761 // __cxa_begin_catch will actually return that pointer by value.
3762 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3763 QualType PointeeType = PT->getPointeeType();
3764
3765 // When catching by reference, generally we should just ignore
3766 // this by-value pointer and use the exception object instead.
3767 if (!PointeeType->isRecordType()) {
3768
3769 // Exn points to the struct _Unwind_Exception header, which
3770 // we have to skip past in order to reach the exception data.
3771 unsigned HeaderSize =
3772 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3773 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3774
3775 // However, if we're catching a pointer-to-record type that won't
3776 // work, because the personality function might have adjusted
3777 // the pointer. There's actually no way for us to fully satisfy
3778 // the language/ABI contract here: we can't use Exn because it
3779 // might have the wrong adjustment, but we can't use the by-value
3780 // pointer because it's off by a level of abstraction.
3781 //
3782 // The current solution is to dump the adjusted pointer into an
3783 // alloca, which breaks language semantics (because changing the
3784 // pointer doesn't change the exception) but at least works.
3785 // The better solution would be to filter out non-exact matches
3786 // and rethrow them, but this is tricky because the rethrow
3787 // really needs to be catchable by other sites at this landing
3788 // pad. The best solution is to fix the personality function.
3789 } else {
3790 // Pull the pointer for the reference type off.
3791 llvm::Type *PtrTy =
3792 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3793
3794 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003795 Address ExnPtrTmp =
3796 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003797 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3798 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3799
3800 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003801 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003802 }
3803 }
3804
3805 llvm::Value *ExnCast =
3806 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3807 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3808 return;
3809 }
3810
3811 // Scalars and complexes.
3812 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3813 if (TEK != TEK_Aggregate) {
3814 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3815
3816 // If the catch type is a pointer type, __cxa_begin_catch returns
3817 // the pointer by value.
3818 if (CatchType->hasPointerRepresentation()) {
3819 llvm::Value *CastExn =
3820 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3821
3822 switch (CatchType.getQualifiers().getObjCLifetime()) {
3823 case Qualifiers::OCL_Strong:
3824 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3825 // fallthrough
3826
3827 case Qualifiers::OCL_None:
3828 case Qualifiers::OCL_ExplicitNone:
3829 case Qualifiers::OCL_Autoreleasing:
3830 CGF.Builder.CreateStore(CastExn, ParamAddr);
3831 return;
3832
3833 case Qualifiers::OCL_Weak:
3834 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3835 return;
3836 }
3837 llvm_unreachable("bad ownership qualifier!");
3838 }
3839
3840 // Otherwise, it returns a pointer into the exception object.
3841
3842 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3843 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3844
3845 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003846 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003847 switch (TEK) {
3848 case TEK_Complex:
3849 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3850 /*init*/ true);
3851 return;
3852 case TEK_Scalar: {
3853 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3854 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3855 return;
3856 }
3857 case TEK_Aggregate:
3858 llvm_unreachable("evaluation kind filtered out!");
3859 }
3860 llvm_unreachable("bad evaluation kind");
3861 }
3862
3863 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003864 auto catchRD = CatchType->getAsCXXRecordDecl();
3865 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003866
3867 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3868
3869 // Check for a copy expression. If we don't have a copy expression,
3870 // that means a trivial copy is okay.
3871 const Expr *copyExpr = CatchParam.getInit();
3872 if (!copyExpr) {
3873 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003874 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3875 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003876 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3877 return;
3878 }
3879
3880 // We have to call __cxa_get_exception_ptr to get the adjusted
3881 // pointer before copying.
3882 llvm::CallInst *rawAdjustedExn =
3883 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3884
3885 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003886 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3887 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003888
3889 // The copy expression is defined in terms of an OpaqueValueExpr.
3890 // Find it and map it to the adjusted expression.
3891 CodeGenFunction::OpaqueValueMapping
3892 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3893 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3894
3895 // Call the copy ctor in a terminate scope.
3896 CGF.EHStack.pushTerminate();
3897
3898 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003899 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003900 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003901 AggValueSlot::IsNotDestructed,
3902 AggValueSlot::DoesNotNeedGCBarriers,
3903 AggValueSlot::IsNotAliased));
3904
3905 // Leave the terminate scope.
3906 CGF.EHStack.popTerminate();
3907
3908 // Undo the opaque value mapping.
3909 opaque.pop();
3910
3911 // Finally we can call __cxa_begin_catch.
3912 CallBeginCatch(CGF, Exn, true);
3913}
3914
3915/// Begins a catch statement by initializing the catch variable and
3916/// calling __cxa_begin_catch.
3917void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3918 const CXXCatchStmt *S) {
3919 // We have to be very careful with the ordering of cleanups here:
3920 // C++ [except.throw]p4:
3921 // The destruction [of the exception temporary] occurs
3922 // immediately after the destruction of the object declared in
3923 // the exception-declaration in the handler.
3924 //
3925 // So the precise ordering is:
3926 // 1. Construct catch variable.
3927 // 2. __cxa_begin_catch
3928 // 3. Enter __cxa_end_catch cleanup
3929 // 4. Enter dtor cleanup
3930 //
3931 // We do this by using a slightly abnormal initialization process.
3932 // Delegation sequence:
3933 // - ExitCXXTryStmt opens a RunCleanupsScope
3934 // - EmitAutoVarAlloca creates the variable and debug info
3935 // - InitCatchParam initializes the variable from the exception
3936 // - CallBeginCatch calls __cxa_begin_catch
3937 // - CallBeginCatch enters the __cxa_end_catch cleanup
3938 // - EmitAutoVarCleanups enters the variable destructor cleanup
3939 // - EmitCXXTryStmt emits the code for the catch body
3940 // - EmitCXXTryStmt close the RunCleanupsScope
3941
3942 VarDecl *CatchParam = S->getExceptionDecl();
3943 if (!CatchParam) {
3944 llvm::Value *Exn = CGF.getExceptionFromSlot();
3945 CallBeginCatch(CGF, Exn, true);
3946 return;
3947 }
3948
3949 // Emit the local.
3950 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3951 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3952 CGF.EmitAutoVarCleanups(var);
3953}
3954
3955/// Get or define the following function:
3956/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3957/// This code is used only in C++.
3958static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3959 llvm::FunctionType *fnTy =
3960 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00003961 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
3962 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003963
3964 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3965 if (fn && fn->empty()) {
3966 fn->setDoesNotThrow();
3967 fn->setDoesNotReturn();
3968
3969 // What we really want is to massively penalize inlining without
3970 // forbidding it completely. The difference between that and
3971 // 'noinline' is negligible.
3972 fn->addFnAttr(llvm::Attribute::NoInline);
3973
3974 // Allow this function to be shared across translation units, but
3975 // we don't want it to turn into an exported symbol.
3976 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3977 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003978 if (CGM.supportsCOMDAT())
3979 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003980
3981 // Set up the function.
3982 llvm::BasicBlock *entry =
3983 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003984 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003985
3986 // Pull the exception pointer out of the parameter list.
3987 llvm::Value *exn = &*fn->arg_begin();
3988
3989 // Call __cxa_begin_catch(exn).
3990 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3991 catchCall->setDoesNotThrow();
3992 catchCall->setCallingConv(CGM.getRuntimeCC());
3993
3994 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00003995 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003996 termCall->setDoesNotThrow();
3997 termCall->setDoesNotReturn();
3998 termCall->setCallingConv(CGM.getRuntimeCC());
3999
4000 // std::terminate cannot return.
4001 builder.CreateUnreachable();
4002 }
4003
4004 return fnRef;
4005}
4006
4007llvm::CallInst *
4008ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4009 llvm::Value *Exn) {
4010 // In C++, we want to call __cxa_begin_catch() before terminating.
4011 if (Exn) {
4012 assert(CGF.CGM.getLangOpts().CPlusPlus);
4013 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4014 }
4015 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4016}