blob: c1f892a3173344fc0478e132e58129c1860b00ed [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
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000160 /// Itanium says that an _Unwind_Exception has to be "double-word"
161 /// aligned (and thus the end of it is also so-aligned), meaning 16
162 /// bytes. Of course, that was written for the actual Itanium,
163 /// which is a 64-bit platform. Classically, the ABI doesn't really
164 /// specify the alignment on other platforms, but in practice
165 /// libUnwind declares the struct with __attribute__((aligned)), so
166 /// we assume that alignment here. (It's generally 16 bytes, but
167 /// some targets overwrite it.)
John McCall7f416cc2015-09-08 08:05:57 +0000168 CharUnits getAlignmentOfExnObject() {
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000169 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned();
170 return CGM.getContext().toCharUnitsFromBits(align);
John McCall7f416cc2015-09-08 08:05:57 +0000171 }
172
David Majnemer442d0a22014-11-25 07:20:20 +0000173 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000174 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000175
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000176 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
177
178 llvm::CallInst *
179 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
180 llvm::Value *Exn) override;
181
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000182 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
183 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000184 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000185 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000186 getAddrOfCXXCatchHandlerType(QualType Ty,
187 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000188 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000189 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000190
David Majnemer1162d252014-06-22 19:05:33 +0000191 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
192 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
193 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000194 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000195 llvm::Type *StdTypeInfoPtrTy) override;
196
197 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
198 QualType SrcRecordTy) override;
199
John McCall7f416cc2015-09-08 08:05:57 +0000200 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000201 QualType SrcRecordTy, QualType DestTy,
202 QualType DestRecordTy,
203 llvm::BasicBlock *CastEnd) override;
204
John McCall7f416cc2015-09-08 08:05:57 +0000205 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000206 QualType SrcRecordTy,
207 QualType DestTy) override;
208
209 bool EmitBadCastCall(CodeGenFunction &CGF) override;
210
Craig Topper4f12f102014-03-12 06:41:41 +0000211 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000212 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000213 const CXXRecordDecl *ClassDecl,
214 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000215
Craig Topper4f12f102014-03-12 06:41:41 +0000216 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000217
George Burgess IVf203dbf2017-02-22 20:28:02 +0000218 AddedStructorArgs
219 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
220 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000221
Reid Klecknere7de47e2013-07-22 13:51:44 +0000222 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000223 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000224 // Itanium does not emit any destructor variant as an inline thunk.
225 // Delegating may occur as an optimization, but all variants are either
226 // emitted with external linkage or as linkonce if they are inline and used.
227 return false;
228 }
229
Craig Topper4f12f102014-03-12 06:41:41 +0000230 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000231
Reid Kleckner89077a12013-12-17 19:46:40 +0000232 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000233 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000234
Craig Topper4f12f102014-03-12 06:41:41 +0000235 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000236
George Burgess IVf203dbf2017-02-22 20:28:02 +0000237 AddedStructorArgs
238 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
239 CXXCtorType Type, bool ForVirtualBase,
240 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000241
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000242 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
243 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000244 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000245
Craig Topper4f12f102014-03-12 06:41:41 +0000246 void emitVTableDefinitions(CodeGenVTables &CGVT,
247 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000248
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000249 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
250 CodeGenFunction::VPtr Vptr) override;
251
252 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
253 return true;
254 }
255
256 llvm::Constant *
257 getVTableAddressPoint(BaseSubobject Base,
258 const CXXRecordDecl *VTableClass) override;
259
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000260 llvm::Value *getVTableAddressPointInStructor(
261 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000262 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
263
264 llvm::Value *getVTableAddressPointInStructorWithVTT(
265 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
266 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000267
268 llvm::Constant *
269 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000270 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000271
272 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000273 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000274
John McCallb92ab1a2016-10-26 23:46:34 +0000275 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
276 Address This, llvm::Type *Ty,
277 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000278
David Majnemer0c0b6d92014-10-31 20:09:12 +0000279 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
280 const CXXDestructorDecl *Dtor,
281 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000282 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000283 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000284
Craig Topper4f12f102014-03-12 06:41:41 +0000285 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000286
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000287 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000288
Hans Wennborgc94391d2014-06-06 20:04:01 +0000289 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
290 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000291 // Allow inlining of thunks by emitting them with available_externally
292 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000293 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000294 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Shoaib Meenaicef66e52017-07-24 17:16:27 +0000295
296 // Propagate dllexport storage, to enable the linker to generate import
297 // thunks as necessary (e.g. when a parent class has a key function and a
298 // child class doesn't, and the construction vtable for the parent in the
299 // child needs to reference the parent's thunks).
300 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
301 if (MD->hasAttr<DLLExportAttr>())
302 Thunk->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000303 }
304
John McCall7f416cc2015-09-08 08:05:57 +0000305 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000306 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000307
John McCall7f416cc2015-09-08 08:05:57 +0000308 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000309 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000310
David Majnemer196ac332014-09-11 23:05:02 +0000311 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
312 FunctionArgList &Args) const override {
313 assert(!Args.empty() && "expected the arglist to not be empty!");
314 return Args.size() - 1;
315 }
316
Craig Topper4f12f102014-03-12 06:41:41 +0000317 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
318 StringRef GetDeletedVirtualCallName() override
319 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000320
Craig Topper4f12f102014-03-12 06:41:41 +0000321 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000322 Address InitializeArrayCookie(CodeGenFunction &CGF,
323 Address NewPtr,
324 llvm::Value *NumElements,
325 const CXXNewExpr *expr,
326 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000327 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000328 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000329 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000330
John McCallcdf7ef52010-11-06 09:44:32 +0000331 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000332 llvm::GlobalVariable *DeclPtr,
333 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000334 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000335 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000336
337 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000338 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000339 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000340 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000341 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000342 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000343 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000344
345 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000346 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
347 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000348
Craig Topper4f12f102014-03-12 06:41:41 +0000349 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000350
351 /**************************** RTTI Uniqueness ******************************/
352
353protected:
354 /// Returns true if the ABI requires RTTI type_info objects to be unique
355 /// across a program.
356 virtual bool shouldRTTIBeUnique() const { return true; }
357
358public:
359 /// What sort of unique-RTTI behavior should we use?
360 enum RTTIUniquenessKind {
361 /// We are guaranteeing, or need to guarantee, that the RTTI string
362 /// is unique.
363 RUK_Unique,
364
365 /// We are not guaranteeing uniqueness for the RTTI string, so we
366 /// can demote to hidden visibility but must use string comparisons.
367 RUK_NonUniqueHidden,
368
369 /// We are not guaranteeing uniqueness for the RTTI string, so we
370 /// have to use string comparisons, but we also have to emit it with
371 /// non-hidden visibility.
372 RUK_NonUniqueVisible
373 };
374
375 /// Return the required visibility status for the given type and linkage in
376 /// the current ABI.
377 RTTIUniquenessKind
378 classifyRTTIUniqueness(QualType CanTy,
379 llvm::GlobalValue::LinkageTypes Linkage) const;
380 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000381
382 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000383
384 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000385 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
386 const auto &VtableLayout =
387 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000388
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000389 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
390 // Skip empty slot.
391 if (!VtableComponent.isUsedFunctionPointerKind())
392 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000393
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000394 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
395 if (!Method->getCanonicalDecl()->isInlined())
396 continue;
397
398 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
399 auto *Entry = CGM.GetGlobalValue(Name);
400 // This checks if virtual inline function has already been emitted.
401 // Note that it is possible that this inline function would be emitted
402 // after trying to emit vtable speculatively. Because of this we do
403 // an extra pass after emitting all deferred vtables to find and emit
404 // these vtables opportunistically.
405 if (!Entry || Entry->isDeclaration())
406 return true;
407 }
408 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000409 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000410
411 bool isVTableHidden(const CXXRecordDecl *RD) const {
412 const auto &VtableLayout =
413 CGM.getItaniumVTableContext().getVTableLayout(RD);
414
415 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
416 if (VtableComponent.isRTTIKind()) {
417 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
418 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
419 return true;
420 } else if (VtableComponent.isUsedFunctionPointerKind()) {
421 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
422 if (Method->getVisibility() == Visibility::HiddenVisibility &&
423 !Method->isDefined())
424 return true;
425 }
426 }
427 return false;
428 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000429};
John McCall86353412010-08-21 22:46:04 +0000430
431class ARMCXXABI : public ItaniumCXXABI {
432public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000433 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
434 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
435 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000436
Craig Topper4f12f102014-03-12 06:41:41 +0000437 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000438 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
439 isa<CXXDestructorDecl>(GD.getDecl()) &&
440 GD.getDtorType() != Dtor_Deleting));
441 }
John McCall5d865c322010-08-31 07:33:07 +0000442
Craig Topper4f12f102014-03-12 06:41:41 +0000443 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
444 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000445
Craig Topper4f12f102014-03-12 06:41:41 +0000446 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000447 Address InitializeArrayCookie(CodeGenFunction &CGF,
448 Address NewPtr,
449 llvm::Value *NumElements,
450 const CXXNewExpr *expr,
451 QualType ElementType) override;
452 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000453 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000454};
Tim Northovera2ee4332014-03-29 15:09:45 +0000455
456class iOS64CXXABI : public ARMCXXABI {
457public:
John McCalld23b27e2016-09-16 02:40:45 +0000458 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
459 Use32BitVTableOffsetABI = true;
460 }
Tim Northover65f582f2014-03-30 17:32:48 +0000461
462 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000463 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000464};
Dan Gohmanc2853072015-09-03 22:51:53 +0000465
466class WebAssemblyCXXABI final : public ItaniumCXXABI {
467public:
468 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
469 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
470 /*UseARMGuardVarABI=*/true) {}
471
472private:
473 bool HasThisReturn(GlobalDecl GD) const override {
474 return isa<CXXConstructorDecl>(GD.getDecl()) ||
475 (isa<CXXDestructorDecl>(GD.getDecl()) &&
476 GD.getDtorType() != Dtor_Deleting);
477 }
Derek Schuff8179be42016-05-10 17:44:55 +0000478 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000479};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000480}
Charles Davis4e786dd2010-05-25 19:52:27 +0000481
Charles Davis53c59df2010-08-16 03:33:14 +0000482CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000483 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000484 // For IR-generation purposes, there's no significant difference
485 // between the ARM and iOS ABIs.
486 case TargetCXXABI::GenericARM:
487 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000488 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000489 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000490
Tim Northovera2ee4332014-03-29 15:09:45 +0000491 case TargetCXXABI::iOS64:
492 return new iOS64CXXABI(CGM);
493
Tim Northover9bb857a2013-01-31 12:13:10 +0000494 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
495 // include the other 32-bit ARM oddities: constructor/destructor return values
496 // and array cookies.
497 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000498 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
499 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000500
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000501 case TargetCXXABI::GenericMIPS:
502 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
503
Dan Gohmanc2853072015-09-03 22:51:53 +0000504 case TargetCXXABI::WebAssembly:
505 return new WebAssemblyCXXABI(CGM);
506
John McCall57625922013-01-25 23:36:14 +0000507 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000508 if (CGM.getContext().getTargetInfo().getTriple().getArch()
509 == llvm::Triple::le32) {
510 // For PNaCl, use ARM-style method pointers so that PNaCl code
511 // does not assume anything about the alignment of function
512 // pointers.
513 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
514 /* UseARMGuardVarABI = */ false);
515 }
John McCall57625922013-01-25 23:36:14 +0000516 return new ItaniumCXXABI(CGM);
517
518 case TargetCXXABI::Microsoft:
519 llvm_unreachable("Microsoft ABI is not Itanium-based");
520 }
521 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000522}
523
Chris Lattnera5f58b02011-07-09 17:41:47 +0000524llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000525ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
526 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000527 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000528 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000529}
530
John McCalld9c6c0b2010-08-22 00:59:17 +0000531/// In the Itanium and ARM ABIs, method pointers have the form:
532/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
533///
534/// In the Itanium ABI:
535/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
536/// - the this-adjustment is (memptr.adj)
537/// - the virtual offset is (memptr.ptr - 1)
538///
539/// In the ARM ABI:
540/// - method pointers are virtual if (memptr.adj & 1) is nonzero
541/// - the this-adjustment is (memptr.adj >> 1)
542/// - the virtual offset is (memptr.ptr)
543/// ARM uses 'adj' for the virtual flag because Thumb functions
544/// may be only single-byte aligned.
545///
546/// If the member is virtual, the adjusted 'this' pointer points
547/// to a vtable pointer from which the virtual offset is applied.
548///
549/// If the member is non-virtual, memptr.ptr is the address of
550/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000551CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000552 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
553 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000554 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000555 CGBuilderTy &Builder = CGF.Builder;
556
557 const FunctionProtoType *FPT =
558 MPT->getPointeeType()->getAs<FunctionProtoType>();
559 const CXXRecordDecl *RD =
560 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
561
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000562 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
563 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000564
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000565 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000566
John McCalld9c6c0b2010-08-22 00:59:17 +0000567 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
568 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
569 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
570
John McCalla1dee5302010-08-22 10:59:02 +0000571 // Extract memptr.adj, which is in the second field.
572 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000573
574 // Compute the true adjustment.
575 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000576 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000577 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000578
579 // Apply the adjustment and cast back to the original struct type
580 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000581 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000582 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
583 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
584 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000585 ThisPtrForCall = This;
John McCall475999d2010-08-22 00:05:51 +0000586
587 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000588 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
John McCall475999d2010-08-22 00:05:51 +0000589
590 // If the LSB in the function pointer is 1, the function pointer points to
591 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000592 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000593 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000594 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
595 else
596 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
597 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000598 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
599
600 // In the virtual path, the adjustment left 'This' pointing to the
601 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000602 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000603 CGF.EmitBlock(FnVirtual);
604
605 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000606 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000607 CharUnits VTablePtrAlign =
608 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
609 CGF.getPointerAlign());
610 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000611 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000612
613 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000614 // On ARM64, to reserve extra space in virtual member function pointers,
615 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000616 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000617 if (!UseARMMethodPtrABI)
618 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000619 if (Use32BitVTableOffsetABI) {
620 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
621 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
622 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000623 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000624
625 // Load the virtual function to call.
626 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000627 llvm::Value *VirtualFn =
628 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
629 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000630 CGF.EmitBranch(FnEnd);
631
632 // In the non-virtual path, the function pointer is actually a
633 // function pointer.
634 CGF.EmitBlock(FnNonVirtual);
635 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000636 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
John McCall475999d2010-08-22 00:05:51 +0000637
638 // We're done.
639 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000640 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
641 CalleePtr->addIncoming(VirtualFn, FnVirtual);
642 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
643
644 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000645 return Callee;
646}
John McCalla8bbb822010-08-22 03:04:22 +0000647
John McCallc134eb52010-08-31 21:07:20 +0000648/// Compute an l-value by applying the given pointer-to-member to a
649/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000650llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000651 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000652 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000653 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000654
655 CGBuilderTy &Builder = CGF.Builder;
656
John McCallc134eb52010-08-31 21:07:20 +0000657 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000658 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000659
660 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000661 llvm::Value *Addr =
662 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000663
664 // Cast the address to the appropriate pointer type, adopting the
665 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000666 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
667 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000668 return Builder.CreateBitCast(Addr, PType);
669}
670
John McCallc62bb392012-02-15 01:22:51 +0000671/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
672/// conversion.
673///
674/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000675///
676/// Obligatory offset/adjustment diagram:
677/// <-- offset --> <-- adjustment -->
678/// |--------------------------|----------------------|--------------------|
679/// ^Derived address point ^Base address point ^Member address point
680///
681/// So when converting a base member pointer to a derived member pointer,
682/// we add the offset to the adjustment because the address point has
683/// decreased; and conversely, when converting a derived MP to a base MP
684/// we subtract the offset from the adjustment because the address point
685/// has increased.
686///
687/// The standard forbids (at compile time) conversion to and from
688/// virtual bases, which is why we don't have to consider them here.
689///
690/// The standard forbids (at run time) casting a derived MP to a base
691/// MP when the derived MP does not point to a member of the base.
692/// This is why -1 is a reasonable choice for null data member
693/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000694llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000695ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
696 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000697 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000698 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000699 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
700 E->getCastKind() == CK_ReinterpretMemberPointer);
701
702 // Under Itanium, reinterprets don't require any additional processing.
703 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
704
705 // Use constant emission if we can.
706 if (isa<llvm::Constant>(src))
707 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
708
709 llvm::Constant *adj = getMemberPointerAdjustment(E);
710 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000711
712 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000713 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000714
John McCallc62bb392012-02-15 01:22:51 +0000715 const MemberPointerType *destTy =
716 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000717
John McCall7a9aac22010-08-23 01:21:21 +0000718 // For member data pointers, this is just a matter of adding the
719 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000720 if (destTy->isMemberDataPointer()) {
721 llvm::Value *dst;
722 if (isDerivedToBase)
723 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000724 else
John McCallc62bb392012-02-15 01:22:51 +0000725 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000726
727 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000728 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
729 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
730 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000731 }
732
John McCalla1dee5302010-08-22 10:59:02 +0000733 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000734 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000735 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
736 offset <<= 1;
737 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000738 }
739
John McCallc62bb392012-02-15 01:22:51 +0000740 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
741 llvm::Value *dstAdj;
742 if (isDerivedToBase)
743 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000744 else
John McCallc62bb392012-02-15 01:22:51 +0000745 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000746
John McCallc62bb392012-02-15 01:22:51 +0000747 return Builder.CreateInsertValue(src, dstAdj, 1);
748}
749
750llvm::Constant *
751ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
752 llvm::Constant *src) {
753 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
754 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
755 E->getCastKind() == CK_ReinterpretMemberPointer);
756
757 // Under Itanium, reinterprets don't require any additional processing.
758 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
759
760 // If the adjustment is trivial, we don't need to do anything.
761 llvm::Constant *adj = getMemberPointerAdjustment(E);
762 if (!adj) return src;
763
764 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
765
766 const MemberPointerType *destTy =
767 E->getType()->castAs<MemberPointerType>();
768
769 // For member data pointers, this is just a matter of adding the
770 // offset if the source is non-null.
771 if (destTy->isMemberDataPointer()) {
772 // null maps to null.
773 if (src->isAllOnesValue()) return src;
774
775 if (isDerivedToBase)
776 return llvm::ConstantExpr::getNSWSub(src, adj);
777 else
778 return llvm::ConstantExpr::getNSWAdd(src, adj);
779 }
780
781 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000782 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000783 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
784 offset <<= 1;
785 adj = llvm::ConstantInt::get(adj->getType(), offset);
786 }
787
788 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
789 llvm::Constant *dstAdj;
790 if (isDerivedToBase)
791 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
792 else
793 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
794
795 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000796}
John McCall84fa5102010-08-22 04:16:24 +0000797
798llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000799ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000800 // Itanium C++ ABI 2.3:
801 // A NULL pointer is represented as -1.
802 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000803 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000804
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000805 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000806 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000807 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000808}
809
John McCallf3a88602011-02-03 08:15:49 +0000810llvm::Constant *
811ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
812 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000813 // Itanium C++ ABI 2.3:
814 // A pointer to data member is an offset from the base address of
815 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000816 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000817}
818
David Majnemere2be95b2015-06-23 07:31:01 +0000819llvm::Constant *
820ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000821 return BuildMemberPointer(MD, CharUnits::Zero());
822}
823
824llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
825 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000826 assert(MD->isInstance() && "Member function must not be static!");
827 MD = MD->getCanonicalDecl();
828
829 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000830
831 // Get the function pointer (or index if this is a virtual function).
832 llvm::Constant *MemPtr[2];
833 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000834 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000835
Ken Dyckdf016282011-04-09 01:30:02 +0000836 const ASTContext &Context = getContext();
837 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000838 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000839 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000840
Mark Seabornedf0d382013-07-24 16:25:13 +0000841 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000842 // ARM C++ ABI 3.2.1:
843 // This ABI specifies that adj contains twice the this
844 // adjustment, plus 1 if the member function is virtual. The
845 // least significant bit of adj then makes exactly the same
846 // discrimination as the least significant bit of ptr does for
847 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000848 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
849 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000850 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000851 } else {
852 // Itanium C++ ABI 2.3:
853 // For a virtual function, [the pointer field] is 1 plus the
854 // virtual table offset (in bytes) of the function,
855 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000856 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
857 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000858 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000859 }
860 } else {
John McCall2979fe02011-04-12 00:42:48 +0000861 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000862 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000863 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000864 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000865 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000866 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000867 } else {
John McCall2979fe02011-04-12 00:42:48 +0000868 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
869 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000870 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000871 }
John McCall2979fe02011-04-12 00:42:48 +0000872 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000873
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000874 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000875 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
876 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000877 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000878 }
John McCall1c456c82010-08-22 06:43:33 +0000879
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000880 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000881}
882
Richard Smithdafff942012-01-14 04:30:29 +0000883llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
884 QualType MPType) {
885 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
886 const ValueDecl *MPD = MP.getMemberPointerDecl();
887 if (!MPD)
888 return EmitNullMemberPointer(MPT);
889
Reid Kleckner452abac2013-05-09 21:01:17 +0000890 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000891
892 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
893 return BuildMemberPointer(MD, ThisAdjustment);
894
895 CharUnits FieldOffset =
896 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
897 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
898}
899
John McCall131d97d2010-08-22 08:30:07 +0000900/// The comparison algorithm is pretty easy: the member pointers are
901/// the same if they're either bitwise identical *or* both null.
902///
903/// ARM is different here only because null-ness is more complicated.
904llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000905ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
906 llvm::Value *L,
907 llvm::Value *R,
908 const MemberPointerType *MPT,
909 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000910 CGBuilderTy &Builder = CGF.Builder;
911
John McCall131d97d2010-08-22 08:30:07 +0000912 llvm::ICmpInst::Predicate Eq;
913 llvm::Instruction::BinaryOps And, Or;
914 if (Inequality) {
915 Eq = llvm::ICmpInst::ICMP_NE;
916 And = llvm::Instruction::Or;
917 Or = llvm::Instruction::And;
918 } else {
919 Eq = llvm::ICmpInst::ICMP_EQ;
920 And = llvm::Instruction::And;
921 Or = llvm::Instruction::Or;
922 }
923
John McCall7a9aac22010-08-23 01:21:21 +0000924 // Member data pointers are easy because there's a unique null
925 // value, so it just comes down to bitwise equality.
926 if (MPT->isMemberDataPointer())
927 return Builder.CreateICmp(Eq, L, R);
928
929 // For member function pointers, the tautologies are more complex.
930 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000931 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000932 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000933 // (L == R) <==> (L.ptr == R.ptr &&
934 // (L.adj == R.adj ||
935 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000936 // The inequality tautologies have exactly the same structure, except
937 // applying De Morgan's laws.
938
939 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
940 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
941
John McCall131d97d2010-08-22 08:30:07 +0000942 // This condition tests whether L.ptr == R.ptr. This must always be
943 // true for equality to hold.
944 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
945
946 // This condition, together with the assumption that L.ptr == R.ptr,
947 // tests whether the pointers are both null. ARM imposes an extra
948 // condition.
949 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
950 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
951
952 // This condition tests whether L.adj == R.adj. If this isn't
953 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000954 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
955 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000956 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
957
958 // Null member function pointers on ARM clear the low bit of Adj,
959 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000960 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000961 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
962
963 // Compute (l.adj | r.adj) & 1 and test it against zero.
964 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
965 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
966 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
967 "cmp.or.adj");
968 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
969 }
970
971 // Tie together all our conditions.
972 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
973 Result = Builder.CreateBinOp(And, PtrEq, Result,
974 Inequality ? "memptr.ne" : "memptr.eq");
975 return Result;
976}
977
978llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000979ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
980 llvm::Value *MemPtr,
981 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000982 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000983
984 /// For member data pointers, this is just a check against -1.
985 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000986 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000987 llvm::Value *NegativeOne =
988 llvm::Constant::getAllOnesValue(MemPtr->getType());
989 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
990 }
John McCall131d97d2010-08-22 08:30:07 +0000991
Daniel Dunbar914bc412011-04-19 23:10:47 +0000992 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000993 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000994
995 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
996 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
997
Daniel Dunbar914bc412011-04-19 23:10:47 +0000998 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
999 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001000 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001001 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001002 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001003 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001004 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1005 "memptr.isvirtual");
1006 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001007 }
1008
1009 return Result;
1010}
John McCall1c456c82010-08-22 06:43:33 +00001011
Reid Kleckner40ca9132014-05-13 22:05:45 +00001012bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1013 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1014 if (!RD)
1015 return false;
1016
Reid Klecknerd355ca72014-05-15 01:26:32 +00001017 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
1018 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
1019 // special members.
1020 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
John McCall7f416cc2015-09-08 08:05:57 +00001021 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1022 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001023 return true;
1024 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001025 return false;
1026}
1027
John McCall614dbdc2010-08-22 21:01:12 +00001028/// The Itanium ABI requires non-zero initialization only for data
1029/// member pointers, for which '0' is a valid offset.
1030bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001031 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001032}
John McCall5d865c322010-08-31 07:33:07 +00001033
John McCall82fb8922012-09-25 10:10:39 +00001034/// The Itanium ABI always places an offset to the complete object
1035/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001036void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1037 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001038 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001039 QualType ElementType,
1040 const CXXDestructorDecl *Dtor) {
1041 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001042 if (UseGlobalDelete) {
1043 // Derive the complete-object pointer, which is what we need
1044 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001045
David Majnemer0c0b6d92014-10-31 20:09:12 +00001046 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001047 auto *ClassDecl =
1048 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1049 llvm::Value *VTable =
1050 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001051
David Majnemer0c0b6d92014-10-31 20:09:12 +00001052 // Track back to entry -2 and pull out the offset there.
1053 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1054 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001055 llvm::Value *Offset =
1056 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001057
1058 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001059 llvm::Value *CompletePtr =
1060 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001061 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1062
1063 // If we're supposed to call the global delete, make sure we do so
1064 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001065 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1066 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001067 }
1068
1069 // FIXME: Provide a source location here even though there's no
1070 // CXXMemberCallExpr for dtor call.
1071 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1072 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1073
1074 if (UseGlobalDelete)
1075 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001076}
1077
David Majnemer442d0a22014-11-25 07:20:20 +00001078void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1079 // void __cxa_rethrow();
1080
1081 llvm::FunctionType *FTy =
1082 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1083
1084 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1085
1086 if (isNoReturn)
1087 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1088 else
1089 CGF.EmitRuntimeCallOrInvoke(Fn);
1090}
1091
David Majnemer7c237072015-03-05 00:46:22 +00001092static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1093 // void *__cxa_allocate_exception(size_t thrown_size);
1094
1095 llvm::FunctionType *FTy =
1096 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1097
1098 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1099}
1100
1101static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1102 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1103 // void (*dest) (void *));
1104
1105 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1106 llvm::FunctionType *FTy =
1107 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1108
1109 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1110}
1111
1112void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1113 QualType ThrowType = E->getSubExpr()->getType();
1114 // Now allocate the exception object.
1115 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1116 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1117
1118 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1119 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1120 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1121
John McCall7f416cc2015-09-08 08:05:57 +00001122 CharUnits ExnAlign = getAlignmentOfExnObject();
1123 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001124
1125 // Now throw the exception.
1126 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1127 /*ForEH=*/true);
1128
1129 // The address of the destructor. If the exception type has a
1130 // trivial destructor (or isn't a record), we just pass null.
1131 llvm::Constant *Dtor = nullptr;
1132 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1133 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1134 if (!Record->hasTrivialDestructor()) {
1135 CXXDestructorDecl *DtorD = Record->getDestructor();
1136 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1137 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1138 }
1139 }
1140 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1141
1142 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1143 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1144}
1145
David Majnemer1162d252014-06-22 19:05:33 +00001146static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1147 // void *__dynamic_cast(const void *sub,
1148 // const abi::__class_type_info *src,
1149 // const abi::__class_type_info *dst,
1150 // std::ptrdiff_t src2dst_offset);
1151
1152 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1153 llvm::Type *PtrDiffTy =
1154 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1155
1156 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1157
1158 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1159
1160 // Mark the function as nounwind readonly.
1161 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1162 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001163 llvm::AttributeList Attrs = llvm::AttributeList::get(
1164 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001165
1166 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1167}
1168
1169static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1170 // void __cxa_bad_cast();
1171 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1172 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1173}
1174
1175/// \brief Compute the src2dst_offset hint as described in the
1176/// Itanium C++ ABI [2.9.7]
1177static CharUnits computeOffsetHint(ASTContext &Context,
1178 const CXXRecordDecl *Src,
1179 const CXXRecordDecl *Dst) {
1180 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1181 /*DetectVirtual=*/false);
1182
1183 // If Dst is not derived from Src we can skip the whole computation below and
1184 // return that Src is not a public base of Dst. Record all inheritance paths.
1185 if (!Dst->isDerivedFrom(Src, Paths))
1186 return CharUnits::fromQuantity(-2ULL);
1187
1188 unsigned NumPublicPaths = 0;
1189 CharUnits Offset;
1190
1191 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001192 for (const CXXBasePath &Path : Paths) {
1193 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001194 continue;
1195
1196 ++NumPublicPaths;
1197
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001198 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001199 // If the path contains a virtual base class we can't give any hint.
1200 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001201 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001202 return CharUnits::fromQuantity(-1ULL);
1203
1204 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1205 continue;
1206
1207 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001208 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1209 Offset += L.getBaseClassOffset(
1210 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001211 }
1212 }
1213
1214 // -2: Src is not a public base of Dst.
1215 if (NumPublicPaths == 0)
1216 return CharUnits::fromQuantity(-2ULL);
1217
1218 // -3: Src is a multiple public base type but never a virtual base type.
1219 if (NumPublicPaths > 1)
1220 return CharUnits::fromQuantity(-3ULL);
1221
1222 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1223 // Return the offset of Src from the origin of Dst.
1224 return Offset;
1225}
1226
1227static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1228 // void __cxa_bad_typeid();
1229 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1230
1231 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1232}
1233
1234bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1235 QualType SrcRecordTy) {
1236 return IsDeref;
1237}
1238
1239void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1240 llvm::Value *Fn = getBadTypeidFn(CGF);
1241 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1242 CGF.Builder.CreateUnreachable();
1243}
1244
1245llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1246 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001247 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001248 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001249 auto *ClassDecl =
1250 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001251 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001252 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001253
1254 // Load the type info.
1255 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001256 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001257}
1258
1259bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1260 QualType SrcRecordTy) {
1261 return SrcIsPtr;
1262}
1263
1264llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001265 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001266 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1267 llvm::Type *PtrDiffLTy =
1268 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1269 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1270
1271 llvm::Value *SrcRTTI =
1272 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1273 llvm::Value *DestRTTI =
1274 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1275
1276 // Compute the offset hint.
1277 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1278 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1279 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1280 PtrDiffLTy,
1281 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1282
1283 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001284 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001285 Value = CGF.EmitCastToVoidPtr(Value);
1286
1287 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1288 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1289 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1290
1291 /// C++ [expr.dynamic.cast]p9:
1292 /// A failed cast to reference type throws std::bad_cast
1293 if (DestTy->isReferenceType()) {
1294 llvm::BasicBlock *BadCastBlock =
1295 CGF.createBasicBlock("dynamic_cast.bad_cast");
1296
1297 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1298 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1299
1300 CGF.EmitBlock(BadCastBlock);
1301 EmitBadCastCall(CGF);
1302 }
1303
1304 return Value;
1305}
1306
1307llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001308 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001309 QualType SrcRecordTy,
1310 QualType DestTy) {
1311 llvm::Type *PtrDiffLTy =
1312 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1313 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1314
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001315 auto *ClassDecl =
1316 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001317 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001318 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1319 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001320
1321 // Get the offset-to-top from the vtable.
1322 llvm::Value *OffsetToTop =
1323 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001324 OffsetToTop =
1325 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1326 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001327
1328 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001329 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001330 Value = CGF.EmitCastToVoidPtr(Value);
1331 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1332
1333 return CGF.Builder.CreateBitCast(Value, DestLTy);
1334}
1335
1336bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1337 llvm::Value *Fn = getBadCastFn(CGF);
1338 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1339 CGF.Builder.CreateUnreachable();
1340 return true;
1341}
1342
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001343llvm::Value *
1344ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001345 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001346 const CXXRecordDecl *ClassDecl,
1347 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001348 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001349 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001350 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1351 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001352
1353 llvm::Value *VBaseOffsetPtr =
1354 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1355 "vbase.offset.ptr");
1356 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1357 CGM.PtrDiffTy->getPointerTo());
1358
1359 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001360 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1361 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001362
1363 return VBaseOffset;
1364}
1365
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001366void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1367 // Just make sure we're in sync with TargetCXXABI.
1368 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1369
Rafael Espindolac3cde362013-12-09 14:51:17 +00001370 // The constructor used for constructing this as a base class;
1371 // ignores virtual bases.
1372 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1373
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001374 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001375 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001376 if (!D->getParent()->isAbstract()) {
1377 // We don't need to emit the complete ctor if the class is abstract.
1378 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1379 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001380}
1381
George Burgess IVf203dbf2017-02-22 20:28:02 +00001382CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001383ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1384 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001385 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001386
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001387 // All parameters are already in place except VTT, which goes after 'this'.
1388 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001389
1390 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001391 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001392 ArgTys.insert(ArgTys.begin() + 1,
1393 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001394 return AddedStructorArgs::prefix(1);
1395 }
1396 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001397}
1398
Reid Klecknere7de47e2013-07-22 13:51:44 +00001399void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001400 // The destructor used for destructing this as a base class; ignores
1401 // virtual bases.
1402 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001403
1404 // The destructor used for destructing this as a most-derived class;
1405 // call the base destructor and then destructs any virtual bases.
1406 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1407
Rafael Espindolac3cde362013-12-09 14:51:17 +00001408 // The destructor in a virtual table is always a 'deleting'
1409 // destructor, which calls the complete destructor and then uses the
1410 // appropriate operator delete.
1411 if (D->isVirtual())
1412 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001413}
1414
Reid Kleckner89077a12013-12-17 19:46:40 +00001415void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1416 QualType &ResTy,
1417 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001418 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001419 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001420
1421 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001422 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001423 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001424
1425 // FIXME: avoid the fake decl
1426 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001427 auto *VTTDecl = ImplicitParamDecl::Create(
1428 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1429 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001430 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001431 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001432 }
1433}
1434
John McCall5d865c322010-08-31 07:33:07 +00001435void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001436 // Naked functions have no prolog.
1437 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1438 return;
1439
John McCall5d865c322010-08-31 07:33:07 +00001440 /// Initialize the 'this' slot.
1441 EmitThisParam(CGF);
1442
1443 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001444 if (getStructorImplicitParamDecl(CGF)) {
1445 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1446 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001447 }
John McCall5d865c322010-08-31 07:33:07 +00001448
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001449 /// If this is a function that the ABI specifies returns 'this', initialize
1450 /// the return slot to 'this' at the start of the function.
1451 ///
1452 /// Unlike the setting of return types, this is done within the ABI
1453 /// implementation instead of by clients of CGCXXABI because:
1454 /// 1) getThisValue is currently protected
1455 /// 2) in theory, an ABI could implement 'this' returns some other way;
1456 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001457 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001458 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001459}
1460
George Burgess IVf203dbf2017-02-22 20:28:02 +00001461CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001462 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1463 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1464 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001465 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001466
Reid Kleckner89077a12013-12-17 19:46:40 +00001467 // Insert the implicit 'vtt' argument as the second argument.
1468 llvm::Value *VTT =
1469 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1470 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1471 Args.insert(Args.begin() + 1,
1472 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001473 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001474}
1475
1476void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1477 const CXXDestructorDecl *DD,
1478 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001479 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001480 GlobalDecl GD(DD, Type);
1481 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1482 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1483
John McCallb92ab1a2016-10-26 23:46:34 +00001484 CGCallee Callee;
1485 if (getContext().getLangOpts().AppleKext &&
1486 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001487 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001488 else
1489 Callee =
1490 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1491 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001492
John McCall7f416cc2015-09-08 08:05:57 +00001493 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001494 This.getPointer(), VTT, VTTTy,
1495 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001496}
1497
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001498void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1499 const CXXRecordDecl *RD) {
1500 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1501 if (VTable->hasInitializer())
1502 return;
1503
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001504 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001505 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1506 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001507 llvm::Constant *RTTI =
1508 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001509
1510 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001511 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001512 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001513 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1514 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001515
1516 // Set the correct linkage.
1517 VTable->setLinkage(Linkage);
1518
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001519 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1520 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001521
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001522 // Set the right visibility.
John McCall8f80a612014-02-08 00:41:16 +00001523 CGM.setGlobalVisibility(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001524
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001525 // Use pointer alignment for the vtable. Otherwise we would align them based
1526 // on the size of the initializer which doesn't make sense as only single
1527 // values are read.
1528 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1529 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1530
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001531 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1532 // we will emit the typeinfo for the fundamental types. This is the
1533 // same behaviour as GCC.
1534 const DeclContext *DC = RD->getDeclContext();
1535 if (RD->getIdentifier() &&
1536 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1537 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1538 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1539 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001540 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001541
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001542 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001543 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001544}
1545
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001546bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1547 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1548 if (Vptr.NearestVBase == nullptr)
1549 return false;
1550 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001551}
1552
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001553llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1554 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1555 const CXXRecordDecl *NearestVBase) {
1556
1557 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1558 NeedsVTTParameter(CGF.CurGD)) {
1559 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1560 NearestVBase);
1561 }
1562 return getVTableAddressPoint(Base, VTableClass);
1563}
1564
1565llvm::Constant *
1566ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1567 const CXXRecordDecl *VTableClass) {
1568 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001569
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001570 // Find the appropriate vtable within the vtable group, and the address point
1571 // within that vtable.
1572 VTableLayout::AddressPointLocation AddressPoint =
1573 CGM.getItaniumVTableContext()
1574 .getVTableLayout(VTableClass)
1575 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001576 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001577 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001578 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1579 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001580 };
1581
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001582 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1583 Indices, /*InBounds=*/true,
1584 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001585}
1586
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001587llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1588 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1589 const CXXRecordDecl *NearestVBase) {
1590 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1591 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1592
1593 // Get the secondary vpointer index.
1594 uint64_t VirtualPointerIndex =
1595 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1596
1597 /// Load the VTT.
1598 llvm::Value *VTT = CGF.LoadCXXVTT();
1599 if (VirtualPointerIndex)
1600 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1601
1602 // And load the address point from the VTT.
1603 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1604}
1605
1606llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1607 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1608 return getVTableAddressPoint(Base, VTableClass);
1609}
1610
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001611llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1612 CharUnits VPtrOffset) {
1613 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1614
1615 llvm::GlobalVariable *&VTable = VTables[RD];
1616 if (VTable)
1617 return VTable;
1618
Eric Christopherd160c502016-01-29 01:35:53 +00001619 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001620 CGM.addDeferredVTable(RD);
1621
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001622 SmallString<256> Name;
1623 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001624 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001625
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001626 const VTableLayout &VTLayout =
1627 CGM.getItaniumVTableContext().getVTableLayout(RD);
1628 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001629
1630 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001631 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001632 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001633
1634 if (RD->hasAttr<DLLImportAttr>())
1635 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1636 else if (RD->hasAttr<DLLExportAttr>())
1637 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1638
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001639 return VTable;
1640}
1641
John McCallb92ab1a2016-10-26 23:46:34 +00001642CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1643 GlobalDecl GD,
1644 Address This,
1645 llvm::Type *Ty,
1646 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001647 GD = GD.getCanonicalDecl();
1648 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001649 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1650 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001651
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001652 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCallb92ab1a2016-10-26 23:46:34 +00001653 llvm::Value *VFunc;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001654 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
John McCallb92ab1a2016-10-26 23:46:34 +00001655 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001656 MethodDecl->getParent(), VTable,
1657 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1658 } else {
1659 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1660
1661 llvm::Value *VFuncPtr =
1662 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001663 auto *VFuncLoad =
1664 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1665
1666 // Add !invariant.load md to virtual function load to indicate that
1667 // function didn't change inside vtable.
1668 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1669 // help in devirtualization because it will only matter if we will have 2
1670 // the same virtual function loads from the same vtable load, which won't
1671 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1672 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1673 CGM.getCodeGenOpts().StrictVTablePointers)
1674 VFuncLoad->setMetadata(
1675 llvm::LLVMContext::MD_invariant_load,
1676 llvm::MDNode::get(CGM.getLLVMContext(),
1677 llvm::ArrayRef<llvm::Metadata *>()));
1678 VFunc = VFuncLoad;
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001679 }
John McCallb92ab1a2016-10-26 23:46:34 +00001680
1681 CGCallee Callee(MethodDecl, VFunc);
1682 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001683}
1684
David Majnemer0c0b6d92014-10-31 20:09:12 +00001685llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1686 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001687 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001688 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001689 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1690
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001691 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1692 Dtor, getFromDtorType(DtorType));
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001693 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001694 CGCallee Callee =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001695 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1696 CE ? CE->getLocStart() : SourceLocation());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001697
John McCall7f416cc2015-09-08 08:05:57 +00001698 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1699 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001700 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001701 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001702}
1703
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001704void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001705 CodeGenVTables &VTables = CGM.getVTables();
1706 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001707 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001708}
1709
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001710bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001711 // We don't emit available_externally vtables if we are in -fapple-kext mode
1712 // because kext mode does not permit devirtualization.
1713 if (CGM.getLangOpts().AppleKext)
1714 return false;
1715
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001716 // If we don't have any not emitted inline virtual function, and if vtable is
1717 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001718 // FIXME we can still emit a copy of the vtable if we
1719 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001720 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001721}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001722static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001723 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001724 int64_t NonVirtualAdjustment,
1725 int64_t VirtualAdjustment,
1726 bool IsReturnAdjustment) {
1727 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001728 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001729
John McCall7f416cc2015-09-08 08:05:57 +00001730 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001731
John McCall7f416cc2015-09-08 08:05:57 +00001732 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001733 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001734 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1735 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001736 }
1737
John McCall7f416cc2015-09-08 08:05:57 +00001738 // Perform the virtual adjustment if we have one.
1739 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001740 if (VirtualAdjustment) {
1741 llvm::Type *PtrDiffTy =
1742 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1743
John McCall7f416cc2015-09-08 08:05:57 +00001744 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001745 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1746
1747 llvm::Value *OffsetPtr =
1748 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1749
1750 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1751
1752 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001753 llvm::Value *Offset =
1754 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001755
1756 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001757 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1758 } else {
1759 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001760 }
1761
John McCall7f416cc2015-09-08 08:05:57 +00001762 // In a derived-to-base conversion, the non-virtual adjustment is
1763 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001764 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001765 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1766 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001767 }
1768
1769 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001770 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001771}
1772
1773llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001774 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001775 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001776 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1777 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001778 /*IsReturnAdjustment=*/false);
1779}
1780
1781llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001782ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001783 const ReturnAdjustment &RA) {
1784 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1785 RA.Virtual.Itanium.VBaseOffsetOffset,
1786 /*IsReturnAdjustment=*/true);
1787}
1788
John McCall5d865c322010-08-31 07:33:07 +00001789void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1790 RValue RV, QualType ResultType) {
1791 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1792 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1793
1794 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001795 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001796 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1797 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1798}
John McCall8ed55a52010-09-02 09:58:18 +00001799
1800/************************** Array allocation cookies **************************/
1801
John McCallb91cd662012-05-01 05:23:51 +00001802CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1803 // The array cookie is a size_t; pad that up to the element alignment.
1804 // The cookie is actually right-justified in that space.
1805 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1806 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001807}
1808
John McCall7f416cc2015-09-08 08:05:57 +00001809Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1810 Address NewPtr,
1811 llvm::Value *NumElements,
1812 const CXXNewExpr *expr,
1813 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001814 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001815
John McCall7f416cc2015-09-08 08:05:57 +00001816 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001817
John McCall9bca9232010-09-02 10:25:57 +00001818 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001819 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001820
1821 // The size of the cookie.
1822 CharUnits CookieSize =
1823 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001824 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001825
1826 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001827 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001828 CharUnits CookieOffset = CookieSize - SizeSize;
1829 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001830 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001831
1832 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001833 Address NumElementsPtr =
1834 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001835 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001836
1837 // Handle the array cookie specially in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001838 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001839 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001840 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001841 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1842 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001843 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001844 llvm::Constant *F =
1845 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001846 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001847 }
John McCall8ed55a52010-09-02 09:58:18 +00001848
1849 // Finally, compute a pointer to the actual data buffer by skipping
1850 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001851 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001852}
1853
John McCallb91cd662012-05-01 05:23:51 +00001854llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001855 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001856 CharUnits cookieSize) {
1857 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001858 Address numElementsPtr = allocPtr;
1859 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001860 if (!numElementsOffset.isZero())
1861 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001862 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001863
John McCall7f416cc2015-09-08 08:05:57 +00001864 unsigned AS = allocPtr.getAddressSpace();
1865 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001866 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001867 return CGF.Builder.CreateLoad(numElementsPtr);
1868 // In asan mode emit a function call instead of a regular load and let the
1869 // run-time deal with it: if the shadow is properly poisoned return the
1870 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1871 // We can't simply ignore this load using nosanitize metadata because
1872 // the metadata may be lost.
1873 llvm::FunctionType *FTy =
1874 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1875 llvm::Constant *F =
1876 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001877 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001878}
1879
John McCallb91cd662012-05-01 05:23:51 +00001880CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001881 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001882 // struct array_cookie {
1883 // std::size_t element_size; // element_size != 0
1884 // std::size_t element_count;
1885 // };
John McCallc19c7062013-01-25 23:36:19 +00001886 // But the base ABI doesn't give anything an alignment greater than
1887 // 8, so we can dismiss this as typical ABI-author blindness to
1888 // actual language complexity and round up to the element alignment.
1889 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1890 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001891}
1892
John McCall7f416cc2015-09-08 08:05:57 +00001893Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1894 Address newPtr,
1895 llvm::Value *numElements,
1896 const CXXNewExpr *expr,
1897 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001898 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001899
John McCall8ed55a52010-09-02 09:58:18 +00001900 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001901 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001902
1903 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001904 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001905 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1906 getContext().getTypeSizeInChars(elementType).getQuantity());
1907 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001908
1909 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001910 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001911 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001912
1913 // Finally, compute a pointer to the actual data buffer by skipping
1914 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001915 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001916 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001917}
1918
John McCallb91cd662012-05-01 05:23:51 +00001919llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001920 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001921 CharUnits cookieSize) {
1922 // The number of elements is at offset sizeof(size_t) relative to
1923 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001924 Address numElementsPtr
1925 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001926
John McCall7f416cc2015-09-08 08:05:57 +00001927 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001928 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001929}
1930
John McCall68ff0372010-09-08 01:44:27 +00001931/*********************** Static local initialization **************************/
1932
1933static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001934 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001935 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001936 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001937 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001938 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001939 return CGM.CreateRuntimeFunction(
1940 FTy, "__cxa_guard_acquire",
1941 llvm::AttributeList::get(CGM.getLLVMContext(),
1942 llvm::AttributeList::FunctionIndex,
1943 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001944}
1945
1946static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001947 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001948 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001949 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001950 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001951 return CGM.CreateRuntimeFunction(
1952 FTy, "__cxa_guard_release",
1953 llvm::AttributeList::get(CGM.getLLVMContext(),
1954 llvm::AttributeList::FunctionIndex,
1955 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001956}
1957
1958static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001959 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001960 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001961 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001962 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001963 return CGM.CreateRuntimeFunction(
1964 FTy, "__cxa_guard_abort",
1965 llvm::AttributeList::get(CGM.getLLVMContext(),
1966 llvm::AttributeList::FunctionIndex,
1967 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001968}
1969
1970namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001971 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001972 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001973 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001974
Craig Topper4f12f102014-03-12 06:41:41 +00001975 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001976 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1977 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001978 }
1979 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001980}
John McCall68ff0372010-09-08 01:44:27 +00001981
1982/// The ARM code here follows the Itanium code closely enough that we
1983/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001984void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1985 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001986 llvm::GlobalVariable *var,
1987 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001988 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001989
Richard Smith62f19e72016-06-25 00:15:56 +00001990 // Inline variables that weren't instantiated from variable templates have
1991 // partially-ordered initialization within their translation unit.
1992 bool NonTemplateInline =
1993 D.isInline() &&
1994 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1995
1996 // We only need to use thread-safe statics for local non-TLS variables and
1997 // inline variables; other global initialization is always single-threaded
1998 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001999 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002000 (D.isLocalVarDecl() || NonTemplateInline) &&
2001 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002002
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002003 // If we have a global variable with internal linkage and thread-safe statics
2004 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002005 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2006
2007 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002008 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002009 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002010 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002011 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002012 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002013 // Guard variables are 64 bits in the generic ABI and size width on ARM
2014 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002015 if (UseARMGuardVarABI) {
2016 guardTy = CGF.SizeTy;
2017 guardAlignment = CGF.getSizeAlign();
2018 } else {
2019 guardTy = CGF.Int64Ty;
2020 guardAlignment = CharUnits::fromQuantity(
2021 CGM.getDataLayout().getABITypeAlignment(guardTy));
2022 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002023 }
John McCallb88a5662012-03-30 21:00:39 +00002024 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002025
John McCallb88a5662012-03-30 21:00:39 +00002026 // Create the guard variable if we don't already have it (as we
2027 // might if we're double-emitting this function body).
2028 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2029 if (!guard) {
2030 // Mangle the name for the guard.
2031 SmallString<256> guardName;
2032 {
2033 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002034 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002035 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002036
John McCallb88a5662012-03-30 21:00:39 +00002037 // Create the guard variable with a zero-initializer.
2038 // Just absorb linkage and visibility from the guarded variable.
2039 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2040 false, var->getLinkage(),
2041 llvm::ConstantInt::get(guardTy, 0),
2042 guardName.str());
2043 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002044 // If the variable is thread-local, so is its guard variable.
2045 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002046 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002047
Yaron Keren5bfa1082015-09-03 20:33:29 +00002048 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2049 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002050 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002051 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002052 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002053 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2054 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002055 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002056 // An inline variable's guard function is run from the per-TU
2057 // initialization function, not via a dedicated global ctor function, so
2058 // we can't put it in a comdat.
2059 if (!NonTemplateInline)
2060 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002061 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2062 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002063 }
2064
John McCallb88a5662012-03-30 21:00:39 +00002065 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2066 }
John McCall87590e62012-03-30 07:09:50 +00002067
John McCall7f416cc2015-09-08 08:05:57 +00002068 Address guardAddr = Address(guard, guardAlignment);
2069
John McCall68ff0372010-09-08 01:44:27 +00002070 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002071 //
John McCall68ff0372010-09-08 01:44:27 +00002072 // Itanium C++ ABI 3.3.2:
2073 // The following is pseudo-code showing how these functions can be used:
2074 // if (obj_guard.first_byte == 0) {
2075 // if ( __cxa_guard_acquire (&obj_guard) ) {
2076 // try {
2077 // ... initialize the object ...;
2078 // } catch (...) {
2079 // __cxa_guard_abort (&obj_guard);
2080 // throw;
2081 // }
2082 // ... queue object destructor with __cxa_atexit() ...;
2083 // __cxa_guard_release (&obj_guard);
2084 // }
2085 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002086
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002087 // Load the first byte of the guard variable.
2088 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002089 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002090
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002091 // Itanium ABI:
2092 // An implementation supporting thread-safety on multiprocessor
2093 // systems must also guarantee that references to the initialized
2094 // object do not occur before the load of the initialization flag.
2095 //
2096 // In LLVM, we do this by marking the load Acquire.
2097 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002098 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002099
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002100 // For ARM, we should only check the first bit, rather than the entire byte:
2101 //
2102 // ARM C++ ABI 3.2.3.1:
2103 // To support the potential use of initialization guard variables
2104 // as semaphores that are the target of ARM SWP and LDREX/STREX
2105 // synchronizing instructions we define a static initialization
2106 // guard variable to be a 4-byte aligned, 4-byte word with the
2107 // following inline access protocol.
2108 // #define INITIALIZED 1
2109 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2110 // if (__cxa_guard_acquire(&obj_guard))
2111 // ...
2112 // }
2113 //
2114 // and similarly for ARM64:
2115 //
2116 // ARM64 C++ ABI 3.2.2:
2117 // This ABI instead only specifies the value bit 0 of the static guard
2118 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2119 // variable is not initialized and 1 when it is.
2120 llvm::Value *V =
2121 (UseARMGuardVarABI && !useInt8GuardVariable)
2122 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2123 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002124 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002125
2126 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2127 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2128
2129 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002130 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2131 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002132
2133 CGF.EmitBlock(InitCheckBlock);
2134
2135 // Variables used when coping with thread-safe statics and exceptions.
John McCall5aa52592011-06-17 07:33:57 +00002136 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002137 // Call __cxa_guard_acquire.
2138 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002139 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
John McCall68ff0372010-09-08 01:44:27 +00002140
2141 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2142
2143 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2144 InitBlock, EndBlock);
2145
2146 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002147 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
John McCall68ff0372010-09-08 01:44:27 +00002148
2149 CGF.EmitBlock(InitBlock);
2150 }
2151
2152 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002153 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002154
John McCall5aa52592011-06-17 07:33:57 +00002155 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002156 // Pop the guard-abort cleanup if we pushed one.
2157 CGF.PopCleanupBlock();
2158
2159 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002160 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2161 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002162 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002163 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002164 }
2165
2166 CGF.EmitBlock(EndBlock);
2167}
John McCallc84ed6a2012-05-01 06:13:13 +00002168
2169/// Register a global destructor using __cxa_atexit.
2170static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2171 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002172 llvm::Constant *addr,
2173 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002174 const char *Name = "__cxa_atexit";
2175 if (TLS) {
2176 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002177 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002178 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002179
John McCallc84ed6a2012-05-01 06:13:13 +00002180 // We're assuming that the destructor function is something we can
2181 // reasonably call with the default CC. Go ahead and cast it to the
2182 // right prototype.
2183 llvm::Type *dtorTy =
2184 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2185
2186 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2187 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2188 llvm::FunctionType *atexitTy =
2189 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2190
2191 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002192 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002193 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2194 fn->setDoesNotThrow();
2195
2196 // Create a variable that binds the atexit to this shared object.
2197 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002198 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2199 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2200 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002201
2202 llvm::Value *args[] = {
2203 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2204 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2205 handle
2206 };
John McCall882987f2013-02-28 19:01:20 +00002207 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002208}
2209
2210/// Register a global destructor as best as we know how.
2211void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002212 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002213 llvm::Constant *dtor,
2214 llvm::Constant *addr) {
2215 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002216 if (CGM.getCodeGenOpts().CXAAtExit)
2217 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2218
2219 if (D.getTLSKind())
2220 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002221
2222 // In Apple kexts, we want to add a global destructor entry.
2223 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002224 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002225 // Generate a global destructor entry.
2226 return CGM.AddCXXDtorEntry(dtor, addr);
2227 }
2228
David Blaikieebe87e12013-08-27 23:57:18 +00002229 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002230}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002231
David Majnemer9b21c332014-07-11 20:28:10 +00002232static bool isThreadWrapperReplaceable(const VarDecl *VD,
2233 CodeGen::CodeGenModule &CGM) {
2234 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002235 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002236 // the thread wrapper instead of directly referencing the backing variable.
2237 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002238 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002239}
2240
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002241/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002242/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002243/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002244static llvm::GlobalValue::LinkageTypes
2245getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2246 llvm::GlobalValue::LinkageTypes VarLinkage =
2247 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2248
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002249 // For internal linkage variables, we don't need an external or weak wrapper.
2250 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2251 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002252
David Majnemer9b21c332014-07-11 20:28:10 +00002253 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002254 if (isThreadWrapperReplaceable(VD, CGM))
2255 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2256 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2257 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002258 return llvm::GlobalValue::WeakODRLinkage;
2259}
2260
2261llvm::Function *
2262ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002263 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002264 // Mangle the name for the thread_local wrapper function.
2265 SmallString<256> WrapperName;
2266 {
2267 llvm::raw_svector_ostream Out(WrapperName);
2268 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002269 }
2270
Akira Hatanaka26907f92016-01-15 03:34:06 +00002271 // FIXME: If VD is a definition, we should regenerate the function attributes
2272 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002273 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002274 return cast<llvm::Function>(V);
2275
Akira Hatanaka26907f92016-01-15 03:34:06 +00002276 QualType RetQT = VD->getType();
2277 if (RetQT->isReferenceType())
2278 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002279
John McCallc56a8b32016-03-11 04:30:31 +00002280 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2281 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002282
2283 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002284 llvm::Function *Wrapper =
2285 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2286 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002287
2288 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2289
2290 if (VD->hasDefinition())
2291 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2292
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002293 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002294 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2295 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2296 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002297 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002298
2299 if (isThreadWrapperReplaceable(VD, CGM)) {
2300 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2301 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2302 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002303 return Wrapper;
2304}
2305
2306void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002307 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2308 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2309 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002310 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002311
2312 // Separate initializers into those with ordered (or partially-ordered)
2313 // initialization and those with unordered initialization.
2314 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2315 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2316 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2317 if (isTemplateInstantiation(
2318 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2319 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2320 CXXThreadLocalInits[I];
2321 else
2322 OrderedInits.push_back(CXXThreadLocalInits[I]);
2323 }
2324
2325 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002326 // Generate a guarded initialization function.
2327 llvm::FunctionType *FTy =
2328 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002329 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2330 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002331 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002332 /*TLS=*/true);
2333 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2334 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2335 llvm::GlobalVariable::InternalLinkage,
2336 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2337 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002338
2339 CharUnits GuardAlign = CharUnits::One();
2340 Guard->setAlignment(GuardAlign.getQuantity());
2341
Richard Smithfbe23692017-01-13 00:43:31 +00002342 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2343 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002344 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2345 if (CGM.getTarget().getTriple().isOSDarwin()) {
2346 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2347 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2348 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002349 }
Richard Smithfbe23692017-01-13 00:43:31 +00002350
2351 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002352 for (const VarDecl *VD : CXXThreadLocals) {
2353 llvm::GlobalVariable *Var =
2354 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002355 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002356
David Majnemer9b21c332014-07-11 20:28:10 +00002357 // Some targets require that all access to thread local variables go through
2358 // the thread wrapper. This means that we cannot attempt to create a thread
2359 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002360 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2361 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002362 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002363 }
David Majnemer9b21c332014-07-11 20:28:10 +00002364
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002365 // Mangle the name for the thread_local initialization function.
2366 SmallString<256> InitFnName;
2367 {
2368 llvm::raw_svector_ostream Out(InitFnName);
2369 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002370 }
2371
2372 // If we have a definition for the variable, emit the initialization
2373 // function as an alias to the global Init function (if any). Otherwise,
2374 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002375 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002376 bool InitIsInitFunc = false;
2377 if (VD->hasDefinition()) {
2378 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002379 llvm::Function *InitFuncToUse = InitFunc;
2380 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2381 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2382 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002383 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002384 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002385 } else {
2386 // Emit a weak global function referring to the initialization function.
2387 // This function will not exist if the TU defining the thread_local
2388 // variable in question does not need any dynamic initialization for
2389 // its thread_local variables.
2390 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002391 Init = llvm::Function::Create(FnTy,
2392 llvm::GlobalVariable::ExternalWeakLinkage,
2393 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002394 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002395 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002396 }
2397
2398 if (Init)
2399 Init->setVisibility(Var->getVisibility());
2400
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002401 llvm::LLVMContext &Context = CGM.getModule().getContext();
2402 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002403 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002404 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002405 if (Init) {
2406 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2407 if (isThreadWrapperReplaceable(VD, CGM))
2408 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2409 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002410 } else {
2411 // Don't know whether we have an init function. Call it if it exists.
2412 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2413 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2414 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2415 Builder.CreateCondBr(Have, InitBB, ExitBB);
2416
2417 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002418 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002419 Builder.CreateBr(ExitBB);
2420
2421 Builder.SetInsertPoint(ExitBB);
2422 }
2423
2424 // For a reference, the result of the wrapper function is a pointer to
2425 // the referenced object.
2426 llvm::Value *Val = Var;
2427 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002428 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2429 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002430 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002431 if (Val->getType() != Wrapper->getReturnType())
2432 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2433 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002434 Builder.CreateRet(Val);
2435 }
2436}
2437
Richard Smith0f383742014-03-26 22:48:22 +00002438LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2439 const VarDecl *VD,
2440 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002441 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002442 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002443
Manman Renb0b3af72015-12-17 00:42:36 +00002444 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002445 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002446
2447 LValue LV;
2448 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002449 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002450 else
Manman Renb0b3af72015-12-17 00:42:36 +00002451 LV = CGF.MakeAddrLValue(CallVal, LValType,
2452 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002453 // FIXME: need setObjCGCLValueClass?
2454 return LV;
2455}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002456
2457/// Return whether the given global decl needs a VTT parameter, which it does
2458/// if it's a base constructor or destructor with virtual bases.
2459bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2460 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2461
2462 // We don't have any virtual bases, just return early.
2463 if (!MD->getParent()->getNumVBases())
2464 return false;
2465
2466 // Check if we have a base constructor.
2467 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2468 return true;
2469
2470 // Check if we have a base destructor.
2471 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2472 return true;
2473
2474 return false;
2475}
David Majnemere2cb8d12014-07-07 06:20:47 +00002476
2477namespace {
2478class ItaniumRTTIBuilder {
2479 CodeGenModule &CGM; // Per-module state.
2480 llvm::LLVMContext &VMContext;
2481 const ItaniumCXXABI &CXXABI; // Per-module state.
2482
2483 /// Fields - The fields of the RTTI descriptor currently being built.
2484 SmallVector<llvm::Constant *, 16> Fields;
2485
2486 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2487 llvm::GlobalVariable *
2488 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2489
2490 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2491 /// descriptor of the given type.
2492 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2493
2494 /// BuildVTablePointer - Build the vtable pointer for the given type.
2495 void BuildVTablePointer(const Type *Ty);
2496
2497 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2498 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2499 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2500
2501 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2502 /// classes with bases that do not satisfy the abi::__si_class_type_info
2503 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2504 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2505
2506 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2507 /// for pointer types.
2508 void BuildPointerTypeInfo(QualType PointeeTy);
2509
2510 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2511 /// type_info for an object type.
2512 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2513
2514 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2515 /// struct, used for member pointer types.
2516 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2517
2518public:
2519 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2520 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2521
2522 // Pointer type info flags.
2523 enum {
2524 /// PTI_Const - Type has const qualifier.
2525 PTI_Const = 0x1,
2526
2527 /// PTI_Volatile - Type has volatile qualifier.
2528 PTI_Volatile = 0x2,
2529
2530 /// PTI_Restrict - Type has restrict qualifier.
2531 PTI_Restrict = 0x4,
2532
2533 /// PTI_Incomplete - Type is incomplete.
2534 PTI_Incomplete = 0x8,
2535
2536 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2537 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002538 PTI_ContainingClassIncomplete = 0x10,
2539
2540 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2541 //PTI_TransactionSafe = 0x20,
2542
2543 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2544 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002545 };
2546
2547 // VMI type info flags.
2548 enum {
2549 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2550 VMI_NonDiamondRepeat = 0x1,
2551
2552 /// VMI_DiamondShaped - Class is diamond shaped.
2553 VMI_DiamondShaped = 0x2
2554 };
2555
2556 // Base class type info flags.
2557 enum {
2558 /// BCTI_Virtual - Base class is virtual.
2559 BCTI_Virtual = 0x1,
2560
2561 /// BCTI_Public - Base class is public.
2562 BCTI_Public = 0x2
2563 };
2564
2565 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2566 ///
2567 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002568 /// \param DLLExport - true to mark the RTTI value as DLLExport
2569 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2570 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002571};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002572}
David Majnemere2cb8d12014-07-07 06:20:47 +00002573
2574llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2575 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002576 SmallString<256> Name;
2577 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002578 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002579
2580 // We know that the mangled name of the type starts at index 4 of the
2581 // mangled name of the typename, so we can just index into it in order to
2582 // get the mangled name of the type.
2583 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2584 Name.substr(4));
2585
2586 llvm::GlobalVariable *GV =
2587 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2588
2589 GV->setInitializer(Init);
2590
2591 return GV;
2592}
2593
2594llvm::Constant *
2595ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2596 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002597 SmallString<256> Name;
2598 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002599 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002600
2601 // Look for an existing global.
2602 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2603
2604 if (!GV) {
2605 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002606 // Note for the future: If we would ever like to do deferred emission of
2607 // RTTI, check if emitting vtables opportunistically need any adjustment.
2608
David Majnemere2cb8d12014-07-07 06:20:47 +00002609 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2610 /*Constant=*/true,
2611 llvm::GlobalValue::ExternalLinkage, nullptr,
2612 Name);
David Majnemer1fb1a042014-11-07 07:26:38 +00002613 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2614 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2615 if (RD->hasAttr<DLLImportAttr>())
2616 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2617 }
David Majnemere2cb8d12014-07-07 06:20:47 +00002618 }
2619
2620 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2621}
2622
2623/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2624/// info for that type is defined in the standard library.
2625static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2626 // Itanium C++ ABI 2.9.2:
2627 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2628 // the run-time support library. Specifically, the run-time support
2629 // library should contain type_info objects for the types X, X* and
2630 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2631 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2632 // long, unsigned long, long long, unsigned long long, float, double,
2633 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2634 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002635 //
2636 // GCC also emits RTTI for __int128.
2637 // FIXME: We do not emit RTTI information for decimal types here.
2638
2639 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002640 switch (Ty->getKind()) {
2641 case BuiltinType::Void:
2642 case BuiltinType::NullPtr:
2643 case BuiltinType::Bool:
2644 case BuiltinType::WChar_S:
2645 case BuiltinType::WChar_U:
2646 case BuiltinType::Char_U:
2647 case BuiltinType::Char_S:
2648 case BuiltinType::UChar:
2649 case BuiltinType::SChar:
2650 case BuiltinType::Short:
2651 case BuiltinType::UShort:
2652 case BuiltinType::Int:
2653 case BuiltinType::UInt:
2654 case BuiltinType::Long:
2655 case BuiltinType::ULong:
2656 case BuiltinType::LongLong:
2657 case BuiltinType::ULongLong:
2658 case BuiltinType::Half:
2659 case BuiltinType::Float:
2660 case BuiltinType::Double:
2661 case BuiltinType::LongDouble:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002662 case BuiltinType::Float128:
David Majnemere2cb8d12014-07-07 06:20:47 +00002663 case BuiltinType::Char16:
2664 case BuiltinType::Char32:
2665 case BuiltinType::Int128:
2666 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002667 return true;
2668
Alexey Bader954ba212016-04-08 13:40:33 +00002669#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2670 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002671#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002672 case BuiltinType::OCLSampler:
2673 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002674 case BuiltinType::OCLClkEvent:
2675 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002676 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002677 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002678
2679 case BuiltinType::Dependent:
2680#define BUILTIN_TYPE(Id, SingletonId)
2681#define PLACEHOLDER_TYPE(Id, SingletonId) \
2682 case BuiltinType::Id:
2683#include "clang/AST/BuiltinTypes.def"
2684 llvm_unreachable("asking for RRTI for a placeholder type!");
2685
2686 case BuiltinType::ObjCId:
2687 case BuiltinType::ObjCClass:
2688 case BuiltinType::ObjCSel:
2689 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2690 }
2691
2692 llvm_unreachable("Invalid BuiltinType Kind!");
2693}
2694
2695static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2696 QualType PointeeTy = PointerTy->getPointeeType();
2697 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2698 if (!BuiltinTy)
2699 return false;
2700
2701 // Check the qualifiers.
2702 Qualifiers Quals = PointeeTy.getQualifiers();
2703 Quals.removeConst();
2704
2705 if (!Quals.empty())
2706 return false;
2707
2708 return TypeInfoIsInStandardLibrary(BuiltinTy);
2709}
2710
2711/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2712/// information for the given type exists in the standard library.
2713static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2714 // Type info for builtin types is defined in the standard library.
2715 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2716 return TypeInfoIsInStandardLibrary(BuiltinTy);
2717
2718 // Type info for some pointer types to builtin types is defined in the
2719 // standard library.
2720 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2721 return TypeInfoIsInStandardLibrary(PointerTy);
2722
2723 return false;
2724}
2725
2726/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2727/// the given type exists somewhere else, and that we should not emit the type
2728/// information in this translation unit. Assumes that it is not a
2729/// standard-library type.
2730static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2731 QualType Ty) {
2732 ASTContext &Context = CGM.getContext();
2733
2734 // If RTTI is disabled, assume it might be disabled in the
2735 // translation unit that defines any potential key function, too.
2736 if (!Context.getLangOpts().RTTI) return false;
2737
2738 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2739 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2740 if (!RD->hasDefinition())
2741 return false;
2742
2743 if (!RD->isDynamicClass())
2744 return false;
2745
2746 // FIXME: this may need to be reconsidered if the key function
2747 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002748 // N.B. We must always emit the RTTI data ourselves if there exists a key
2749 // function.
2750 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
David Majnemer1fb1a042014-11-07 07:26:38 +00002751 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002752 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2753 ? false
2754 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002755
David Majnemerbe9022c2015-08-06 20:56:55 +00002756 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002757 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002758 }
2759
2760 return false;
2761}
2762
2763/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2764static bool IsIncompleteClassType(const RecordType *RecordTy) {
2765 return !RecordTy->getDecl()->isCompleteDefinition();
2766}
2767
2768/// ContainsIncompleteClassType - Returns whether the given type contains an
2769/// incomplete class type. This is true if
2770///
2771/// * The given type is an incomplete class type.
2772/// * The given type is a pointer type whose pointee type contains an
2773/// incomplete class type.
2774/// * The given type is a member pointer type whose class is an incomplete
2775/// class type.
2776/// * The given type is a member pointer type whoise pointee type contains an
2777/// incomplete class type.
2778/// is an indirect or direct pointer to an incomplete class type.
2779static bool ContainsIncompleteClassType(QualType Ty) {
2780 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2781 if (IsIncompleteClassType(RecordTy))
2782 return true;
2783 }
2784
2785 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2786 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2787
2788 if (const MemberPointerType *MemberPointerTy =
2789 dyn_cast<MemberPointerType>(Ty)) {
2790 // Check if the class type is incomplete.
2791 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2792 if (IsIncompleteClassType(ClassType))
2793 return true;
2794
2795 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2796 }
2797
2798 return false;
2799}
2800
2801// CanUseSingleInheritance - Return whether the given record decl has a "single,
2802// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2803// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2804static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2805 // Check the number of bases.
2806 if (RD->getNumBases() != 1)
2807 return false;
2808
2809 // Get the base.
2810 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2811
2812 // Check that the base is not virtual.
2813 if (Base->isVirtual())
2814 return false;
2815
2816 // Check that the base is public.
2817 if (Base->getAccessSpecifier() != AS_public)
2818 return false;
2819
2820 // Check that the class is dynamic iff the base is.
2821 const CXXRecordDecl *BaseDecl =
2822 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2823 if (!BaseDecl->isEmpty() &&
2824 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2825 return false;
2826
2827 return true;
2828}
2829
2830void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2831 // abi::__class_type_info.
2832 static const char * const ClassTypeInfo =
2833 "_ZTVN10__cxxabiv117__class_type_infoE";
2834 // abi::__si_class_type_info.
2835 static const char * const SIClassTypeInfo =
2836 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2837 // abi::__vmi_class_type_info.
2838 static const char * const VMIClassTypeInfo =
2839 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2840
2841 const char *VTableName = nullptr;
2842
2843 switch (Ty->getTypeClass()) {
2844#define TYPE(Class, Base)
2845#define ABSTRACT_TYPE(Class, Base)
2846#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2847#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2848#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2849#include "clang/AST/TypeNodes.def"
2850 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2851
2852 case Type::LValueReference:
2853 case Type::RValueReference:
2854 llvm_unreachable("References shouldn't get here");
2855
2856 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002857 case Type::DeducedTemplateSpecialization:
2858 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002859
Xiuli Pan9c14e282016-01-09 12:53:17 +00002860 case Type::Pipe:
2861 llvm_unreachable("Pipe types shouldn't get here");
2862
David Majnemere2cb8d12014-07-07 06:20:47 +00002863 case Type::Builtin:
2864 // GCC treats vector and complex types as fundamental types.
2865 case Type::Vector:
2866 case Type::ExtVector:
2867 case Type::Complex:
2868 case Type::Atomic:
2869 // FIXME: GCC treats block pointers as fundamental types?!
2870 case Type::BlockPointer:
2871 // abi::__fundamental_type_info.
2872 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2873 break;
2874
2875 case Type::ConstantArray:
2876 case Type::IncompleteArray:
2877 case Type::VariableArray:
2878 // abi::__array_type_info.
2879 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2880 break;
2881
2882 case Type::FunctionNoProto:
2883 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002884 // abi::__function_type_info.
2885 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002886 break;
2887
2888 case Type::Enum:
2889 // abi::__enum_type_info.
2890 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2891 break;
2892
2893 case Type::Record: {
2894 const CXXRecordDecl *RD =
2895 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2896
2897 if (!RD->hasDefinition() || !RD->getNumBases()) {
2898 VTableName = ClassTypeInfo;
2899 } else if (CanUseSingleInheritance(RD)) {
2900 VTableName = SIClassTypeInfo;
2901 } else {
2902 VTableName = VMIClassTypeInfo;
2903 }
2904
2905 break;
2906 }
2907
2908 case Type::ObjCObject:
2909 // Ignore protocol qualifiers.
2910 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2911
2912 // Handle id and Class.
2913 if (isa<BuiltinType>(Ty)) {
2914 VTableName = ClassTypeInfo;
2915 break;
2916 }
2917
2918 assert(isa<ObjCInterfaceType>(Ty));
2919 // Fall through.
2920
2921 case Type::ObjCInterface:
2922 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2923 VTableName = SIClassTypeInfo;
2924 } else {
2925 VTableName = ClassTypeInfo;
2926 }
2927 break;
2928
2929 case Type::ObjCObjectPointer:
2930 case Type::Pointer:
2931 // abi::__pointer_type_info.
2932 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2933 break;
2934
2935 case Type::MemberPointer:
2936 // abi::__pointer_to_member_type_info.
2937 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2938 break;
2939 }
2940
2941 llvm::Constant *VTable =
2942 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2943
2944 llvm::Type *PtrDiffTy =
2945 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2946
2947 // The vtable address point is 2.
2948 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002949 VTable =
2950 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00002951 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2952
2953 Fields.push_back(VTable);
2954}
2955
2956/// \brief Return the linkage that the type info and type info name constants
2957/// should have for the given type.
2958static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2959 QualType Ty) {
2960 // Itanium C++ ABI 2.9.5p7:
2961 // In addition, it and all of the intermediate abi::__pointer_type_info
2962 // structs in the chain down to the abi::__class_type_info for the
2963 // incomplete class type must be prevented from resolving to the
2964 // corresponding type_info structs for the complete class type, possibly
2965 // by making them local static objects. Finally, a dummy class RTTI is
2966 // generated for the incomplete type that will not resolve to the final
2967 // complete class RTTI (because the latter need not exist), possibly by
2968 // making it a local static object.
2969 if (ContainsIncompleteClassType(Ty))
2970 return llvm::GlobalValue::InternalLinkage;
2971
2972 switch (Ty->getLinkage()) {
2973 case NoLinkage:
2974 case InternalLinkage:
2975 case UniqueExternalLinkage:
2976 return llvm::GlobalValue::InternalLinkage;
2977
2978 case VisibleNoLinkage:
Richard Smith1283e982017-07-07 20:04:28 +00002979 case ModuleInternalLinkage:
2980 case ModuleLinkage:
David Majnemere2cb8d12014-07-07 06:20:47 +00002981 case ExternalLinkage:
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002982 // RTTI is not enabled, which means that this type info struct is going
2983 // to be used for exception handling. Give it linkonce_odr linkage.
2984 if (!CGM.getLangOpts().RTTI)
David Majnemere2cb8d12014-07-07 06:20:47 +00002985 return llvm::GlobalValue::LinkOnceODRLinkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00002986
2987 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2988 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2989 if (RD->hasAttr<WeakAttr>())
2990 return llvm::GlobalValue::WeakODRLinkage;
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002991 if (CGM.getTriple().isWindowsItaniumEnvironment())
Shoaib Meenai61118e72017-07-04 01:02:19 +00002992 if (RD->hasAttr<DLLImportAttr>() &&
2993 ShouldUseExternalRTTIDescriptor(CGM, Ty))
Saleem Abdulrasool18820022016-12-02 22:46:18 +00002994 return llvm::GlobalValue::ExternalLinkage;
David Majnemerbe9022c2015-08-06 20:56:55 +00002995 if (RD->isDynamicClass()) {
2996 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2997 // MinGW won't export the RTTI information when there is a key function.
2998 // Make sure we emit our own copy instead of attempting to dllimport it.
2999 if (RD->hasAttr<DLLImportAttr>() &&
3000 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
3001 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3002 return LT;
3003 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003004 }
3005
3006 return llvm::GlobalValue::LinkOnceODRLinkage;
3007 }
3008
3009 llvm_unreachable("Invalid linkage!");
3010}
3011
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003012llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3013 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003014 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003015 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003016
3017 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003018 SmallString<256> Name;
3019 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003020 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003021
3022 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3023 if (OldGV && !OldGV->isDeclaration()) {
3024 assert(!OldGV->hasAvailableExternallyLinkage() &&
3025 "available_externally typeinfos not yet implemented");
3026
3027 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3028 }
3029
3030 // Check if there is already an external RTTI descriptor for this type.
3031 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3032 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3033 return GetAddrOfExternalRTTIDescriptor(Ty);
3034
3035 // Emit the standard library with external linkage.
3036 llvm::GlobalVariable::LinkageTypes Linkage;
3037 if (IsStdLib)
3038 Linkage = llvm::GlobalValue::ExternalLinkage;
3039 else
3040 Linkage = getTypeInfoLinkage(CGM, Ty);
3041
3042 // Add the vtable pointer.
3043 BuildVTablePointer(cast<Type>(Ty));
3044
3045 // And the name.
3046 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3047 llvm::Constant *TypeNameField;
3048
3049 // If we're supposed to demote the visibility, be sure to set a flag
3050 // to use a string comparison for type_info comparisons.
3051 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3052 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3053 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3054 // The flag is the sign bit, which on ARM64 is defined to be clear
3055 // for global pointers. This is very ARM64-specific.
3056 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3057 llvm::Constant *flag =
3058 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3059 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3060 TypeNameField =
3061 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3062 } else {
3063 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3064 }
3065 Fields.push_back(TypeNameField);
3066
3067 switch (Ty->getTypeClass()) {
3068#define TYPE(Class, Base)
3069#define ABSTRACT_TYPE(Class, Base)
3070#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3071#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3072#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3073#include "clang/AST/TypeNodes.def"
3074 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3075
3076 // GCC treats vector types as fundamental types.
3077 case Type::Builtin:
3078 case Type::Vector:
3079 case Type::ExtVector:
3080 case Type::Complex:
3081 case Type::BlockPointer:
3082 // Itanium C++ ABI 2.9.5p4:
3083 // abi::__fundamental_type_info adds no data members to std::type_info.
3084 break;
3085
3086 case Type::LValueReference:
3087 case Type::RValueReference:
3088 llvm_unreachable("References shouldn't get here");
3089
3090 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003091 case Type::DeducedTemplateSpecialization:
3092 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003093
Xiuli Pan9c14e282016-01-09 12:53:17 +00003094 case Type::Pipe:
3095 llvm_unreachable("Pipe type shouldn't get here");
3096
David Majnemere2cb8d12014-07-07 06:20:47 +00003097 case Type::ConstantArray:
3098 case Type::IncompleteArray:
3099 case Type::VariableArray:
3100 // Itanium C++ ABI 2.9.5p5:
3101 // abi::__array_type_info adds no data members to std::type_info.
3102 break;
3103
3104 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003105 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003106 // Itanium C++ ABI 2.9.5p5:
3107 // abi::__function_type_info adds no data members to std::type_info.
3108 break;
3109
3110 case Type::Enum:
3111 // Itanium C++ ABI 2.9.5p5:
3112 // abi::__enum_type_info adds no data members to std::type_info.
3113 break;
3114
3115 case Type::Record: {
3116 const CXXRecordDecl *RD =
3117 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3118 if (!RD->hasDefinition() || !RD->getNumBases()) {
3119 // We don't need to emit any fields.
3120 break;
3121 }
3122
3123 if (CanUseSingleInheritance(RD))
3124 BuildSIClassTypeInfo(RD);
3125 else
3126 BuildVMIClassTypeInfo(RD);
3127
3128 break;
3129 }
3130
3131 case Type::ObjCObject:
3132 case Type::ObjCInterface:
3133 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3134 break;
3135
3136 case Type::ObjCObjectPointer:
3137 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3138 break;
3139
3140 case Type::Pointer:
3141 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3142 break;
3143
3144 case Type::MemberPointer:
3145 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3146 break;
3147
3148 case Type::Atomic:
3149 // No fields, at least for the moment.
3150 break;
3151 }
3152
3153 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3154
Rafael Espindolacb92c192015-01-15 23:18:01 +00003155 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003156 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003157 new llvm::GlobalVariable(M, Init->getType(),
3158 /*Constant=*/true, Linkage, Init, Name);
3159
David Majnemere2cb8d12014-07-07 06:20:47 +00003160 // If there's already an old global variable, replace it with the new one.
3161 if (OldGV) {
3162 GV->takeName(OldGV);
3163 llvm::Constant *NewPtr =
3164 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3165 OldGV->replaceAllUsesWith(NewPtr);
3166 OldGV->eraseFromParent();
3167 }
3168
Yaron Keren04da2382015-07-29 15:42:28 +00003169 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3170 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3171
David Majnemere2cb8d12014-07-07 06:20:47 +00003172 // The Itanium ABI specifies that type_info objects must be globally
3173 // unique, with one exception: if the type is an incomplete class
3174 // type or a (possibly indirect) pointer to one. That exception
3175 // affects the general case of comparing type_info objects produced
3176 // by the typeid operator, which is why the comparison operators on
3177 // std::type_info generally use the type_info name pointers instead
3178 // of the object addresses. However, the language's built-in uses
3179 // of RTTI generally require class types to be complete, even when
3180 // manipulating pointers to those class types. This allows the
3181 // implementation of dynamic_cast to rely on address equality tests,
3182 // which is much faster.
3183
3184 // All of this is to say that it's important that both the type_info
3185 // object and the type_info name be uniqued when weakly emitted.
3186
3187 // Give the type_info object and name the formal visibility of the
3188 // type itself.
3189 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3190 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3191 // If the linkage is local, only default visibility makes sense.
3192 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3193 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3194 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3195 else
3196 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003197
David Majnemere2cb8d12014-07-07 06:20:47 +00003198 TypeName->setVisibility(llvmVisibility);
3199 GV->setVisibility(llvmVisibility);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003200
3201 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3202 auto RD = Ty->getAsCXXRecordDecl();
3203 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3204 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3205 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003206 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3207 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003208 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3209 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3210
3211 // Because the typename and the typeinfo are DLL import, convert them to
3212 // declarations rather than definitions. The initializers still need to
3213 // be constructed to calculate the type for the declarations.
3214 TypeName->setInitializer(nullptr);
3215 GV->setInitializer(nullptr);
3216 }
3217 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003218
3219 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3220}
3221
David Majnemere2cb8d12014-07-07 06:20:47 +00003222/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3223/// for the given Objective-C object type.
3224void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3225 // Drop qualifiers.
3226 const Type *T = OT->getBaseType().getTypePtr();
3227 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3228
3229 // The builtin types are abi::__class_type_infos and don't require
3230 // extra fields.
3231 if (isa<BuiltinType>(T)) return;
3232
3233 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3234 ObjCInterfaceDecl *Super = Class->getSuperClass();
3235
3236 // Root classes are also __class_type_info.
3237 if (!Super) return;
3238
3239 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3240
3241 // Everything else is single inheritance.
3242 llvm::Constant *BaseTypeInfo =
3243 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3244 Fields.push_back(BaseTypeInfo);
3245}
3246
3247/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3248/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3249void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3250 // Itanium C++ ABI 2.9.5p6b:
3251 // It adds to abi::__class_type_info a single member pointing to the
3252 // type_info structure for the base type,
3253 llvm::Constant *BaseTypeInfo =
3254 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3255 Fields.push_back(BaseTypeInfo);
3256}
3257
3258namespace {
3259 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3260 /// a class hierarchy.
3261 struct SeenBases {
3262 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3263 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3264 };
3265}
3266
3267/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3268/// abi::__vmi_class_type_info.
3269///
3270static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3271 SeenBases &Bases) {
3272
3273 unsigned Flags = 0;
3274
3275 const CXXRecordDecl *BaseDecl =
3276 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3277
3278 if (Base->isVirtual()) {
3279 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003280 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003281 // If this virtual base has been seen before, then the class is diamond
3282 // shaped.
3283 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3284 } else {
3285 if (Bases.NonVirtualBases.count(BaseDecl))
3286 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3287 }
3288 } else {
3289 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003290 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003291 // If this non-virtual base has been seen before, then the class has non-
3292 // diamond shaped repeated inheritance.
3293 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3294 } else {
3295 if (Bases.VirtualBases.count(BaseDecl))
3296 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3297 }
3298 }
3299
3300 // Walk all bases.
3301 for (const auto &I : BaseDecl->bases())
3302 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3303
3304 return Flags;
3305}
3306
3307static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3308 unsigned Flags = 0;
3309 SeenBases Bases;
3310
3311 // Walk all bases.
3312 for (const auto &I : RD->bases())
3313 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3314
3315 return Flags;
3316}
3317
3318/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3319/// classes with bases that do not satisfy the abi::__si_class_type_info
3320/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3321void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3322 llvm::Type *UnsignedIntLTy =
3323 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3324
3325 // Itanium C++ ABI 2.9.5p6c:
3326 // __flags is a word with flags describing details about the class
3327 // structure, which may be referenced by using the __flags_masks
3328 // enumeration. These flags refer to both direct and indirect bases.
3329 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3330 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3331
3332 // Itanium C++ ABI 2.9.5p6c:
3333 // __base_count is a word with the number of direct proper base class
3334 // descriptions that follow.
3335 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3336
3337 if (!RD->getNumBases())
3338 return;
3339
David Majnemere2cb8d12014-07-07 06:20:47 +00003340 // Now add the base class descriptions.
3341
3342 // Itanium C++ ABI 2.9.5p6c:
3343 // __base_info[] is an array of base class descriptions -- one for every
3344 // direct proper base. Each description is of the type:
3345 //
3346 // struct abi::__base_class_type_info {
3347 // public:
3348 // const __class_type_info *__base_type;
3349 // long __offset_flags;
3350 //
3351 // enum __offset_flags_masks {
3352 // __virtual_mask = 0x1,
3353 // __public_mask = 0x2,
3354 // __offset_shift = 8
3355 // };
3356 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003357
3358 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3359 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3360 // LLP64 platforms.
3361 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3362 // LLP64 platforms.
3363 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3364 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3365 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3366 OffsetFlagsTy = CGM.getContext().LongLongTy;
3367 llvm::Type *OffsetFlagsLTy =
3368 CGM.getTypes().ConvertType(OffsetFlagsTy);
3369
David Majnemere2cb8d12014-07-07 06:20:47 +00003370 for (const auto &Base : RD->bases()) {
3371 // The __base_type member points to the RTTI for the base type.
3372 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3373
3374 const CXXRecordDecl *BaseDecl =
3375 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3376
3377 int64_t OffsetFlags = 0;
3378
3379 // All but the lower 8 bits of __offset_flags are a signed offset.
3380 // For a non-virtual base, this is the offset in the object of the base
3381 // subobject. For a virtual base, this is the offset in the virtual table of
3382 // the virtual base offset for the virtual base referenced (negative).
3383 CharUnits Offset;
3384 if (Base.isVirtual())
3385 Offset =
3386 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3387 else {
3388 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3389 Offset = Layout.getBaseClassOffset(BaseDecl);
3390 };
3391
3392 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3393
3394 // The low-order byte of __offset_flags contains flags, as given by the
3395 // masks from the enumeration __offset_flags_masks.
3396 if (Base.isVirtual())
3397 OffsetFlags |= BCTI_Virtual;
3398 if (Base.getAccessSpecifier() == AS_public)
3399 OffsetFlags |= BCTI_Public;
3400
Reid Klecknerd8b04662016-08-25 22:16:30 +00003401 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003402 }
3403}
3404
Richard Smitha7d93782016-12-01 03:32:42 +00003405/// Compute the flags for a __pbase_type_info, and remove the corresponding
3406/// pieces from \p Type.
3407static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3408 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003409
Richard Smitha7d93782016-12-01 03:32:42 +00003410 if (Type.isConstQualified())
3411 Flags |= ItaniumRTTIBuilder::PTI_Const;
3412 if (Type.isVolatileQualified())
3413 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3414 if (Type.isRestrictQualified())
3415 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3416 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003417
3418 // Itanium C++ ABI 2.9.5p7:
3419 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3420 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003421 if (ContainsIncompleteClassType(Type))
3422 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3423
3424 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3425 if (Proto->isNothrow(Ctx)) {
3426 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
3427 Type = Ctx.getFunctionType(
3428 Proto->getReturnType(), Proto->getParamTypes(),
3429 Proto->getExtProtoInfo().withExceptionSpec(EST_None));
3430 }
3431 }
3432
3433 return Flags;
3434}
3435
3436/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3437/// used for pointer types.
3438void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3439 // Itanium C++ ABI 2.9.5p7:
3440 // __flags is a flag word describing the cv-qualification and other
3441 // attributes of the type pointed to
3442 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003443
3444 llvm::Type *UnsignedIntLTy =
3445 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3446 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3447
3448 // Itanium C++ ABI 2.9.5p7:
3449 // __pointee is a pointer to the std::type_info derivation for the
3450 // unqualified type being pointed to.
3451 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003452 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003453 Fields.push_back(PointeeTypeInfo);
3454}
3455
3456/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3457/// struct, used for member pointer types.
3458void
3459ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3460 QualType PointeeTy = Ty->getPointeeType();
3461
David Majnemere2cb8d12014-07-07 06:20:47 +00003462 // Itanium C++ ABI 2.9.5p7:
3463 // __flags is a flag word describing the cv-qualification and other
3464 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003465 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003466
3467 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003468 if (IsIncompleteClassType(ClassType))
3469 Flags |= PTI_ContainingClassIncomplete;
3470
3471 llvm::Type *UnsignedIntLTy =
3472 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3473 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3474
3475 // Itanium C++ ABI 2.9.5p7:
3476 // __pointee is a pointer to the std::type_info derivation for the
3477 // unqualified type being pointed to.
3478 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003479 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003480 Fields.push_back(PointeeTypeInfo);
3481
3482 // Itanium C++ ABI 2.9.5p9:
3483 // __context is a pointer to an abi::__class_type_info corresponding to the
3484 // class type containing the member pointed to
3485 // (e.g., the "A" in "int A::*").
3486 Fields.push_back(
3487 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3488}
3489
David Majnemer443250f2015-03-17 20:35:00 +00003490llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003491 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3492}
3493
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003494void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3495 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003496 QualType PointerType = getContext().getPointerType(Type);
3497 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003498 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3499 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3500 DLLExport);
3501 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3502 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003503}
3504
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003505void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003506 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003507 QualType FundamentalTypes[] = {
3508 getContext().VoidTy, getContext().NullPtrTy,
3509 getContext().BoolTy, getContext().WCharTy,
3510 getContext().CharTy, getContext().UnsignedCharTy,
3511 getContext().SignedCharTy, getContext().ShortTy,
3512 getContext().UnsignedShortTy, getContext().IntTy,
3513 getContext().UnsignedIntTy, getContext().LongTy,
3514 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003515 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3516 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003517 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003518 getContext().LongDoubleTy, getContext().Float128Ty,
3519 getContext().Char16Ty, getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003520 };
3521 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003522 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003523}
3524
3525/// What sort of uniqueness rules should we use for the RTTI for the
3526/// given type?
3527ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3528 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3529 if (shouldRTTIBeUnique())
3530 return RUK_Unique;
3531
3532 // It's only necessary for linkonce_odr or weak_odr linkage.
3533 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3534 Linkage != llvm::GlobalValue::WeakODRLinkage)
3535 return RUK_Unique;
3536
3537 // It's only necessary with default visibility.
3538 if (CanTy->getVisibility() != DefaultVisibility)
3539 return RUK_Unique;
3540
3541 // If we're not required to publish this symbol, hide it.
3542 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3543 return RUK_NonUniqueHidden;
3544
3545 // If we're required to publish this symbol, as we might be under an
3546 // explicit instantiation, leave it with default visibility but
3547 // enable string-comparisons.
3548 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3549 return RUK_NonUniqueVisible;
3550}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003551
Rafael Espindola1e4df922014-09-16 15:18:21 +00003552// Find out how to codegen the complete destructor and constructor
3553namespace {
3554enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3555}
3556static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3557 const CXXMethodDecl *MD) {
3558 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3559 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003560
Rafael Espindola1e4df922014-09-16 15:18:21 +00003561 // The complete and base structors are not equivalent if there are any virtual
3562 // bases, so emit separate functions.
3563 if (MD->getParent()->getNumVBases())
3564 return StructorCodegen::Emit;
3565
3566 GlobalDecl AliasDecl;
3567 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3568 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3569 } else {
3570 const auto *CD = cast<CXXConstructorDecl>(MD);
3571 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3572 }
3573 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3574
3575 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3576 return StructorCodegen::RAUW;
3577
3578 // FIXME: Should we allow available_externally aliases?
3579 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3580 return StructorCodegen::RAUW;
3581
Rafael Espindola0806f982014-09-16 20:19:43 +00003582 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003583 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3584 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3585 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003586 return StructorCodegen::COMDAT;
3587 return StructorCodegen::Emit;
3588 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003589
3590 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003591}
3592
Rafael Espindola1e4df922014-09-16 15:18:21 +00003593static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3594 GlobalDecl AliasDecl,
3595 GlobalDecl TargetDecl) {
3596 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3597
3598 StringRef MangledName = CGM.getMangledName(AliasDecl);
3599 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3600 if (Entry && !Entry->isDeclaration())
3601 return;
3602
3603 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003604
3605 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003606 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003607
3608 // Switch any previous uses to the alias.
3609 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003610 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003611 "declaration exists with different type");
3612 Alias->takeName(Entry);
3613 Entry->replaceAllUsesWith(Alias);
3614 Entry->eraseFromParent();
3615 } else {
3616 Alias->setName(MangledName);
3617 }
3618
3619 // Finally, set up the alias with its proper name and attributes.
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00003620 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003621}
3622
3623void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3624 StructorType Type) {
3625 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3626 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3627
3628 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3629
3630 if (Type == StructorType::Complete) {
3631 GlobalDecl CompleteDecl;
3632 GlobalDecl BaseDecl;
3633 if (CD) {
3634 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3635 BaseDecl = GlobalDecl(CD, Ctor_Base);
3636 } else {
3637 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3638 BaseDecl = GlobalDecl(DD, Dtor_Base);
3639 }
3640
3641 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3642 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3643 return;
3644 }
3645
3646 if (CGType == StructorCodegen::RAUW) {
3647 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003648 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003649 CGM.addReplacement(MangledName, Aliasee);
3650 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003651 }
3652 }
3653
3654 // The base destructor is equivalent to the base destructor of its
3655 // base class if there is exactly one non-virtual base class with a
3656 // non-trivial destructor, there are no fields with a non-trivial
3657 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003658 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3659 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003660 return;
3661
Rafael Espindola1e4df922014-09-16 15:18:21 +00003662 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003663
Rafael Espindola1e4df922014-09-16 15:18:21 +00003664 if (CGType == StructorCodegen::COMDAT) {
3665 SmallString<256> Buffer;
3666 llvm::raw_svector_ostream Out(Buffer);
3667 if (DD)
3668 getMangleContext().mangleCXXDtorComdat(DD, Out);
3669 else
3670 getMangleContext().mangleCXXCtorComdat(CD, Out);
3671 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3672 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003673 } else {
3674 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003675 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003676}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003677
3678static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3679 // void *__cxa_begin_catch(void*);
3680 llvm::FunctionType *FTy = llvm::FunctionType::get(
3681 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3682
3683 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3684}
3685
3686static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3687 // void __cxa_end_catch();
3688 llvm::FunctionType *FTy =
3689 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3690
3691 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3692}
3693
3694static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3695 // void *__cxa_get_exception_ptr(void*);
3696 llvm::FunctionType *FTy = llvm::FunctionType::get(
3697 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3698
3699 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3700}
3701
3702namespace {
3703 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3704 /// exception type lets us state definitively that the thrown exception
3705 /// type does not have a destructor. In particular:
3706 /// - Catch-alls tell us nothing, so we have to conservatively
3707 /// assume that the thrown exception might have a destructor.
3708 /// - Catches by reference behave according to their base types.
3709 /// - Catches of non-record types will only trigger for exceptions
3710 /// of non-record types, which never have destructors.
3711 /// - Catches of record types can trigger for arbitrary subclasses
3712 /// of the caught type, so we have to assume the actual thrown
3713 /// exception type might have a throwing destructor, even if the
3714 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003715 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003716 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3717 bool MightThrow;
3718
3719 void Emit(CodeGenFunction &CGF, Flags flags) override {
3720 if (!MightThrow) {
3721 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3722 return;
3723 }
3724
3725 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3726 }
3727 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003728}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003729
3730/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3731/// __cxa_end_catch.
3732///
3733/// \param EndMightThrow - true if __cxa_end_catch might throw
3734static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3735 llvm::Value *Exn,
3736 bool EndMightThrow) {
3737 llvm::CallInst *call =
3738 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3739
3740 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3741
3742 return call;
3743}
3744
3745/// A "special initializer" callback for initializing a catch
3746/// parameter during catch initialization.
3747static void InitCatchParam(CodeGenFunction &CGF,
3748 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003749 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003750 SourceLocation Loc) {
3751 // Load the exception from where the landing pad saved it.
3752 llvm::Value *Exn = CGF.getExceptionFromSlot();
3753
3754 CanQualType CatchType =
3755 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3756 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3757
3758 // If we're catching by reference, we can just cast the object
3759 // pointer to the appropriate pointer.
3760 if (isa<ReferenceType>(CatchType)) {
3761 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3762 bool EndCatchMightThrow = CaughtType->isRecordType();
3763
3764 // __cxa_begin_catch returns the adjusted object pointer.
3765 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3766
3767 // We have no way to tell the personality function that we're
3768 // catching by reference, so if we're catching a pointer,
3769 // __cxa_begin_catch will actually return that pointer by value.
3770 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3771 QualType PointeeType = PT->getPointeeType();
3772
3773 // When catching by reference, generally we should just ignore
3774 // this by-value pointer and use the exception object instead.
3775 if (!PointeeType->isRecordType()) {
3776
3777 // Exn points to the struct _Unwind_Exception header, which
3778 // we have to skip past in order to reach the exception data.
3779 unsigned HeaderSize =
3780 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3781 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3782
3783 // However, if we're catching a pointer-to-record type that won't
3784 // work, because the personality function might have adjusted
3785 // the pointer. There's actually no way for us to fully satisfy
3786 // the language/ABI contract here: we can't use Exn because it
3787 // might have the wrong adjustment, but we can't use the by-value
3788 // pointer because it's off by a level of abstraction.
3789 //
3790 // The current solution is to dump the adjusted pointer into an
3791 // alloca, which breaks language semantics (because changing the
3792 // pointer doesn't change the exception) but at least works.
3793 // The better solution would be to filter out non-exact matches
3794 // and rethrow them, but this is tricky because the rethrow
3795 // really needs to be catchable by other sites at this landing
3796 // pad. The best solution is to fix the personality function.
3797 } else {
3798 // Pull the pointer for the reference type off.
3799 llvm::Type *PtrTy =
3800 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3801
3802 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003803 Address ExnPtrTmp =
3804 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003805 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3806 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3807
3808 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003809 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003810 }
3811 }
3812
3813 llvm::Value *ExnCast =
3814 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3815 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3816 return;
3817 }
3818
3819 // Scalars and complexes.
3820 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3821 if (TEK != TEK_Aggregate) {
3822 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3823
3824 // If the catch type is a pointer type, __cxa_begin_catch returns
3825 // the pointer by value.
3826 if (CatchType->hasPointerRepresentation()) {
3827 llvm::Value *CastExn =
3828 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3829
3830 switch (CatchType.getQualifiers().getObjCLifetime()) {
3831 case Qualifiers::OCL_Strong:
3832 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3833 // fallthrough
3834
3835 case Qualifiers::OCL_None:
3836 case Qualifiers::OCL_ExplicitNone:
3837 case Qualifiers::OCL_Autoreleasing:
3838 CGF.Builder.CreateStore(CastExn, ParamAddr);
3839 return;
3840
3841 case Qualifiers::OCL_Weak:
3842 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3843 return;
3844 }
3845 llvm_unreachable("bad ownership qualifier!");
3846 }
3847
3848 // Otherwise, it returns a pointer into the exception object.
3849
3850 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3851 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3852
3853 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003854 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003855 switch (TEK) {
3856 case TEK_Complex:
3857 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3858 /*init*/ true);
3859 return;
3860 case TEK_Scalar: {
3861 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3862 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3863 return;
3864 }
3865 case TEK_Aggregate:
3866 llvm_unreachable("evaluation kind filtered out!");
3867 }
3868 llvm_unreachable("bad evaluation kind");
3869 }
3870
3871 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003872 auto catchRD = CatchType->getAsCXXRecordDecl();
3873 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003874
3875 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3876
3877 // Check for a copy expression. If we don't have a copy expression,
3878 // that means a trivial copy is okay.
3879 const Expr *copyExpr = CatchParam.getInit();
3880 if (!copyExpr) {
3881 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003882 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3883 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003884 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3885 return;
3886 }
3887
3888 // We have to call __cxa_get_exception_ptr to get the adjusted
3889 // pointer before copying.
3890 llvm::CallInst *rawAdjustedExn =
3891 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3892
3893 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003894 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3895 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003896
3897 // The copy expression is defined in terms of an OpaqueValueExpr.
3898 // Find it and map it to the adjusted expression.
3899 CodeGenFunction::OpaqueValueMapping
3900 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3901 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3902
3903 // Call the copy ctor in a terminate scope.
3904 CGF.EHStack.pushTerminate();
3905
3906 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003907 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003908 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003909 AggValueSlot::IsNotDestructed,
3910 AggValueSlot::DoesNotNeedGCBarriers,
3911 AggValueSlot::IsNotAliased));
3912
3913 // Leave the terminate scope.
3914 CGF.EHStack.popTerminate();
3915
3916 // Undo the opaque value mapping.
3917 opaque.pop();
3918
3919 // Finally we can call __cxa_begin_catch.
3920 CallBeginCatch(CGF, Exn, true);
3921}
3922
3923/// Begins a catch statement by initializing the catch variable and
3924/// calling __cxa_begin_catch.
3925void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3926 const CXXCatchStmt *S) {
3927 // We have to be very careful with the ordering of cleanups here:
3928 // C++ [except.throw]p4:
3929 // The destruction [of the exception temporary] occurs
3930 // immediately after the destruction of the object declared in
3931 // the exception-declaration in the handler.
3932 //
3933 // So the precise ordering is:
3934 // 1. Construct catch variable.
3935 // 2. __cxa_begin_catch
3936 // 3. Enter __cxa_end_catch cleanup
3937 // 4. Enter dtor cleanup
3938 //
3939 // We do this by using a slightly abnormal initialization process.
3940 // Delegation sequence:
3941 // - ExitCXXTryStmt opens a RunCleanupsScope
3942 // - EmitAutoVarAlloca creates the variable and debug info
3943 // - InitCatchParam initializes the variable from the exception
3944 // - CallBeginCatch calls __cxa_begin_catch
3945 // - CallBeginCatch enters the __cxa_end_catch cleanup
3946 // - EmitAutoVarCleanups enters the variable destructor cleanup
3947 // - EmitCXXTryStmt emits the code for the catch body
3948 // - EmitCXXTryStmt close the RunCleanupsScope
3949
3950 VarDecl *CatchParam = S->getExceptionDecl();
3951 if (!CatchParam) {
3952 llvm::Value *Exn = CGF.getExceptionFromSlot();
3953 CallBeginCatch(CGF, Exn, true);
3954 return;
3955 }
3956
3957 // Emit the local.
3958 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3959 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3960 CGF.EmitAutoVarCleanups(var);
3961}
3962
3963/// Get or define the following function:
3964/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3965/// This code is used only in C++.
3966static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3967 llvm::FunctionType *fnTy =
3968 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00003969 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
3970 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003971
3972 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3973 if (fn && fn->empty()) {
3974 fn->setDoesNotThrow();
3975 fn->setDoesNotReturn();
3976
3977 // What we really want is to massively penalize inlining without
3978 // forbidding it completely. The difference between that and
3979 // 'noinline' is negligible.
3980 fn->addFnAttr(llvm::Attribute::NoInline);
3981
3982 // Allow this function to be shared across translation units, but
3983 // we don't want it to turn into an exported symbol.
3984 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3985 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003986 if (CGM.supportsCOMDAT())
3987 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003988
3989 // Set up the function.
3990 llvm::BasicBlock *entry =
3991 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00003992 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003993
3994 // Pull the exception pointer out of the parameter list.
3995 llvm::Value *exn = &*fn->arg_begin();
3996
3997 // Call __cxa_begin_catch(exn).
3998 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3999 catchCall->setDoesNotThrow();
4000 catchCall->setCallingConv(CGM.getRuntimeCC());
4001
4002 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004003 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004004 termCall->setDoesNotThrow();
4005 termCall->setDoesNotReturn();
4006 termCall->setCallingConv(CGM.getRuntimeCC());
4007
4008 // std::terminate cannot return.
4009 builder.CreateUnreachable();
4010 }
4011
4012 return fnRef;
4013}
4014
4015llvm::CallInst *
4016ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4017 llvm::Value *Exn) {
4018 // In C++, we want to call __cxa_begin_catch() before terminating.
4019 if (Exn) {
4020 assert(CGF.CGM.getLangOpts().CPlusPlus);
4021 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4022 }
4023 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4024}