blob: a12f08fbe9a302d1dd0cb6f87e5b3a8c618564f6 [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Charles Davis4e786dd2010-05-25 19:52:27 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattner57540c52011-04-15 05:22:18 +00009// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000010// in this file generates structures that follow the Itanium C++ ABI, which is
11// documented at:
12// http://www.codesourcery.com/public/cxx-abi/abi.html
13// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000014//
15// It also supports the closely-related ARM ABI, documented at:
16// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
17//
Charles Davis4e786dd2010-05-25 19:52:27 +000018//===----------------------------------------------------------------------===//
19
20#include "CGCXXABI.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000021#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000022#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000023#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000024#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000025#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000026#include "TargetInfo.h"
John McCall5ad74072017-03-02 20:04:19 +000027#include "clang/CodeGen/ConstantInitBuilder.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000028#include "clang/AST/Mangle.h"
29#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000030#include "clang/AST/StmtCXX.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
Thomas Andersonb6d87cf2018-07-24 00:43:47 +000032#include "llvm/IR/GlobalValue.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000033#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Value.h"
Akira Hatanaka617e2612018-04-17 18:41:52 +000036#include "llvm/Support/ScopedPrinter.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 {
Richard Smith96cd6712017-08-16 01:49:53 +000066 // If C++ prohibits us from making a copy, pass by address.
Reid Kleckneradb41982019-04-30 22:23:20 +000067 if (!RD->canPassInRegisters())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068 return RAA_Indirect;
69 return RAA_Default;
70 }
71
John McCall7f416cc2015-09-08 08:05:57 +000072 bool isThisCompleteObject(GlobalDecl GD) const override {
73 // The Itanium ABI has separate complete-object vs. base-object
74 // variants of both constructors and destructors.
75 if (isa<CXXDestructorDecl>(GD.getDecl())) {
76 switch (GD.getDtorType()) {
77 case Dtor_Complete:
78 case Dtor_Deleting:
79 return true;
80
81 case Dtor_Base:
82 return false;
83
84 case Dtor_Comdat:
85 llvm_unreachable("emitting dtor comdat as function?");
86 }
87 llvm_unreachable("bad dtor kind");
88 }
89 if (isa<CXXConstructorDecl>(GD.getDecl())) {
90 switch (GD.getCtorType()) {
91 case Ctor_Complete:
92 return true;
93
94 case Ctor_Base:
95 return false;
96
97 case Ctor_CopyingClosure:
98 case Ctor_DefaultClosure:
99 llvm_unreachable("closure ctors in Itanium ABI?");
100
101 case Ctor_Comdat:
102 llvm_unreachable("emitting ctor comdat as function?");
103 }
104 llvm_unreachable("bad dtor kind");
105 }
106
107 // No other kinds.
108 return false;
109 }
110
Craig Topper4f12f102014-03-12 06:41:41 +0000111 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000112
Craig Topper4f12f102014-03-12 06:41:41 +0000113 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000114
John McCallb92ab1a2016-10-26 23:46:34 +0000115 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000116 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
117 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000118 Address This,
119 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000120 llvm::Value *MemFnPtr,
121 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000122
Craig Topper4f12f102014-03-12 06:41:41 +0000123 llvm::Value *
124 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000125 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000126 llvm::Value *MemPtr,
127 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000128
John McCall7a9aac22010-08-23 01:21:21 +0000129 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
130 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000132 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000133 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000134
Craig Topper4f12f102014-03-12 06:41:41 +0000135 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000136
David Majnemere2be95b2015-06-23 07:31:01 +0000137 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000138 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000139 CharUnits offset) override;
140 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000141 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
142 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000143
John McCall7a9aac22010-08-23 01:21:21 +0000144 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000145 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000146 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000147 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000148
John McCall7a9aac22010-08-23 01:21:21 +0000149 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 llvm::Value *Addr,
151 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000152
David Majnemer08681372014-11-01 07:37:17 +0000153 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000154 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000155 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000156
David Majnemer442d0a22014-11-25 07:20:20 +0000157 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000158 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000159
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000160 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
161
162 llvm::CallInst *
163 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
164 llvm::Value *Exn) override;
165
Thomas Andersonb6d87cf2018-07-24 00:43:47 +0000166 void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
David Majnemer443250f2015-03-17 20:35:00 +0000167 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000168 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000169 getAddrOfCXXCatchHandlerType(QualType Ty,
170 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000171 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000172 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000173
David Majnemer1162d252014-06-22 19:05:33 +0000174 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
175 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
176 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000177 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000178 llvm::Type *StdTypeInfoPtrTy) override;
179
180 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
181 QualType SrcRecordTy) override;
182
John McCall7f416cc2015-09-08 08:05:57 +0000183 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000184 QualType SrcRecordTy, QualType DestTy,
185 QualType DestRecordTy,
186 llvm::BasicBlock *CastEnd) override;
187
John McCall7f416cc2015-09-08 08:05:57 +0000188 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000189 QualType SrcRecordTy,
190 QualType DestTy) override;
191
192 bool EmitBadCastCall(CodeGenFunction &CGF) override;
193
Craig Topper4f12f102014-03-12 06:41:41 +0000194 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000195 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000196 const CXXRecordDecl *ClassDecl,
197 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000198
Craig Topper4f12f102014-03-12 06:41:41 +0000199 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000200
George Burgess IVf203dbf2017-02-22 20:28:02 +0000201 AddedStructorArgs
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000202 buildStructorSignature(GlobalDecl GD,
George Burgess IVf203dbf2017-02-22 20:28:02 +0000203 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000204
Reid Klecknere7de47e2013-07-22 13:51:44 +0000205 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000206 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000207 // Itanium does not emit any destructor variant as an inline thunk.
208 // Delegating may occur as an optimization, but all variants are either
209 // emitted with external linkage or as linkonce if they are inline and used.
210 return false;
211 }
212
Craig Topper4f12f102014-03-12 06:41:41 +0000213 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000214
Reid Kleckner89077a12013-12-17 19:46:40 +0000215 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000216 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000217
Craig Topper4f12f102014-03-12 06:41:41 +0000218 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000219
George Burgess IVf203dbf2017-02-22 20:28:02 +0000220 AddedStructorArgs
221 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
222 CXXCtorType Type, bool ForVirtualBase,
223 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000224
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000225 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
226 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000227 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000228
Craig Topper4f12f102014-03-12 06:41:41 +0000229 void emitVTableDefinitions(CodeGenVTables &CGVT,
230 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000231
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000232 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
233 CodeGenFunction::VPtr Vptr) override;
234
235 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
236 return true;
237 }
238
239 llvm::Constant *
240 getVTableAddressPoint(BaseSubobject Base,
241 const CXXRecordDecl *VTableClass) override;
242
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000243 llvm::Value *getVTableAddressPointInStructor(
244 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000245 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
246
247 llvm::Value *getVTableAddressPointInStructorWithVTT(
248 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
249 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000250
251 llvm::Constant *
252 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000253 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000254
255 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000256 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000257
John McCall9831b842018-02-06 18:52:44 +0000258 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
259 Address This, llvm::Type *Ty,
260 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000261
David Majnemer0c0b6d92014-10-31 20:09:12 +0000262 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
263 const CXXDestructorDecl *Dtor,
264 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000265 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000266 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000267
Craig Topper4f12f102014-03-12 06:41:41 +0000268 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000269
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000270 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Richard Smithc195c252018-11-27 19:33:49 +0000271 bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000272
Hans Wennborgc94391d2014-06-06 20:04:01 +0000273 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
274 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000275 // Allow inlining of thunks by emitting them with available_externally
276 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000277 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000278 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Rafael Espindolab7350042018-03-01 00:35:47 +0000279 CGM.setGVProperties(Thunk, GD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000280 }
281
Rafael Espindolab7350042018-03-01 00:35:47 +0000282 bool exportThunk() override { return true; }
283
John McCall7f416cc2015-09-08 08:05:57 +0000284 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000285 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000286
John McCall7f416cc2015-09-08 08:05:57 +0000287 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000288 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000289
David Majnemer196ac332014-09-11 23:05:02 +0000290 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
291 FunctionArgList &Args) const override {
292 assert(!Args.empty() && "expected the arglist to not be empty!");
293 return Args.size() - 1;
294 }
295
Craig Topper4f12f102014-03-12 06:41:41 +0000296 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
297 StringRef GetDeletedVirtualCallName() override
298 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000299
Craig Topper4f12f102014-03-12 06:41:41 +0000300 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000301 Address InitializeArrayCookie(CodeGenFunction &CGF,
302 Address NewPtr,
303 llvm::Value *NumElements,
304 const CXXNewExpr *expr,
305 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000306 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000307 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000308 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000309
John McCallcdf7ef52010-11-06 09:44:32 +0000310 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000311 llvm::GlobalVariable *DeclPtr,
312 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000313 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
James Y Knightf7321542019-02-07 01:14:17 +0000314 llvm::FunctionCallee dtor,
315 llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000316
317 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000318 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000319 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000320 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000321 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000322 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000323 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000324
325 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000326 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
327 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000328
Craig Topper4f12f102014-03-12 06:41:41 +0000329 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000330
331 /**************************** RTTI Uniqueness ******************************/
332
333protected:
334 /// Returns true if the ABI requires RTTI type_info objects to be unique
335 /// across a program.
336 virtual bool shouldRTTIBeUnique() const { return true; }
337
338public:
339 /// What sort of unique-RTTI behavior should we use?
340 enum RTTIUniquenessKind {
341 /// We are guaranteeing, or need to guarantee, that the RTTI string
342 /// is unique.
343 RUK_Unique,
344
345 /// We are not guaranteeing uniqueness for the RTTI string, so we
346 /// can demote to hidden visibility but must use string comparisons.
347 RUK_NonUniqueHidden,
348
349 /// We are not guaranteeing uniqueness for the RTTI string, so we
350 /// have to use string comparisons, but we also have to emit it with
351 /// non-hidden visibility.
352 RUK_NonUniqueVisible
353 };
354
355 /// Return the required visibility status for the given type and linkage in
356 /// the current ABI.
357 RTTIUniquenessKind
358 classifyRTTIUniqueness(QualType CanTy,
359 llvm::GlobalValue::LinkageTypes Linkage) const;
360 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000361
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000362 void emitCXXStructor(GlobalDecl GD) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000363
Peter Collingbourne60108802017-12-13 21:53:04 +0000364 std::pair<llvm::Value *, const CXXRecordDecl *>
365 LoadVTablePtr(CodeGenFunction &CGF, Address This,
366 const CXXRecordDecl *RD) override;
367
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000368 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000369 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
370 const auto &VtableLayout =
371 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000372
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000373 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
374 // Skip empty slot.
375 if (!VtableComponent.isUsedFunctionPointerKind())
376 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000377
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000378 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
379 if (!Method->getCanonicalDecl()->isInlined())
380 continue;
381
382 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
383 auto *Entry = CGM.GetGlobalValue(Name);
384 // This checks if virtual inline function has already been emitted.
385 // Note that it is possible that this inline function would be emitted
386 // after trying to emit vtable speculatively. Because of this we do
387 // an extra pass after emitting all deferred vtables to find and emit
388 // these vtables opportunistically.
389 if (!Entry || Entry->isDeclaration())
390 return true;
391 }
392 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000393 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000394
395 bool isVTableHidden(const CXXRecordDecl *RD) const {
396 const auto &VtableLayout =
397 CGM.getItaniumVTableContext().getVTableLayout(RD);
398
399 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
400 if (VtableComponent.isRTTIKind()) {
401 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
402 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
403 return true;
404 } else if (VtableComponent.isUsedFunctionPointerKind()) {
405 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
406 if (Method->getVisibility() == Visibility::HiddenVisibility &&
407 !Method->isDefined())
408 return true;
409 }
410 }
411 return false;
412 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000413};
John McCall86353412010-08-21 22:46:04 +0000414
415class ARMCXXABI : public ItaniumCXXABI {
416public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000417 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
418 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
419 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000420
Craig Topper4f12f102014-03-12 06:41:41 +0000421 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000422 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
423 isa<CXXDestructorDecl>(GD.getDecl()) &&
424 GD.getDtorType() != Dtor_Deleting));
425 }
John McCall5d865c322010-08-31 07:33:07 +0000426
Craig Topper4f12f102014-03-12 06:41:41 +0000427 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
428 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000429
Craig Topper4f12f102014-03-12 06:41:41 +0000430 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000431 Address InitializeArrayCookie(CodeGenFunction &CGF,
432 Address NewPtr,
433 llvm::Value *NumElements,
434 const CXXNewExpr *expr,
435 QualType ElementType) override;
436 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000437 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000438};
Tim Northovera2ee4332014-03-29 15:09:45 +0000439
440class iOS64CXXABI : public ARMCXXABI {
441public:
John McCalld23b27e2016-09-16 02:40:45 +0000442 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
443 Use32BitVTableOffsetABI = true;
444 }
Tim Northover65f582f2014-03-30 17:32:48 +0000445
446 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000447 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000448};
Dan Gohmanc2853072015-09-03 22:51:53 +0000449
450class WebAssemblyCXXABI final : public ItaniumCXXABI {
451public:
452 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
453 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
454 /*UseARMGuardVarABI=*/true) {}
Heejin Ahnc6479192018-05-31 22:18:13 +0000455 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000456
457private:
458 bool HasThisReturn(GlobalDecl GD) const override {
459 return isa<CXXConstructorDecl>(GD.getDecl()) ||
460 (isa<CXXDestructorDecl>(GD.getDecl()) &&
461 GD.getDtorType() != Dtor_Deleting);
462 }
Derek Schuff8179be42016-05-10 17:44:55 +0000463 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000464};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000465}
Charles Davis4e786dd2010-05-25 19:52:27 +0000466
Charles Davis53c59df2010-08-16 03:33:14 +0000467CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000468 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000469 // For IR-generation purposes, there's no significant difference
470 // between the ARM and iOS ABIs.
471 case TargetCXXABI::GenericARM:
472 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000473 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000474 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000475
Tim Northovera2ee4332014-03-29 15:09:45 +0000476 case TargetCXXABI::iOS64:
477 return new iOS64CXXABI(CGM);
478
Tim Northover9bb857a2013-01-31 12:13:10 +0000479 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
480 // include the other 32-bit ARM oddities: constructor/destructor return values
481 // and array cookies.
482 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000483 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
484 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000485
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000486 case TargetCXXABI::GenericMIPS:
487 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
488
Dan Gohmanc2853072015-09-03 22:51:53 +0000489 case TargetCXXABI::WebAssembly:
490 return new WebAssemblyCXXABI(CGM);
491
John McCall57625922013-01-25 23:36:14 +0000492 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000493 if (CGM.getContext().getTargetInfo().getTriple().getArch()
494 == llvm::Triple::le32) {
495 // For PNaCl, use ARM-style method pointers so that PNaCl code
496 // does not assume anything about the alignment of function
497 // pointers.
498 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
499 /* UseARMGuardVarABI = */ false);
500 }
John McCall57625922013-01-25 23:36:14 +0000501 return new ItaniumCXXABI(CGM);
502
503 case TargetCXXABI::Microsoft:
504 llvm_unreachable("Microsoft ABI is not Itanium-based");
505 }
506 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000507}
508
Chris Lattnera5f58b02011-07-09 17:41:47 +0000509llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000510ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
511 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000512 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000513 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000514}
515
John McCalld9c6c0b2010-08-22 00:59:17 +0000516/// In the Itanium and ARM ABIs, method pointers have the form:
517/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
518///
519/// In the Itanium ABI:
520/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
521/// - the this-adjustment is (memptr.adj)
522/// - the virtual offset is (memptr.ptr - 1)
523///
524/// In the ARM ABI:
525/// - method pointers are virtual if (memptr.adj & 1) is nonzero
526/// - the this-adjustment is (memptr.adj >> 1)
527/// - the virtual offset is (memptr.ptr)
528/// ARM uses 'adj' for the virtual flag because Thumb functions
529/// may be only single-byte aligned.
530///
531/// If the member is virtual, the adjusted 'this' pointer points
532/// to a vtable pointer from which the virtual offset is applied.
533///
534/// If the member is non-virtual, memptr.ptr is the address of
535/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000536CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000537 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
538 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000539 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000540 CGBuilderTy &Builder = CGF.Builder;
541
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000542 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000543 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000544 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000545 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
546
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000547 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
548 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000549
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000550 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000551
John McCalld9c6c0b2010-08-22 00:59:17 +0000552 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
553 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
554 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
555
John McCalla1dee5302010-08-22 10:59:02 +0000556 // Extract memptr.adj, which is in the second field.
557 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000558
559 // Compute the true adjustment.
560 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000561 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000562 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000563
564 // Apply the adjustment and cast back to the original struct type
565 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000566 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000567 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
568 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
569 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000570 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000571
John McCall475999d2010-08-22 00:05:51 +0000572 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000573 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000574
John McCall475999d2010-08-22 00:05:51 +0000575 // If the LSB in the function pointer is 1, the function pointer points to
576 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000577 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000578 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000579 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
580 else
581 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
582 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000583 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
584
585 // In the virtual path, the adjustment left 'This' pointing to the
586 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000587 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000588 CGF.EmitBlock(FnVirtual);
589
590 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000591 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000592 CharUnits VTablePtrAlign =
593 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
594 CGF.getPointerAlign());
595 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000596 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000597
598 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000599 // On ARM64, to reserve extra space in virtual member function pointers,
600 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000601 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000602 if (!UseARMMethodPtrABI)
603 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000604 if (Use32BitVTableOffsetABI) {
605 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
606 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
607 }
Peter Collingbournee44acad2018-06-26 02:15:47 +0000608 // Compute the address of the virtual function pointer.
609 llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset);
610
611 // Check the address of the function pointer if CFI on member function
612 // pointers is enabled.
613 llvm::Constant *CheckSourceLocation;
614 llvm::Constant *CheckTypeDesc;
615 bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
616 CGM.HasHiddenLTOVisibility(RD);
617 if (ShouldEmitCFICheck) {
618 CodeGenFunction::SanitizerScope SanScope(&CGF);
619
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000620 CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
Peter Collingbournee44acad2018-06-26 02:15:47 +0000621 CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
622 llvm::Constant *StaticData[] = {
623 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
624 CheckSourceLocation,
625 CheckTypeDesc,
626 };
627
628 llvm::Metadata *MD =
629 CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
630 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
631
632 llvm::Value *TypeTest = Builder.CreateCall(
633 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VFPAddr, TypeId});
634
635 if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
636 CGF.EmitTrapCheck(TypeTest);
637 } else {
638 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
639 CGM.getLLVMContext(),
640 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
641 llvm::Value *ValidVtable = Builder.CreateCall(
642 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
643 CGF.EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIMFCall),
644 SanitizerHandler::CFICheckFail, StaticData,
645 {VTable, ValidVtable});
646 }
647
648 FnVirtual = Builder.GetInsertBlock();
649 }
John McCall475999d2010-08-22 00:05:51 +0000650
651 // Load the virtual function to call.
Peter Collingbournee44acad2018-06-26 02:15:47 +0000652 VFPAddr = Builder.CreateBitCast(VFPAddr, FTy->getPointerTo()->getPointerTo());
653 llvm::Value *VirtualFn = Builder.CreateAlignedLoad(
654 VFPAddr, CGF.getPointerAlign(), "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000655 CGF.EmitBranch(FnEnd);
656
657 // In the non-virtual path, the function pointer is actually a
658 // function pointer.
659 CGF.EmitBlock(FnNonVirtual);
660 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000661 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000662
Peter Collingbournee44acad2018-06-26 02:15:47 +0000663 // Check the function pointer if CFI on member function pointers is enabled.
664 if (ShouldEmitCFICheck) {
665 CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
666 if (RD->hasDefinition()) {
667 CodeGenFunction::SanitizerScope SanScope(&CGF);
668
669 llvm::Constant *StaticData[] = {
670 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
671 CheckSourceLocation,
672 CheckTypeDesc,
673 };
674
675 llvm::Value *Bit = Builder.getFalse();
676 llvm::Value *CastedNonVirtualFn =
677 Builder.CreateBitCast(NonVirtualFn, CGF.Int8PtrTy);
678 for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
679 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
680 getContext().getMemberPointerType(
681 MPT->getPointeeType(),
682 getContext().getRecordType(Base).getTypePtr()));
683 llvm::Value *TypeId =
684 llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
685
686 llvm::Value *TypeTest =
687 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
688 {CastedNonVirtualFn, TypeId});
689 Bit = Builder.CreateOr(Bit, TypeTest);
690 }
691
692 CGF.EmitCheck(std::make_pair(Bit, SanitizerKind::CFIMFCall),
693 SanitizerHandler::CFICheckFail, StaticData,
694 {CastedNonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
695
696 FnNonVirtual = Builder.GetInsertBlock();
697 }
698 }
699
John McCall475999d2010-08-22 00:05:51 +0000700 // We're done.
701 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000702 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
703 CalleePtr->addIncoming(VirtualFn, FnVirtual);
704 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
705
706 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000707 return Callee;
708}
John McCalla8bbb822010-08-22 03:04:22 +0000709
John McCallc134eb52010-08-31 21:07:20 +0000710/// Compute an l-value by applying the given pointer-to-member to a
711/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000712llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000713 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000714 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000715 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000716
717 CGBuilderTy &Builder = CGF.Builder;
718
John McCallc134eb52010-08-31 21:07:20 +0000719 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000720 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000721
722 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000723 llvm::Value *Addr =
724 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000725
726 // Cast the address to the appropriate pointer type, adopting the
727 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000728 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
729 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000730 return Builder.CreateBitCast(Addr, PType);
731}
732
John McCallc62bb392012-02-15 01:22:51 +0000733/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
734/// conversion.
735///
736/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000737///
738/// Obligatory offset/adjustment diagram:
739/// <-- offset --> <-- adjustment -->
740/// |--------------------------|----------------------|--------------------|
741/// ^Derived address point ^Base address point ^Member address point
742///
743/// So when converting a base member pointer to a derived member pointer,
744/// we add the offset to the adjustment because the address point has
745/// decreased; and conversely, when converting a derived MP to a base MP
746/// we subtract the offset from the adjustment because the address point
747/// has increased.
748///
749/// The standard forbids (at compile time) conversion to and from
750/// virtual bases, which is why we don't have to consider them here.
751///
752/// The standard forbids (at run time) casting a derived MP to a base
753/// MP when the derived MP does not point to a member of the base.
754/// This is why -1 is a reasonable choice for null data member
755/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000756llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000757ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
758 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000759 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000760 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000761 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
762 E->getCastKind() == CK_ReinterpretMemberPointer);
763
764 // Under Itanium, reinterprets don't require any additional processing.
765 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
766
767 // Use constant emission if we can.
768 if (isa<llvm::Constant>(src))
769 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
770
771 llvm::Constant *adj = getMemberPointerAdjustment(E);
772 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000773
774 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000775 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000776
John McCallc62bb392012-02-15 01:22:51 +0000777 const MemberPointerType *destTy =
778 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000779
John McCall7a9aac22010-08-23 01:21:21 +0000780 // For member data pointers, this is just a matter of adding the
781 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000782 if (destTy->isMemberDataPointer()) {
783 llvm::Value *dst;
784 if (isDerivedToBase)
785 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000786 else
John McCallc62bb392012-02-15 01:22:51 +0000787 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000788
789 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000790 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
791 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
792 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000793 }
794
John McCalla1dee5302010-08-22 10:59:02 +0000795 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000796 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000797 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
798 offset <<= 1;
799 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000800 }
801
John McCallc62bb392012-02-15 01:22:51 +0000802 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
803 llvm::Value *dstAdj;
804 if (isDerivedToBase)
805 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000806 else
John McCallc62bb392012-02-15 01:22:51 +0000807 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000808
John McCallc62bb392012-02-15 01:22:51 +0000809 return Builder.CreateInsertValue(src, dstAdj, 1);
810}
811
812llvm::Constant *
813ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
814 llvm::Constant *src) {
815 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
816 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
817 E->getCastKind() == CK_ReinterpretMemberPointer);
818
819 // Under Itanium, reinterprets don't require any additional processing.
820 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
821
822 // If the adjustment is trivial, we don't need to do anything.
823 llvm::Constant *adj = getMemberPointerAdjustment(E);
824 if (!adj) return src;
825
826 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
827
828 const MemberPointerType *destTy =
829 E->getType()->castAs<MemberPointerType>();
830
831 // For member data pointers, this is just a matter of adding the
832 // offset if the source is non-null.
833 if (destTy->isMemberDataPointer()) {
834 // null maps to null.
835 if (src->isAllOnesValue()) return src;
836
837 if (isDerivedToBase)
838 return llvm::ConstantExpr::getNSWSub(src, adj);
839 else
840 return llvm::ConstantExpr::getNSWAdd(src, adj);
841 }
842
843 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000844 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000845 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
846 offset <<= 1;
847 adj = llvm::ConstantInt::get(adj->getType(), offset);
848 }
849
850 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
851 llvm::Constant *dstAdj;
852 if (isDerivedToBase)
853 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
854 else
855 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
856
857 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000858}
John McCall84fa5102010-08-22 04:16:24 +0000859
860llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000861ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000862 // Itanium C++ ABI 2.3:
863 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000864 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000865 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000866
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000867 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000868 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000869 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000870}
871
John McCallf3a88602011-02-03 08:15:49 +0000872llvm::Constant *
873ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
874 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000875 // Itanium C++ ABI 2.3:
876 // A pointer to data member is an offset from the base address of
877 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000878 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000879}
880
David Majnemere2be95b2015-06-23 07:31:01 +0000881llvm::Constant *
882ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000883 return BuildMemberPointer(MD, CharUnits::Zero());
884}
885
886llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
887 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000888 assert(MD->isInstance() && "Member function must not be static!");
John McCalla1dee5302010-08-22 10:59:02 +0000889
890 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000891
892 // Get the function pointer (or index if this is a virtual function).
893 llvm::Constant *MemPtr[2];
894 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000895 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000896
Ken Dyckdf016282011-04-09 01:30:02 +0000897 const ASTContext &Context = getContext();
898 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000899 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000900 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000901
Mark Seabornedf0d382013-07-24 16:25:13 +0000902 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000903 // ARM C++ ABI 3.2.1:
904 // This ABI specifies that adj contains twice the this
905 // adjustment, plus 1 if the member function is virtual. The
906 // least significant bit of adj then makes exactly the same
907 // discrimination as the least significant bit of ptr does for
908 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000909 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
910 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000911 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000912 } else {
913 // Itanium C++ ABI 2.3:
914 // For a virtual function, [the pointer field] is 1 plus the
915 // virtual table offset (in bytes) of the function,
916 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000917 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
918 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000919 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000920 }
921 } else {
John McCall2979fe02011-04-12 00:42:48 +0000922 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000923 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000924 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000925 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000926 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000927 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000928 } else {
John McCall2979fe02011-04-12 00:42:48 +0000929 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
930 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000931 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000932 }
John McCall2979fe02011-04-12 00:42:48 +0000933 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000934
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000935 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000936 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
937 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000938 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000939 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000940
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000941 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000942}
943
Richard Smithdafff942012-01-14 04:30:29 +0000944llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
945 QualType MPType) {
946 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
947 const ValueDecl *MPD = MP.getMemberPointerDecl();
948 if (!MPD)
949 return EmitNullMemberPointer(MPT);
950
Reid Kleckner452abac2013-05-09 21:01:17 +0000951 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000952
953 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
954 return BuildMemberPointer(MD, ThisAdjustment);
955
956 CharUnits FieldOffset =
957 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
958 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
959}
960
John McCall131d97d2010-08-22 08:30:07 +0000961/// The comparison algorithm is pretty easy: the member pointers are
962/// the same if they're either bitwise identical *or* both null.
963///
964/// ARM is different here only because null-ness is more complicated.
965llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000966ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
967 llvm::Value *L,
968 llvm::Value *R,
969 const MemberPointerType *MPT,
970 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000971 CGBuilderTy &Builder = CGF.Builder;
972
John McCall131d97d2010-08-22 08:30:07 +0000973 llvm::ICmpInst::Predicate Eq;
974 llvm::Instruction::BinaryOps And, Or;
975 if (Inequality) {
976 Eq = llvm::ICmpInst::ICMP_NE;
977 And = llvm::Instruction::Or;
978 Or = llvm::Instruction::And;
979 } else {
980 Eq = llvm::ICmpInst::ICMP_EQ;
981 And = llvm::Instruction::And;
982 Or = llvm::Instruction::Or;
983 }
984
John McCall7a9aac22010-08-23 01:21:21 +0000985 // Member data pointers are easy because there's a unique null
986 // value, so it just comes down to bitwise equality.
987 if (MPT->isMemberDataPointer())
988 return Builder.CreateICmp(Eq, L, R);
989
990 // For member function pointers, the tautologies are more complex.
991 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000992 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000993 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000994 // (L == R) <==> (L.ptr == R.ptr &&
995 // (L.adj == R.adj ||
996 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000997 // The inequality tautologies have exactly the same structure, except
998 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000999
John McCall7a9aac22010-08-23 01:21:21 +00001000 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
1001 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
1002
John McCall131d97d2010-08-22 08:30:07 +00001003 // This condition tests whether L.ptr == R.ptr. This must always be
1004 // true for equality to hold.
1005 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
1006
1007 // This condition, together with the assumption that L.ptr == R.ptr,
1008 // tests whether the pointers are both null. ARM imposes an extra
1009 // condition.
1010 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
1011 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
1012
1013 // This condition tests whether L.adj == R.adj. If this isn't
1014 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +00001015 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
1016 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001017 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
1018
1019 // Null member function pointers on ARM clear the low bit of Adj,
1020 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001021 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001022 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
1023
1024 // Compute (l.adj | r.adj) & 1 and test it against zero.
1025 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
1026 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
1027 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
1028 "cmp.or.adj");
1029 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
1030 }
1031
1032 // Tie together all our conditions.
1033 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
1034 Result = Builder.CreateBinOp(And, PtrEq, Result,
1035 Inequality ? "memptr.ne" : "memptr.eq");
1036 return Result;
1037}
1038
1039llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +00001040ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1041 llvm::Value *MemPtr,
1042 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +00001043 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +00001044
1045 /// For member data pointers, this is just a check against -1.
1046 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +00001047 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +00001048 llvm::Value *NegativeOne =
1049 llvm::Constant::getAllOnesValue(MemPtr->getType());
1050 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
1051 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001052
Daniel Dunbar914bc412011-04-19 23:10:47 +00001053 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +00001054 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +00001055
1056 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1057 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1058
Daniel Dunbar914bc412011-04-19 23:10:47 +00001059 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1060 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001061 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001062 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001063 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001064 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001065 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1066 "memptr.isvirtual");
1067 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001068 }
1069
1070 return Result;
1071}
John McCall1c456c82010-08-22 06:43:33 +00001072
Reid Kleckner40ca9132014-05-13 22:05:45 +00001073bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1074 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1075 if (!RD)
1076 return false;
1077
Richard Smith96cd6712017-08-16 01:49:53 +00001078 // If C++ prohibits us from making a copy, return by address.
Reid Kleckneradb41982019-04-30 22:23:20 +00001079 if (!RD->canPassInRegisters()) {
John McCall7f416cc2015-09-08 08:05:57 +00001080 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1081 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001082 return true;
1083 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001084 return false;
1085}
1086
John McCall614dbdc2010-08-22 21:01:12 +00001087/// The Itanium ABI requires non-zero initialization only for data
1088/// member pointers, for which '0' is a valid offset.
1089bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001090 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001091}
John McCall5d865c322010-08-31 07:33:07 +00001092
John McCall82fb8922012-09-25 10:10:39 +00001093/// The Itanium ABI always places an offset to the complete object
1094/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001095void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1096 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001097 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001098 QualType ElementType,
1099 const CXXDestructorDecl *Dtor) {
1100 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001101 if (UseGlobalDelete) {
1102 // Derive the complete-object pointer, which is what we need
1103 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001104
David Majnemer0c0b6d92014-10-31 20:09:12 +00001105 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001106 auto *ClassDecl =
1107 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1108 llvm::Value *VTable =
1109 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001110
David Majnemer0c0b6d92014-10-31 20:09:12 +00001111 // Track back to entry -2 and pull out the offset there.
1112 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1113 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001114 llvm::Value *Offset =
1115 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001116
1117 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001118 llvm::Value *CompletePtr =
1119 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001120 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1121
1122 // If we're supposed to call the global delete, make sure we do so
1123 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001124 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1125 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001126 }
1127
1128 // FIXME: Provide a source location here even though there's no
1129 // CXXMemberCallExpr for dtor call.
1130 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1131 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1132
1133 if (UseGlobalDelete)
1134 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001135}
1136
David Majnemer442d0a22014-11-25 07:20:20 +00001137void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1138 // void __cxa_rethrow();
1139
1140 llvm::FunctionType *FTy =
1141 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1142
James Y Knight9871db02019-02-05 16:42:33 +00001143 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
David Majnemer442d0a22014-11-25 07:20:20 +00001144
1145 if (isNoReturn)
1146 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1147 else
1148 CGF.EmitRuntimeCallOrInvoke(Fn);
1149}
1150
James Y Knight9871db02019-02-05 16:42:33 +00001151static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
David Majnemer7c237072015-03-05 00:46:22 +00001152 // void *__cxa_allocate_exception(size_t thrown_size);
1153
1154 llvm::FunctionType *FTy =
1155 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1156
1157 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1158}
1159
James Y Knight9871db02019-02-05 16:42:33 +00001160static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
David Majnemer7c237072015-03-05 00:46:22 +00001161 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1162 // void (*dest) (void *));
1163
1164 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1165 llvm::FunctionType *FTy =
1166 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1167
1168 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1169}
1170
1171void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1172 QualType ThrowType = E->getSubExpr()->getType();
1173 // Now allocate the exception object.
1174 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1175 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1176
James Y Knight9871db02019-02-05 16:42:33 +00001177 llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
David Majnemer7c237072015-03-05 00:46:22 +00001178 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1179 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1180
Akira Hatanakac39a2432019-05-10 02:16:37 +00001181 CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
John McCall7f416cc2015-09-08 08:05:57 +00001182 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001183
1184 // Now throw the exception.
1185 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1186 /*ForEH=*/true);
1187
1188 // The address of the destructor. If the exception type has a
1189 // trivial destructor (or isn't a record), we just pass null.
1190 llvm::Constant *Dtor = nullptr;
1191 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1192 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1193 if (!Record->hasTrivialDestructor()) {
1194 CXXDestructorDecl *DtorD = Record->getDestructor();
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001195 Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
David Majnemer7c237072015-03-05 00:46:22 +00001196 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1197 }
1198 }
1199 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1200
1201 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1202 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1203}
1204
James Y Knight9871db02019-02-05 16:42:33 +00001205static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001206 // void *__dynamic_cast(const void *sub,
1207 // const abi::__class_type_info *src,
1208 // const abi::__class_type_info *dst,
1209 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001210
David Majnemer1162d252014-06-22 19:05:33 +00001211 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001212 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001213 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1214
1215 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1216
1217 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1218
1219 // Mark the function as nounwind readonly.
1220 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1221 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001222 llvm::AttributeList Attrs = llvm::AttributeList::get(
1223 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001224
1225 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1226}
1227
James Y Knight9871db02019-02-05 16:42:33 +00001228static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001229 // void __cxa_bad_cast();
1230 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1231 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1232}
1233
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001234/// Compute the src2dst_offset hint as described in the
David Majnemer1162d252014-06-22 19:05:33 +00001235/// Itanium C++ ABI [2.9.7]
1236static CharUnits computeOffsetHint(ASTContext &Context,
1237 const CXXRecordDecl *Src,
1238 const CXXRecordDecl *Dst) {
1239 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1240 /*DetectVirtual=*/false);
1241
1242 // If Dst is not derived from Src we can skip the whole computation below and
1243 // return that Src is not a public base of Dst. Record all inheritance paths.
1244 if (!Dst->isDerivedFrom(Src, Paths))
1245 return CharUnits::fromQuantity(-2ULL);
1246
1247 unsigned NumPublicPaths = 0;
1248 CharUnits Offset;
1249
1250 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001251 for (const CXXBasePath &Path : Paths) {
1252 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001253 continue;
1254
1255 ++NumPublicPaths;
1256
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001257 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001258 // If the path contains a virtual base class we can't give any hint.
1259 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001260 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001261 return CharUnits::fromQuantity(-1ULL);
1262
1263 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1264 continue;
1265
1266 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001267 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1268 Offset += L.getBaseClassOffset(
1269 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001270 }
1271 }
1272
1273 // -2: Src is not a public base of Dst.
1274 if (NumPublicPaths == 0)
1275 return CharUnits::fromQuantity(-2ULL);
1276
1277 // -3: Src is a multiple public base type but never a virtual base type.
1278 if (NumPublicPaths > 1)
1279 return CharUnits::fromQuantity(-3ULL);
1280
1281 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1282 // Return the offset of Src from the origin of Dst.
1283 return Offset;
1284}
1285
James Y Knight9871db02019-02-05 16:42:33 +00001286static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001287 // void __cxa_bad_typeid();
1288 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1289
1290 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1291}
1292
1293bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1294 QualType SrcRecordTy) {
1295 return IsDeref;
1296}
1297
1298void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
James Y Knight9871db02019-02-05 16:42:33 +00001299 llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
James Y Knight3933add2019-01-30 02:54:28 +00001300 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1301 Call->setDoesNotReturn();
David Majnemer1162d252014-06-22 19:05:33 +00001302 CGF.Builder.CreateUnreachable();
1303}
1304
1305llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1306 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001307 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001308 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001309 auto *ClassDecl =
1310 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001311 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001312 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001313
1314 // Load the type info.
1315 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001316 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001317}
1318
1319bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1320 QualType SrcRecordTy) {
1321 return SrcIsPtr;
1322}
1323
1324llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001325 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001326 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1327 llvm::Type *PtrDiffLTy =
1328 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1329 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1330
1331 llvm::Value *SrcRTTI =
1332 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1333 llvm::Value *DestRTTI =
1334 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1335
1336 // Compute the offset hint.
1337 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1338 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1339 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1340 PtrDiffLTy,
1341 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1342
1343 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001344 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001345 Value = CGF.EmitCastToVoidPtr(Value);
1346
1347 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1348 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1349 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1350
1351 /// C++ [expr.dynamic.cast]p9:
1352 /// A failed cast to reference type throws std::bad_cast
1353 if (DestTy->isReferenceType()) {
1354 llvm::BasicBlock *BadCastBlock =
1355 CGF.createBasicBlock("dynamic_cast.bad_cast");
1356
1357 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1358 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1359
1360 CGF.EmitBlock(BadCastBlock);
1361 EmitBadCastCall(CGF);
1362 }
1363
1364 return Value;
1365}
1366
1367llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001368 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001369 QualType SrcRecordTy,
1370 QualType DestTy) {
1371 llvm::Type *PtrDiffLTy =
1372 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1373 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1374
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001375 auto *ClassDecl =
1376 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001377 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001378 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1379 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001380
1381 // Get the offset-to-top from the vtable.
1382 llvm::Value *OffsetToTop =
1383 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001384 OffsetToTop =
1385 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1386 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001387
1388 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001389 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001390 Value = CGF.EmitCastToVoidPtr(Value);
1391 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1392
1393 return CGF.Builder.CreateBitCast(Value, DestLTy);
1394}
1395
1396bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
James Y Knight9871db02019-02-05 16:42:33 +00001397 llvm::FunctionCallee Fn = getBadCastFn(CGF);
James Y Knight3933add2019-01-30 02:54:28 +00001398 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1399 Call->setDoesNotReturn();
David Majnemer1162d252014-06-22 19:05:33 +00001400 CGF.Builder.CreateUnreachable();
1401 return true;
1402}
1403
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001404llvm::Value *
1405ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001406 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001407 const CXXRecordDecl *ClassDecl,
1408 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001409 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001410 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001411 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1412 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001413
1414 llvm::Value *VBaseOffsetPtr =
1415 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1416 "vbase.offset.ptr");
1417 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1418 CGM.PtrDiffTy->getPointerTo());
1419
1420 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001421 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1422 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001423
1424 return VBaseOffset;
1425}
1426
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001427void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1428 // Just make sure we're in sync with TargetCXXABI.
1429 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1430
Rafael Espindolac3cde362013-12-09 14:51:17 +00001431 // The constructor used for constructing this as a base class;
1432 // ignores virtual bases.
1433 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1434
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001435 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001436 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001437 if (!D->getParent()->isAbstract()) {
1438 // We don't need to emit the complete ctor if the class is abstract.
1439 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1440 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001441}
1442
George Burgess IVf203dbf2017-02-22 20:28:02 +00001443CGCXXABI::AddedStructorArgs
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001444ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001445 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001446 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001447
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001448 // All parameters are already in place except VTT, which goes after 'this'.
1449 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001450
1451 // Check if we need to add a VTT parameter (which has type void **).
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001452 if ((isa<CXXConstructorDecl>(GD.getDecl()) ? GD.getCtorType() == Ctor_Base
1453 : GD.getDtorType() == Dtor_Base) &&
1454 cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001455 ArgTys.insert(ArgTys.begin() + 1,
1456 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001457 return AddedStructorArgs::prefix(1);
1458 }
1459 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001460}
1461
Reid Klecknere7de47e2013-07-22 13:51:44 +00001462void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001463 // The destructor used for destructing this as a base class; ignores
1464 // virtual bases.
1465 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001466
1467 // The destructor used for destructing this as a most-derived class;
1468 // call the base destructor and then destructs any virtual bases.
1469 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1470
Rafael Espindolac3cde362013-12-09 14:51:17 +00001471 // The destructor in a virtual table is always a 'deleting'
1472 // destructor, which calls the complete destructor and then uses the
1473 // appropriate operator delete.
1474 if (D->isVirtual())
1475 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001476}
1477
Reid Kleckner89077a12013-12-17 19:46:40 +00001478void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1479 QualType &ResTy,
1480 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001481 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001482 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001483
1484 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001485 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001486 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001487
1488 // FIXME: avoid the fake decl
1489 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001490 auto *VTTDecl = ImplicitParamDecl::Create(
1491 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1492 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001493 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001494 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001495 }
1496}
1497
John McCall5d865c322010-08-31 07:33:07 +00001498void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001499 // Naked functions have no prolog.
1500 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1501 return;
1502
Reid Kleckner06239e42017-11-16 19:09:36 +00001503 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001504 /// adjustments are required, because they are all handled by thunks.
Reid Kleckner06239e42017-11-16 19:09:36 +00001505 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001506
1507 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001508 if (getStructorImplicitParamDecl(CGF)) {
1509 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1510 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001511 }
John McCall5d865c322010-08-31 07:33:07 +00001512
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001513 /// If this is a function that the ABI specifies returns 'this', initialize
1514 /// the return slot to 'this' at the start of the function.
1515 ///
1516 /// Unlike the setting of return types, this is done within the ABI
1517 /// implementation instead of by clients of CGCXXABI because:
1518 /// 1) getThisValue is currently protected
1519 /// 2) in theory, an ABI could implement 'this' returns some other way;
1520 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001521 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001522 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001523}
1524
George Burgess IVf203dbf2017-02-22 20:28:02 +00001525CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001526 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1527 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1528 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001529 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001530
Reid Kleckner89077a12013-12-17 19:46:40 +00001531 // Insert the implicit 'vtt' argument as the second argument.
1532 llvm::Value *VTT =
1533 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1534 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
Yaxun Liu5b330e82018-03-15 15:25:19 +00001535 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001536 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001537}
1538
1539void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1540 const CXXDestructorDecl *DD,
1541 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001542 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001543 GlobalDecl GD(DD, Type);
1544 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1545 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1546
John McCallb92ab1a2016-10-26 23:46:34 +00001547 CGCallee Callee;
1548 if (getContext().getLangOpts().AppleKext &&
1549 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001550 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001551 else
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001552 Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001553
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001554 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), VTT, VTTTy, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001555}
1556
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001557void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1558 const CXXRecordDecl *RD) {
1559 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1560 if (VTable->hasInitializer())
1561 return;
1562
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001563 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001564 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1565 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001566 llvm::Constant *RTTI =
1567 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001568
1569 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001570 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001571 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001572 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1573 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001574
1575 // Set the correct linkage.
1576 VTable->setLinkage(Linkage);
1577
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001578 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1579 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001580
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001581 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001582 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001583
1584 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1585 // we will emit the typeinfo for the fundamental types. This is the
1586 // same behaviour as GCC.
1587 const DeclContext *DC = RD->getDeclContext();
1588 if (RD->getIdentifier() &&
1589 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1590 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1591 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1592 DC->getParent()->isTranslationUnit())
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00001593 EmitFundamentalRTTIDescriptors(RD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001594
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001595 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001596 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001597}
1598
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001599bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1600 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1601 if (Vptr.NearestVBase == nullptr)
1602 return false;
1603 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001604}
1605
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001606llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1607 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1608 const CXXRecordDecl *NearestVBase) {
1609
1610 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1611 NeedsVTTParameter(CGF.CurGD)) {
1612 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1613 NearestVBase);
1614 }
1615 return getVTableAddressPoint(Base, VTableClass);
1616}
1617
1618llvm::Constant *
1619ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1620 const CXXRecordDecl *VTableClass) {
1621 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001622
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001623 // Find the appropriate vtable within the vtable group, and the address point
1624 // within that vtable.
1625 VTableLayout::AddressPointLocation AddressPoint =
1626 CGM.getItaniumVTableContext()
1627 .getVTableLayout(VTableClass)
1628 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001629 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001630 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001631 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1632 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001633 };
1634
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001635 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1636 Indices, /*InBounds=*/true,
1637 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001638}
1639
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001640llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1641 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1642 const CXXRecordDecl *NearestVBase) {
1643 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1644 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1645
1646 // Get the secondary vpointer index.
1647 uint64_t VirtualPointerIndex =
1648 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1649
1650 /// Load the VTT.
1651 llvm::Value *VTT = CGF.LoadCXXVTT();
1652 if (VirtualPointerIndex)
1653 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1654
1655 // And load the address point from the VTT.
1656 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1657}
1658
1659llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1660 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1661 return getVTableAddressPoint(Base, VTableClass);
1662}
1663
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001664llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1665 CharUnits VPtrOffset) {
1666 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1667
1668 llvm::GlobalVariable *&VTable = VTables[RD];
1669 if (VTable)
1670 return VTable;
1671
Eric Christopherd160c502016-01-29 01:35:53 +00001672 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001673 CGM.addDeferredVTable(RD);
1674
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001675 SmallString<256> Name;
1676 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001677 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001678
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001679 const VTableLayout &VTLayout =
1680 CGM.getItaniumVTableContext().getVTableLayout(RD);
1681 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001682
David Greenbe0c5b62018-09-12 14:09:06 +00001683 // Use pointer alignment for the vtable. Otherwise we would align them based
1684 // on the size of the initializer which doesn't make sense as only single
1685 // values are read.
1686 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1687
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001688 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
David Greenbe0c5b62018-09-12 14:09:06 +00001689 Name, VTableType, llvm::GlobalValue::ExternalLinkage,
1690 getContext().toCharUnitsFromBits(PAlign).getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001691 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001692
Rafael Espindola922f2aa2018-02-23 19:30:48 +00001693 CGM.setGVProperties(VTable, RD);
1694
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001695 return VTable;
1696}
1697
John McCall9831b842018-02-06 18:52:44 +00001698CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1699 GlobalDecl GD,
1700 Address This,
1701 llvm::Type *Ty,
1702 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001703 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001704 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1705 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001706
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001707 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001708 llvm::Value *VFunc;
1709 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1710 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001711 MethodDecl->getParent(), VTable,
1712 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001713 } else {
1714 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001715
John McCall9831b842018-02-06 18:52:44 +00001716 llvm::Value *VFuncPtr =
1717 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1718 auto *VFuncLoad =
1719 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001720
John McCall9831b842018-02-06 18:52:44 +00001721 // Add !invariant.load md to virtual function load to indicate that
1722 // function didn't change inside vtable.
1723 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1724 // help in devirtualization because it will only matter if we will have 2
1725 // the same virtual function loads from the same vtable load, which won't
1726 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1727 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1728 CGM.getCodeGenOpts().StrictVTablePointers)
1729 VFuncLoad->setMetadata(
1730 llvm::LLVMContext::MD_invariant_load,
1731 llvm::MDNode::get(CGM.getLLVMContext(),
1732 llvm::ArrayRef<llvm::Metadata *>()));
1733 VFunc = VFuncLoad;
1734 }
John McCallb92ab1a2016-10-26 23:46:34 +00001735
Erich Keanede6480a32018-11-13 15:48:08 +00001736 CGCallee Callee(GD, VFunc);
John McCall9831b842018-02-06 18:52:44 +00001737 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001738}
1739
David Majnemer0c0b6d92014-10-31 20:09:12 +00001740llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1741 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001742 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001743 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001744 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1745
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001746 GlobalDecl GD(Dtor, DtorType);
1747 const CGFunctionInfo *FInfo =
1748 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
George Burgess IV00f70bd2018-03-01 05:43:23 +00001749 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001750 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001751
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001752 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), nullptr, QualType(),
1753 nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001754 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001755}
1756
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001757void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001758 CodeGenVTables &VTables = CGM.getVTables();
1759 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001760 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001761}
1762
Richard Smithc195c252018-11-27 19:33:49 +00001763bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
1764 const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001765 // We don't emit available_externally vtables if we are in -fapple-kext mode
1766 // because kext mode does not permit devirtualization.
1767 if (CGM.getLangOpts().AppleKext)
1768 return false;
1769
Piotr Padlewskie368de32018-06-13 13:55:42 +00001770 // If the vtable is hidden then it is not safe to emit an available_externally
1771 // copy of vtable.
1772 if (isVTableHidden(RD))
1773 return false;
1774
1775 if (CGM.getCodeGenOpts().ForceEmitVTables)
1776 return true;
1777
1778 // If we don't have any not emitted inline virtual function then we are safe
1779 // to emit an available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001780 // FIXME we can still emit a copy of the vtable if we
1781 // can emit definition of the inline functions.
Richard Smithc195c252018-11-27 19:33:49 +00001782 if (hasAnyUnusedVirtualInlineFunction(RD))
1783 return false;
1784
1785 // For a class with virtual bases, we must also be able to speculatively
1786 // emit the VTT, because CodeGen doesn't have separate notions of "can emit
1787 // the vtable" and "can emit the VTT". For a base subobject, this means we
1788 // need to be able to emit non-virtual base vtables.
1789 if (RD->getNumVBases()) {
1790 for (const auto &B : RD->bases()) {
1791 auto *BRD = B.getType()->getAsCXXRecordDecl();
1792 assert(BRD && "no class for base specifier");
1793 if (B.isVirtual() || !BRD->isDynamicClass())
1794 continue;
1795 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1796 return false;
1797 }
1798 }
1799
1800 return true;
1801}
1802
1803bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
1804 if (!canSpeculativelyEmitVTableAsBaseClass(RD))
1805 return false;
1806
1807 // For a complete-object vtable (or more specifically, for the VTT), we need
1808 // to be able to speculatively emit the vtables of all dynamic virtual bases.
1809 for (const auto &B : RD->vbases()) {
1810 auto *BRD = B.getType()->getAsCXXRecordDecl();
1811 assert(BRD && "no class for base specifier");
1812 if (!BRD->isDynamicClass())
1813 continue;
1814 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1815 return false;
1816 }
1817
1818 return true;
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001819}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001820static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001821 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001822 int64_t NonVirtualAdjustment,
1823 int64_t VirtualAdjustment,
1824 bool IsReturnAdjustment) {
1825 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001826 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001827
John McCall7f416cc2015-09-08 08:05:57 +00001828 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001829
John McCall7f416cc2015-09-08 08:05:57 +00001830 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001831 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001832 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1833 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001834 }
1835
John McCall7f416cc2015-09-08 08:05:57 +00001836 // Perform the virtual adjustment if we have one.
1837 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001838 if (VirtualAdjustment) {
1839 llvm::Type *PtrDiffTy =
1840 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1841
John McCall7f416cc2015-09-08 08:05:57 +00001842 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001843 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1844
1845 llvm::Value *OffsetPtr =
1846 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1847
1848 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1849
1850 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001851 llvm::Value *Offset =
1852 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001853
1854 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001855 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1856 } else {
1857 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001858 }
1859
John McCall7f416cc2015-09-08 08:05:57 +00001860 // In a derived-to-base conversion, the non-virtual adjustment is
1861 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001862 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001863 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1864 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001865 }
1866
1867 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001868 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001869}
1870
1871llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001872 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001873 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001874 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1875 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001876 /*IsReturnAdjustment=*/false);
1877}
1878
1879llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001880ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001881 const ReturnAdjustment &RA) {
1882 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1883 RA.Virtual.Itanium.VBaseOffsetOffset,
1884 /*IsReturnAdjustment=*/true);
1885}
1886
John McCall5d865c322010-08-31 07:33:07 +00001887void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1888 RValue RV, QualType ResultType) {
1889 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1890 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1891
1892 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001893 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001894 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1895 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1896}
John McCall8ed55a52010-09-02 09:58:18 +00001897
1898/************************** Array allocation cookies **************************/
1899
John McCallb91cd662012-05-01 05:23:51 +00001900CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1901 // The array cookie is a size_t; pad that up to the element alignment.
1902 // The cookie is actually right-justified in that space.
1903 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1904 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001905}
1906
John McCall7f416cc2015-09-08 08:05:57 +00001907Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1908 Address NewPtr,
1909 llvm::Value *NumElements,
1910 const CXXNewExpr *expr,
1911 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001912 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001913
John McCall7f416cc2015-09-08 08:05:57 +00001914 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001915
John McCall9bca9232010-09-02 10:25:57 +00001916 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001917 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001918
1919 // The size of the cookie.
1920 CharUnits CookieSize =
1921 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001922 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001923
1924 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001925 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001926 CharUnits CookieOffset = CookieSize - SizeSize;
1927 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001928 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001929
1930 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001931 Address NumElementsPtr =
1932 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001933 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001934
1935 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001936 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001937 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
Filipe Cabecinhas0eb50082018-11-02 17:29:04 +00001938 CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001939 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001940 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1941 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001942 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
James Y Knight9871db02019-02-05 16:42:33 +00001943 llvm::FunctionCallee F =
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001944 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001945 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001946 }
John McCall8ed55a52010-09-02 09:58:18 +00001947
1948 // Finally, compute a pointer to the actual data buffer by skipping
1949 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001950 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001951}
1952
John McCallb91cd662012-05-01 05:23:51 +00001953llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001954 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001955 CharUnits cookieSize) {
1956 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001957 Address numElementsPtr = allocPtr;
1958 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001959 if (!numElementsOffset.isZero())
1960 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001961 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001962
John McCall7f416cc2015-09-08 08:05:57 +00001963 unsigned AS = allocPtr.getAddressSpace();
1964 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001965 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001966 return CGF.Builder.CreateLoad(numElementsPtr);
1967 // In asan mode emit a function call instead of a regular load and let the
1968 // run-time deal with it: if the shadow is properly poisoned return the
1969 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1970 // We can't simply ignore this load using nosanitize metadata because
1971 // the metadata may be lost.
1972 llvm::FunctionType *FTy =
1973 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
James Y Knight9871db02019-02-05 16:42:33 +00001974 llvm::FunctionCallee F =
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001975 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001976 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001977}
1978
John McCallb91cd662012-05-01 05:23:51 +00001979CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001980 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001981 // struct array_cookie {
1982 // std::size_t element_size; // element_size != 0
1983 // std::size_t element_count;
1984 // };
John McCallc19c7062013-01-25 23:36:19 +00001985 // But the base ABI doesn't give anything an alignment greater than
1986 // 8, so we can dismiss this as typical ABI-author blindness to
1987 // actual language complexity and round up to the element alignment.
1988 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1989 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001990}
1991
John McCall7f416cc2015-09-08 08:05:57 +00001992Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1993 Address newPtr,
1994 llvm::Value *numElements,
1995 const CXXNewExpr *expr,
1996 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001997 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001998
John McCall8ed55a52010-09-02 09:58:18 +00001999 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00002000 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00002001
2002 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00002003 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00002004 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
2005 getContext().getTypeSizeInChars(elementType).getQuantity());
2006 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00002007
2008 // The second element is the element count.
James Y Knight751fe282019-02-09 22:22:28 +00002009 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00002010 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00002011
2012 // Finally, compute a pointer to the actual data buffer by skipping
2013 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00002014 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00002015 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00002016}
2017
John McCallb91cd662012-05-01 05:23:51 +00002018llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002019 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00002020 CharUnits cookieSize) {
2021 // The number of elements is at offset sizeof(size_t) relative to
2022 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002023 Address numElementsPtr
2024 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00002025
John McCall7f416cc2015-09-08 08:05:57 +00002026 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00002027 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00002028}
2029
John McCall68ff0372010-09-08 01:44:27 +00002030/*********************** Static local initialization **************************/
2031
James Y Knight9871db02019-02-05 16:42:33 +00002032static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
2033 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002034 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002035 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00002036 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00002037 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002038 return CGM.CreateRuntimeFunction(
2039 FTy, "__cxa_guard_acquire",
2040 llvm::AttributeList::get(CGM.getLLVMContext(),
2041 llvm::AttributeList::FunctionIndex,
2042 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002043}
2044
James Y Knight9871db02019-02-05 16:42:33 +00002045static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
2046 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002047 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002048 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00002049 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002050 return CGM.CreateRuntimeFunction(
2051 FTy, "__cxa_guard_release",
2052 llvm::AttributeList::get(CGM.getLLVMContext(),
2053 llvm::AttributeList::FunctionIndex,
2054 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002055}
2056
James Y Knight9871db02019-02-05 16:42:33 +00002057static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
2058 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002059 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002060 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00002061 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002062 return CGM.CreateRuntimeFunction(
2063 FTy, "__cxa_guard_abort",
2064 llvm::AttributeList::get(CGM.getLLVMContext(),
2065 llvm::AttributeList::FunctionIndex,
2066 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002067}
2068
2069namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002070 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00002071 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00002072 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00002073
Craig Topper4f12f102014-03-12 06:41:41 +00002074 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00002075 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
2076 Guard);
John McCall68ff0372010-09-08 01:44:27 +00002077 }
2078 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002079}
John McCall68ff0372010-09-08 01:44:27 +00002080
2081/// The ARM code here follows the Itanium code closely enough that we
2082/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00002083void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
2084 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00002085 llvm::GlobalVariable *var,
2086 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00002087 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00002088
Richard Smith62f19e72016-06-25 00:15:56 +00002089 // Inline variables that weren't instantiated from variable templates have
2090 // partially-ordered initialization within their translation unit.
2091 bool NonTemplateInline =
2092 D.isInline() &&
2093 !isTemplateInstantiation(D.getTemplateSpecializationKind());
2094
2095 // We only need to use thread-safe statics for local non-TLS variables and
2096 // inline variables; other global initialization is always single-threaded
2097 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002098 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002099 (D.isLocalVarDecl() || NonTemplateInline) &&
2100 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002101
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002102 // If we have a global variable with internal linkage and thread-safe statics
2103 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002104 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2105
2106 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002107 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002108 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002109 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002110 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002111 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002112 // Guard variables are 64 bits in the generic ABI and size width on ARM
2113 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002114 if (UseARMGuardVarABI) {
2115 guardTy = CGF.SizeTy;
2116 guardAlignment = CGF.getSizeAlign();
2117 } else {
2118 guardTy = CGF.Int64Ty;
2119 guardAlignment = CharUnits::fromQuantity(
2120 CGM.getDataLayout().getABITypeAlignment(guardTy));
2121 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002122 }
John McCallb88a5662012-03-30 21:00:39 +00002123 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002124
John McCallb88a5662012-03-30 21:00:39 +00002125 // Create the guard variable if we don't already have it (as we
2126 // might if we're double-emitting this function body).
2127 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2128 if (!guard) {
2129 // Mangle the name for the guard.
2130 SmallString<256> guardName;
2131 {
2132 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002133 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002134 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002135
John McCallb88a5662012-03-30 21:00:39 +00002136 // Create the guard variable with a zero-initializer.
2137 // Just absorb linkage and visibility from the guarded variable.
2138 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2139 false, var->getLinkage(),
2140 llvm::ConstantInt::get(guardTy, 0),
2141 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002142 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002143 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002144 // If the variable is thread-local, so is its guard variable.
2145 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002146 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002147
Yaron Keren5bfa1082015-09-03 20:33:29 +00002148 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2149 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002150 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002151 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002152 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002153 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2154 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002155 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002156 // An inline variable's guard function is run from the per-TU
2157 // initialization function, not via a dedicated global ctor function, so
2158 // we can't put it in a comdat.
2159 if (!NonTemplateInline)
2160 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002161 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2162 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002163 }
2164
John McCallb88a5662012-03-30 21:00:39 +00002165 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2166 }
John McCall87590e62012-03-30 07:09:50 +00002167
John McCall7f416cc2015-09-08 08:05:57 +00002168 Address guardAddr = Address(guard, guardAlignment);
2169
John McCall68ff0372010-09-08 01:44:27 +00002170 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002171 //
John McCall68ff0372010-09-08 01:44:27 +00002172 // Itanium C++ ABI 3.3.2:
2173 // The following is pseudo-code showing how these functions can be used:
2174 // if (obj_guard.first_byte == 0) {
2175 // if ( __cxa_guard_acquire (&obj_guard) ) {
2176 // try {
2177 // ... initialize the object ...;
2178 // } catch (...) {
2179 // __cxa_guard_abort (&obj_guard);
2180 // throw;
2181 // }
2182 // ... queue object destructor with __cxa_atexit() ...;
2183 // __cxa_guard_release (&obj_guard);
2184 // }
2185 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002186
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002187 // Load the first byte of the guard variable.
2188 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002189 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002190
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002191 // Itanium ABI:
2192 // An implementation supporting thread-safety on multiprocessor
2193 // systems must also guarantee that references to the initialized
2194 // object do not occur before the load of the initialization flag.
2195 //
2196 // In LLVM, we do this by marking the load Acquire.
2197 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002198 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002199
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002200 // For ARM, we should only check the first bit, rather than the entire byte:
2201 //
2202 // ARM C++ ABI 3.2.3.1:
2203 // To support the potential use of initialization guard variables
2204 // as semaphores that are the target of ARM SWP and LDREX/STREX
2205 // synchronizing instructions we define a static initialization
2206 // guard variable to be a 4-byte aligned, 4-byte word with the
2207 // following inline access protocol.
2208 // #define INITIALIZED 1
2209 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2210 // if (__cxa_guard_acquire(&obj_guard))
2211 // ...
2212 // }
2213 //
2214 // and similarly for ARM64:
2215 //
2216 // ARM64 C++ ABI 3.2.2:
2217 // This ABI instead only specifies the value bit 0 of the static guard
2218 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2219 // variable is not initialized and 1 when it is.
2220 llvm::Value *V =
2221 (UseARMGuardVarABI && !useInt8GuardVariable)
2222 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2223 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002224 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002225
2226 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2227 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2228
2229 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002230 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2231 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002232
2233 CGF.EmitBlock(InitCheckBlock);
2234
2235 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002236 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002237 // Call __cxa_guard_acquire.
2238 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002239 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002240
John McCall68ff0372010-09-08 01:44:27 +00002241 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002242
John McCall68ff0372010-09-08 01:44:27 +00002243 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2244 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002245
John McCall68ff0372010-09-08 01:44:27 +00002246 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002247 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002248
John McCall68ff0372010-09-08 01:44:27 +00002249 CGF.EmitBlock(InitBlock);
2250 }
2251
2252 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002253 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002254
John McCall5aa52592011-06-17 07:33:57 +00002255 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002256 // Pop the guard-abort cleanup if we pushed one.
2257 CGF.PopCleanupBlock();
2258
2259 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002260 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2261 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002262 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002263 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002264 }
2265
2266 CGF.EmitBlock(EndBlock);
2267}
John McCallc84ed6a2012-05-01 06:13:13 +00002268
2269/// Register a global destructor using __cxa_atexit.
2270static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
James Y Knightf7321542019-02-07 01:14:17 +00002271 llvm::FunctionCallee dtor,
2272 llvm::Constant *addr, bool TLS) {
Erich Keane34ec6922019-06-13 18:20:19 +00002273 assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
2274 "__cxa_atexit is disabled");
Bill Wendling95cae882013-05-02 19:18:03 +00002275 const char *Name = "__cxa_atexit";
2276 if (TLS) {
2277 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002278 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002279 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002280
John McCallc84ed6a2012-05-01 06:13:13 +00002281 // We're assuming that the destructor function is something we can
2282 // reasonably call with the default CC. Go ahead and cast it to the
2283 // right prototype.
2284 llvm::Type *dtorTy =
2285 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2286
2287 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2288 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2289 llvm::FunctionType *atexitTy =
2290 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2291
2292 // Fetch the actual function.
James Y Knight9871db02019-02-05 16:42:33 +00002293 llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2294 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
John McCallc84ed6a2012-05-01 06:13:13 +00002295 fn->setDoesNotThrow();
2296
2297 // Create a variable that binds the atexit to this shared object.
2298 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002299 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2300 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2301 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002302
Akira Hatanaka617e2612018-04-17 18:41:52 +00002303 if (!addr)
2304 // addr is null when we are trying to register a dtor annotated with
2305 // __attribute__((destructor)) in a constructor function. Using null here is
2306 // okay because this argument is just passed back to the destructor
2307 // function.
2308 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2309
James Y Knightf7321542019-02-07 01:14:17 +00002310 llvm::Value *args[] = {llvm::ConstantExpr::getBitCast(
2311 cast<llvm::Constant>(dtor.getCallee()), dtorTy),
2312 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2313 handle};
John McCall882987f2013-02-28 19:01:20 +00002314 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002315}
2316
Akira Hatanaka617e2612018-04-17 18:41:52 +00002317void CodeGenModule::registerGlobalDtorsWithAtExit() {
2318 for (const auto I : DtorsUsingAtExit) {
2319 int Priority = I.first;
2320 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2321
2322 // Create a function that registers destructors that have the same priority.
2323 //
2324 // Since constructor functions are run in non-descending order of their
2325 // priorities, destructors are registered in non-descending order of their
2326 // priorities, and since destructor functions are run in the reverse order
2327 // of their registration, destructor functions are run in non-ascending
2328 // order of their priorities.
2329 CodeGenFunction CGF(*this);
2330 std::string GlobalInitFnName =
2331 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2332 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2333 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2334 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2335 SourceLocation());
2336 ASTContext &Ctx = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002337 QualType ReturnTy = Ctx.VoidTy;
2338 QualType FunctionTy = Ctx.getFunctionType(ReturnTy, llvm::None, {});
Akira Hatanaka617e2612018-04-17 18:41:52 +00002339 FunctionDecl *FD = FunctionDecl::Create(
2340 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002341 &Ctx.Idents.get(GlobalInitFnName), FunctionTy, nullptr, SC_Static,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002342 false, false);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002343 CGF.StartFunction(GlobalDecl(FD), ReturnTy, GlobalInitFn,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002344 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2345 SourceLocation(), SourceLocation());
2346
2347 for (auto *Dtor : Dtors) {
2348 // Register the destructor function calling __cxa_atexit if it is
2349 // available. Otherwise fall back on calling atexit.
2350 if (getCodeGenOpts().CXAAtExit)
2351 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2352 else
2353 CGF.registerGlobalDtorWithAtExit(Dtor);
2354 }
2355
2356 CGF.FinishFunction();
2357 AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2358 }
2359}
2360
John McCallc84ed6a2012-05-01 06:13:13 +00002361/// Register a global destructor as best as we know how.
James Y Knightf7321542019-02-07 01:14:17 +00002362void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2363 llvm::FunctionCallee dtor,
John McCallc84ed6a2012-05-01 06:13:13 +00002364 llvm::Constant *addr) {
Erik Pilkington5a559e62018-08-21 17:24:06 +00002365 if (D.isNoDestroy(CGM.getContext()))
2366 return;
2367
Erich Keane34ec6922019-06-13 18:20:19 +00002368 // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
2369 // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
2370 // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
2371 // We can always use __cxa_thread_atexit.
2372 if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
Richard Smithdbf74ba2013-04-14 23:01:42 +00002373 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2374
John McCallc84ed6a2012-05-01 06:13:13 +00002375 // In Apple kexts, we want to add a global destructor entry.
2376 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002377 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002378 // Generate a global destructor entry.
2379 return CGM.AddCXXDtorEntry(dtor, addr);
2380 }
2381
David Blaikieebe87e12013-08-27 23:57:18 +00002382 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002383}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002384
David Majnemer9b21c332014-07-11 20:28:10 +00002385static bool isThreadWrapperReplaceable(const VarDecl *VD,
2386 CodeGen::CodeGenModule &CGM) {
2387 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002388 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002389 // the thread wrapper instead of directly referencing the backing variable.
2390 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002391 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002392}
2393
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002394/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002395/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002396/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002397static llvm::GlobalValue::LinkageTypes
2398getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2399 llvm::GlobalValue::LinkageTypes VarLinkage =
2400 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2401
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002402 // For internal linkage variables, we don't need an external or weak wrapper.
2403 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2404 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002405
David Majnemer9b21c332014-07-11 20:28:10 +00002406 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002407 if (isThreadWrapperReplaceable(VD, CGM))
2408 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2409 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2410 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002411 return llvm::GlobalValue::WeakODRLinkage;
2412}
2413
2414llvm::Function *
2415ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002416 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002417 // Mangle the name for the thread_local wrapper function.
2418 SmallString<256> WrapperName;
2419 {
2420 llvm::raw_svector_ostream Out(WrapperName);
2421 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002422 }
2423
Akira Hatanaka26907f92016-01-15 03:34:06 +00002424 // FIXME: If VD is a definition, we should regenerate the function attributes
2425 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002426 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002427 return cast<llvm::Function>(V);
2428
Akira Hatanaka26907f92016-01-15 03:34:06 +00002429 QualType RetQT = VD->getType();
2430 if (RetQT->isReferenceType())
2431 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002432
John McCallc56a8b32016-03-11 04:30:31 +00002433 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2434 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002435
2436 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002437 llvm::Function *Wrapper =
2438 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2439 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002440
Erich Keanede6480a32018-11-13 15:48:08 +00002441 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper);
Akira Hatanaka26907f92016-01-15 03:34:06 +00002442
2443 if (VD->hasDefinition())
2444 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2445
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002446 // Always resolve references to the wrapper at link time.
Vlad Tsyrklevichc93390b2019-01-17 17:53:45 +00002447 if (!Wrapper->hasLocalLinkage())
2448 if (!isThreadWrapperReplaceable(VD, CGM) ||
2449 llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
2450 llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
2451 VD->getVisibility() == HiddenVisibility)
2452 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002453
2454 if (isThreadWrapperReplaceable(VD, CGM)) {
2455 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2456 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2457 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002458 return Wrapper;
2459}
2460
2461void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002462 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2463 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2464 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002465 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002466
2467 // Separate initializers into those with ordered (or partially-ordered)
2468 // initialization and those with unordered initialization.
2469 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2470 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2471 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2472 if (isTemplateInstantiation(
2473 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2474 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2475 CXXThreadLocalInits[I];
2476 else
2477 OrderedInits.push_back(CXXThreadLocalInits[I]);
2478 }
2479
2480 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002481 // Generate a guarded initialization function.
2482 llvm::FunctionType *FTy =
2483 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002484 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2485 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002486 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002487 /*TLS=*/true);
2488 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2489 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2490 llvm::GlobalVariable::InternalLinkage,
2491 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2492 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002493
2494 CharUnits GuardAlign = CharUnits::One();
2495 Guard->setAlignment(GuardAlign.getQuantity());
2496
Richard Smith3ad06362018-10-31 20:39:26 +00002497 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
2498 InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002499 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2500 if (CGM.getTarget().getTriple().isOSDarwin()) {
2501 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2502 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2503 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002504 }
Richard Smithfbe23692017-01-13 00:43:31 +00002505
2506 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002507 for (const VarDecl *VD : CXXThreadLocals) {
2508 llvm::GlobalVariable *Var =
2509 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002510 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002511
David Majnemer9b21c332014-07-11 20:28:10 +00002512 // Some targets require that all access to thread local variables go through
2513 // the thread wrapper. This means that we cannot attempt to create a thread
2514 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002515 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2516 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002517 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002518 }
David Majnemer9b21c332014-07-11 20:28:10 +00002519
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002520 // Mangle the name for the thread_local initialization function.
2521 SmallString<256> InitFnName;
2522 {
2523 llvm::raw_svector_ostream Out(InitFnName);
2524 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002525 }
2526
James Y Knightf7321542019-02-07 01:14:17 +00002527 llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2528
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002529 // If we have a definition for the variable, emit the initialization
2530 // function as an alias to the global Init function (if any). Otherwise,
2531 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002532 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002533 bool InitIsInitFunc = false;
2534 if (VD->hasDefinition()) {
2535 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002536 llvm::Function *InitFuncToUse = InitFunc;
2537 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2538 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2539 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002540 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002541 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002542 } else {
2543 // Emit a weak global function referring to the initialization function.
2544 // This function will not exist if the TU defining the thread_local
2545 // variable in question does not need any dynamic initialization for
2546 // its thread_local variables.
James Y Knightf7321542019-02-07 01:14:17 +00002547 Init = llvm::Function::Create(InitFnTy,
Richard Smithfbe23692017-01-13 00:43:31 +00002548 llvm::GlobalVariable::ExternalWeakLinkage,
2549 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002550 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Erich Keanede6480a32018-11-13 15:48:08 +00002551 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
2552 cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002553 }
2554
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002555 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002556 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002557 Init->setDSOLocal(Var->isDSOLocal());
2558 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002559
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002560 llvm::LLVMContext &Context = CGM.getModule().getContext();
2561 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002562 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002563 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002564 if (Init) {
James Y Knightf7321542019-02-07 01:14:17 +00002565 llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002566 if (isThreadWrapperReplaceable(VD, CGM)) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002567 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002568 llvm::Function *Fn =
2569 cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
2570 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2571 }
Manman Ren5e5d0462016-03-18 23:35:21 +00002572 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002573 } else {
2574 // Don't know whether we have an init function. Call it if it exists.
2575 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2576 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2577 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2578 Builder.CreateCondBr(Have, InitBB, ExitBB);
2579
2580 Builder.SetInsertPoint(InitBB);
James Y Knightf7321542019-02-07 01:14:17 +00002581 Builder.CreateCall(InitFnTy, Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002582 Builder.CreateBr(ExitBB);
2583
2584 Builder.SetInsertPoint(ExitBB);
2585 }
2586
2587 // For a reference, the result of the wrapper function is a pointer to
2588 // the referenced object.
2589 llvm::Value *Val = Var;
2590 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002591 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2592 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002593 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002594 if (Val->getType() != Wrapper->getReturnType())
2595 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2596 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002597 Builder.CreateRet(Val);
2598 }
2599}
2600
Richard Smith0f383742014-03-26 22:48:22 +00002601LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2602 const VarDecl *VD,
2603 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002604 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002605 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002606
Manman Renb0b3af72015-12-17 00:42:36 +00002607 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002608 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002609
2610 LValue LV;
2611 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002612 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002613 else
Manman Renb0b3af72015-12-17 00:42:36 +00002614 LV = CGF.MakeAddrLValue(CallVal, LValType,
2615 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002616 // FIXME: need setObjCGCLValueClass?
2617 return LV;
2618}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002619
2620/// Return whether the given global decl needs a VTT parameter, which it does
2621/// if it's a base constructor or destructor with virtual bases.
2622bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2623 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002624
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002625 // We don't have any virtual bases, just return early.
2626 if (!MD->getParent()->getNumVBases())
2627 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002628
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002629 // Check if we have a base constructor.
2630 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2631 return true;
2632
2633 // Check if we have a base destructor.
2634 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2635 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002636
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002637 return false;
2638}
David Majnemere2cb8d12014-07-07 06:20:47 +00002639
2640namespace {
2641class ItaniumRTTIBuilder {
2642 CodeGenModule &CGM; // Per-module state.
2643 llvm::LLVMContext &VMContext;
2644 const ItaniumCXXABI &CXXABI; // Per-module state.
2645
2646 /// Fields - The fields of the RTTI descriptor currently being built.
2647 SmallVector<llvm::Constant *, 16> Fields;
2648
2649 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2650 llvm::GlobalVariable *
2651 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2652
2653 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2654 /// descriptor of the given type.
2655 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2656
2657 /// BuildVTablePointer - Build the vtable pointer for the given type.
2658 void BuildVTablePointer(const Type *Ty);
2659
2660 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2661 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2662 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2663
2664 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2665 /// classes with bases that do not satisfy the abi::__si_class_type_info
2666 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2667 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2668
2669 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2670 /// for pointer types.
2671 void BuildPointerTypeInfo(QualType PointeeTy);
2672
2673 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2674 /// type_info for an object type.
2675 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2676
2677 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2678 /// struct, used for member pointer types.
2679 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2680
2681public:
2682 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2683 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2684
2685 // Pointer type info flags.
2686 enum {
2687 /// PTI_Const - Type has const qualifier.
2688 PTI_Const = 0x1,
2689
2690 /// PTI_Volatile - Type has volatile qualifier.
2691 PTI_Volatile = 0x2,
2692
2693 /// PTI_Restrict - Type has restrict qualifier.
2694 PTI_Restrict = 0x4,
2695
2696 /// PTI_Incomplete - Type is incomplete.
2697 PTI_Incomplete = 0x8,
2698
2699 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2700 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002701 PTI_ContainingClassIncomplete = 0x10,
2702
2703 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2704 //PTI_TransactionSafe = 0x20,
2705
2706 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2707 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002708 };
2709
2710 // VMI type info flags.
2711 enum {
2712 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2713 VMI_NonDiamondRepeat = 0x1,
2714
2715 /// VMI_DiamondShaped - Class is diamond shaped.
2716 VMI_DiamondShaped = 0x2
2717 };
2718
2719 // Base class type info flags.
2720 enum {
2721 /// BCTI_Virtual - Base class is virtual.
2722 BCTI_Virtual = 0x1,
2723
2724 /// BCTI_Public - Base class is public.
2725 BCTI_Public = 0x2
2726 };
2727
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002728 /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
2729 /// link to an existing RTTI descriptor if one already exists.
2730 llvm::Constant *BuildTypeInfo(QualType Ty);
2731
David Majnemere2cb8d12014-07-07 06:20:47 +00002732 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002733 llvm::Constant *BuildTypeInfo(
2734 QualType Ty,
2735 llvm::GlobalVariable::LinkageTypes Linkage,
2736 llvm::GlobalValue::VisibilityTypes Visibility,
2737 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00002738};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002739}
David Majnemere2cb8d12014-07-07 06:20:47 +00002740
2741llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2742 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002743 SmallString<256> Name;
2744 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002745 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002746
2747 // We know that the mangled name of the type starts at index 4 of the
2748 // mangled name of the typename, so we can just index into it in order to
2749 // get the mangled name of the type.
2750 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2751 Name.substr(4));
David Greenbe0c5b62018-09-12 14:09:06 +00002752 auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00002753
David Greenbe0c5b62018-09-12 14:09:06 +00002754 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2755 Name, Init->getType(), Linkage, Align.getQuantity());
David Majnemere2cb8d12014-07-07 06:20:47 +00002756
2757 GV->setInitializer(Init);
2758
2759 return GV;
2760}
2761
2762llvm::Constant *
2763ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2764 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002765 SmallString<256> Name;
2766 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002767 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002768
2769 // Look for an existing global.
2770 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2771
2772 if (!GV) {
2773 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002774 // Note for the future: If we would ever like to do deferred emission of
2775 // RTTI, check if emitting vtables opportunistically need any adjustment.
2776
David Majnemere2cb8d12014-07-07 06:20:47 +00002777 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2778 /*Constant=*/true,
2779 llvm::GlobalValue::ExternalLinkage, nullptr,
2780 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002781 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2782 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002783 }
2784
2785 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2786}
2787
2788/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2789/// info for that type is defined in the standard library.
2790static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2791 // Itanium C++ ABI 2.9.2:
2792 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2793 // the run-time support library. Specifically, the run-time support
2794 // library should contain type_info objects for the types X, X* and
2795 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2796 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2797 // long, unsigned long, long long, unsigned long long, float, double,
2798 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2799 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002800 //
2801 // GCC also emits RTTI for __int128.
2802 // FIXME: We do not emit RTTI information for decimal types here.
2803
2804 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002805 switch (Ty->getKind()) {
2806 case BuiltinType::Void:
2807 case BuiltinType::NullPtr:
2808 case BuiltinType::Bool:
2809 case BuiltinType::WChar_S:
2810 case BuiltinType::WChar_U:
2811 case BuiltinType::Char_U:
2812 case BuiltinType::Char_S:
2813 case BuiltinType::UChar:
2814 case BuiltinType::SChar:
2815 case BuiltinType::Short:
2816 case BuiltinType::UShort:
2817 case BuiltinType::Int:
2818 case BuiltinType::UInt:
2819 case BuiltinType::Long:
2820 case BuiltinType::ULong:
2821 case BuiltinType::LongLong:
2822 case BuiltinType::ULongLong:
2823 case BuiltinType::Half:
2824 case BuiltinType::Float:
2825 case BuiltinType::Double:
2826 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002827 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002828 case BuiltinType::Float128:
Richard Smith3a8244d2018-05-01 05:02:45 +00002829 case BuiltinType::Char8:
David Majnemere2cb8d12014-07-07 06:20:47 +00002830 case BuiltinType::Char16:
2831 case BuiltinType::Char32:
2832 case BuiltinType::Int128:
2833 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002834 return true;
2835
Alexey Bader954ba212016-04-08 13:40:33 +00002836#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2837 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002838#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002839#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2840 case BuiltinType::Id:
2841#include "clang/Basic/OpenCLExtensionTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002842 case BuiltinType::OCLSampler:
2843 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002844 case BuiltinType::OCLClkEvent:
2845 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002846 case BuiltinType::OCLReserveID:
Leonard Chanf921d852018-06-04 16:07:52 +00002847 case BuiltinType::ShortAccum:
2848 case BuiltinType::Accum:
2849 case BuiltinType::LongAccum:
2850 case BuiltinType::UShortAccum:
2851 case BuiltinType::UAccum:
2852 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002853 case BuiltinType::ShortFract:
2854 case BuiltinType::Fract:
2855 case BuiltinType::LongFract:
2856 case BuiltinType::UShortFract:
2857 case BuiltinType::UFract:
2858 case BuiltinType::ULongFract:
2859 case BuiltinType::SatShortAccum:
2860 case BuiltinType::SatAccum:
2861 case BuiltinType::SatLongAccum:
2862 case BuiltinType::SatUShortAccum:
2863 case BuiltinType::SatUAccum:
2864 case BuiltinType::SatULongAccum:
2865 case BuiltinType::SatShortFract:
2866 case BuiltinType::SatFract:
2867 case BuiltinType::SatLongFract:
2868 case BuiltinType::SatUShortFract:
2869 case BuiltinType::SatUFract:
2870 case BuiltinType::SatULongFract:
Richard Smith4a382012016-02-03 01:32:42 +00002871 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002872
2873 case BuiltinType::Dependent:
2874#define BUILTIN_TYPE(Id, SingletonId)
2875#define PLACEHOLDER_TYPE(Id, SingletonId) \
2876 case BuiltinType::Id:
2877#include "clang/AST/BuiltinTypes.def"
2878 llvm_unreachable("asking for RRTI for a placeholder type!");
2879
2880 case BuiltinType::ObjCId:
2881 case BuiltinType::ObjCClass:
2882 case BuiltinType::ObjCSel:
2883 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2884 }
2885
2886 llvm_unreachable("Invalid BuiltinType Kind!");
2887}
2888
2889static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2890 QualType PointeeTy = PointerTy->getPointeeType();
2891 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2892 if (!BuiltinTy)
2893 return false;
2894
2895 // Check the qualifiers.
2896 Qualifiers Quals = PointeeTy.getQualifiers();
2897 Quals.removeConst();
2898
2899 if (!Quals.empty())
2900 return false;
2901
2902 return TypeInfoIsInStandardLibrary(BuiltinTy);
2903}
2904
2905/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2906/// information for the given type exists in the standard library.
2907static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2908 // Type info for builtin types is defined in the standard library.
2909 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2910 return TypeInfoIsInStandardLibrary(BuiltinTy);
2911
2912 // Type info for some pointer types to builtin types is defined in the
2913 // standard library.
2914 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2915 return TypeInfoIsInStandardLibrary(PointerTy);
2916
2917 return false;
2918}
2919
2920/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2921/// the given type exists somewhere else, and that we should not emit the type
2922/// information in this translation unit. Assumes that it is not a
2923/// standard-library type.
2924static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2925 QualType Ty) {
2926 ASTContext &Context = CGM.getContext();
2927
2928 // If RTTI is disabled, assume it might be disabled in the
2929 // translation unit that defines any potential key function, too.
2930 if (!Context.getLangOpts().RTTI) return false;
2931
2932 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2933 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2934 if (!RD->hasDefinition())
2935 return false;
2936
2937 if (!RD->isDynamicClass())
2938 return false;
2939
2940 // FIXME: this may need to be reconsidered if the key function
2941 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002942 // N.B. We must always emit the RTTI data ourselves if there exists a key
2943 // function.
2944 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002945
2946 // Don't import the RTTI but emit it locally.
Martin Storsjo228ccd62019-04-26 19:31:51 +00002947 if (CGM.getTriple().isWindowsGNUEnvironment())
Martin Storsjo3b528942018-02-02 06:22:35 +00002948 return false;
2949
David Majnemer1fb1a042014-11-07 07:26:38 +00002950 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002951 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2952 ? false
2953 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002954
David Majnemerbe9022c2015-08-06 20:56:55 +00002955 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002956 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002957 }
2958
2959 return false;
2960}
2961
2962/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2963static bool IsIncompleteClassType(const RecordType *RecordTy) {
2964 return !RecordTy->getDecl()->isCompleteDefinition();
2965}
2966
2967/// ContainsIncompleteClassType - Returns whether the given type contains an
2968/// incomplete class type. This is true if
2969///
2970/// * The given type is an incomplete class type.
2971/// * The given type is a pointer type whose pointee type contains an
2972/// incomplete class type.
2973/// * The given type is a member pointer type whose class is an incomplete
2974/// class type.
2975/// * The given type is a member pointer type whoise pointee type contains an
2976/// incomplete class type.
2977/// is an indirect or direct pointer to an incomplete class type.
2978static bool ContainsIncompleteClassType(QualType Ty) {
2979 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2980 if (IsIncompleteClassType(RecordTy))
2981 return true;
2982 }
2983
2984 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2985 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2986
2987 if (const MemberPointerType *MemberPointerTy =
2988 dyn_cast<MemberPointerType>(Ty)) {
2989 // Check if the class type is incomplete.
2990 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2991 if (IsIncompleteClassType(ClassType))
2992 return true;
2993
2994 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2995 }
2996
2997 return false;
2998}
2999
3000// CanUseSingleInheritance - Return whether the given record decl has a "single,
3001// public, non-virtual base at offset zero (i.e. the derived class is dynamic
3002// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3003static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
3004 // Check the number of bases.
3005 if (RD->getNumBases() != 1)
3006 return false;
3007
3008 // Get the base.
3009 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
3010
3011 // Check that the base is not virtual.
3012 if (Base->isVirtual())
3013 return false;
3014
3015 // Check that the base is public.
3016 if (Base->getAccessSpecifier() != AS_public)
3017 return false;
3018
3019 // Check that the class is dynamic iff the base is.
3020 const CXXRecordDecl *BaseDecl =
3021 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3022 if (!BaseDecl->isEmpty() &&
3023 BaseDecl->isDynamicClass() != RD->isDynamicClass())
3024 return false;
3025
3026 return true;
3027}
3028
3029void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
3030 // abi::__class_type_info.
3031 static const char * const ClassTypeInfo =
3032 "_ZTVN10__cxxabiv117__class_type_infoE";
3033 // abi::__si_class_type_info.
3034 static const char * const SIClassTypeInfo =
3035 "_ZTVN10__cxxabiv120__si_class_type_infoE";
3036 // abi::__vmi_class_type_info.
3037 static const char * const VMIClassTypeInfo =
3038 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3039
3040 const char *VTableName = nullptr;
3041
3042 switch (Ty->getTypeClass()) {
3043#define TYPE(Class, Base)
3044#define ABSTRACT_TYPE(Class, Base)
3045#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3046#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3047#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3048#include "clang/AST/TypeNodes.def"
3049 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3050
3051 case Type::LValueReference:
3052 case Type::RValueReference:
3053 llvm_unreachable("References shouldn't get here");
3054
3055 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003056 case Type::DeducedTemplateSpecialization:
3057 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003058
Xiuli Pan9c14e282016-01-09 12:53:17 +00003059 case Type::Pipe:
3060 llvm_unreachable("Pipe types shouldn't get here");
3061
David Majnemere2cb8d12014-07-07 06:20:47 +00003062 case Type::Builtin:
3063 // GCC treats vector and complex types as fundamental types.
3064 case Type::Vector:
3065 case Type::ExtVector:
3066 case Type::Complex:
3067 case Type::Atomic:
3068 // FIXME: GCC treats block pointers as fundamental types?!
3069 case Type::BlockPointer:
3070 // abi::__fundamental_type_info.
3071 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
3072 break;
3073
3074 case Type::ConstantArray:
3075 case Type::IncompleteArray:
3076 case Type::VariableArray:
3077 // abi::__array_type_info.
3078 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
3079 break;
3080
3081 case Type::FunctionNoProto:
3082 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003083 // abi::__function_type_info.
3084 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00003085 break;
3086
3087 case Type::Enum:
3088 // abi::__enum_type_info.
3089 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
3090 break;
3091
3092 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00003093 const CXXRecordDecl *RD =
3094 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00003095
3096 if (!RD->hasDefinition() || !RD->getNumBases()) {
3097 VTableName = ClassTypeInfo;
3098 } else if (CanUseSingleInheritance(RD)) {
3099 VTableName = SIClassTypeInfo;
3100 } else {
3101 VTableName = VMIClassTypeInfo;
3102 }
3103
3104 break;
3105 }
3106
3107 case Type::ObjCObject:
3108 // Ignore protocol qualifiers.
3109 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
3110
3111 // Handle id and Class.
3112 if (isa<BuiltinType>(Ty)) {
3113 VTableName = ClassTypeInfo;
3114 break;
3115 }
3116
3117 assert(isa<ObjCInterfaceType>(Ty));
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003118 LLVM_FALLTHROUGH;
David Majnemere2cb8d12014-07-07 06:20:47 +00003119
3120 case Type::ObjCInterface:
3121 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
3122 VTableName = SIClassTypeInfo;
3123 } else {
3124 VTableName = ClassTypeInfo;
3125 }
3126 break;
3127
3128 case Type::ObjCObjectPointer:
3129 case Type::Pointer:
3130 // abi::__pointer_type_info.
3131 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
3132 break;
3133
3134 case Type::MemberPointer:
3135 // abi::__pointer_to_member_type_info.
3136 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
3137 break;
3138 }
3139
3140 llvm::Constant *VTable =
3141 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00003142 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00003143
3144 llvm::Type *PtrDiffTy =
3145 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
3146
3147 // The vtable address point is 2.
3148 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00003149 VTable =
3150 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00003151 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3152
3153 Fields.push_back(VTable);
3154}
3155
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003156/// Return the linkage that the type info and type info name constants
David Majnemere2cb8d12014-07-07 06:20:47 +00003157/// should have for the given type.
Richard Smithbbb26552018-05-21 20:10:54 +00003158static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
3159 QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003160 // Itanium C++ ABI 2.9.5p7:
3161 // In addition, it and all of the intermediate abi::__pointer_type_info
3162 // structs in the chain down to the abi::__class_type_info for the
3163 // incomplete class type must be prevented from resolving to the
3164 // corresponding type_info structs for the complete class type, possibly
3165 // by making them local static objects. Finally, a dummy class RTTI is
3166 // generated for the incomplete type that will not resolve to the final
3167 // complete class RTTI (because the latter need not exist), possibly by
3168 // making it a local static object.
3169 if (ContainsIncompleteClassType(Ty))
Richard Smithbbb26552018-05-21 20:10:54 +00003170 return llvm::GlobalValue::InternalLinkage;
3171
3172 switch (Ty->getLinkage()) {
3173 case NoLinkage:
3174 case InternalLinkage:
3175 case UniqueExternalLinkage:
3176 return llvm::GlobalValue::InternalLinkage;
3177
3178 case VisibleNoLinkage:
3179 case ModuleInternalLinkage:
3180 case ModuleLinkage:
3181 case ExternalLinkage:
3182 // RTTI is not enabled, which means that this type info struct is going
3183 // to be used for exception handling. Give it linkonce_odr linkage.
3184 if (!CGM.getLangOpts().RTTI)
3185 return llvm::GlobalValue::LinkOnceODRLinkage;
3186
3187 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3188 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3189 if (RD->hasAttr<WeakAttr>())
3190 return llvm::GlobalValue::WeakODRLinkage;
3191 if (CGM.getTriple().isWindowsItaniumEnvironment())
3192 if (RD->hasAttr<DLLImportAttr>() &&
3193 ShouldUseExternalRTTIDescriptor(CGM, Ty))
3194 return llvm::GlobalValue::ExternalLinkage;
3195 // MinGW always uses LinkOnceODRLinkage for type info.
3196 if (RD->isDynamicClass() &&
3197 !CGM.getContext()
3198 .getTargetInfo()
3199 .getTriple()
3200 .isWindowsGNUEnvironment())
3201 return CGM.getVTableLinkage(RD);
3202 }
3203
3204 return llvm::GlobalValue::LinkOnceODRLinkage;
3205 }
3206
3207 llvm_unreachable("Invalid linkage!");
David Majnemere2cb8d12014-07-07 06:20:47 +00003208}
3209
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003210llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003211 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003212 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003213
3214 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003215 SmallString<256> Name;
3216 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003217 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003218
3219 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3220 if (OldGV && !OldGV->isDeclaration()) {
3221 assert(!OldGV->hasAvailableExternallyLinkage() &&
3222 "available_externally typeinfos not yet implemented");
3223
3224 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3225 }
3226
3227 // Check if there is already an external RTTI descriptor for this type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003228 if (IsStandardLibraryRTTIDescriptor(Ty) ||
3229 ShouldUseExternalRTTIDescriptor(CGM, Ty))
David Majnemere2cb8d12014-07-07 06:20:47 +00003230 return GetAddrOfExternalRTTIDescriptor(Ty);
3231
3232 // Emit the standard library with external linkage.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003233 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
Richard Smithbbb26552018-05-21 20:10:54 +00003234
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003235 // Give the type_info object and name the formal visibility of the
3236 // type itself.
3237 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3238 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3239 // If the linkage is local, only default visibility makes sense.
3240 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3241 else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
3242 ItaniumCXXABI::RUK_NonUniqueHidden)
3243 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3244 else
3245 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3246
3247 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3248 llvm::GlobalValue::DefaultStorageClass;
3249 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3250 auto RD = Ty->getAsCXXRecordDecl();
3251 if (RD && RD->hasAttr<DLLExportAttr>())
3252 DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
3253 }
3254
3255 return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
3256}
3257
3258llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
3259 QualType Ty,
3260 llvm::GlobalVariable::LinkageTypes Linkage,
3261 llvm::GlobalValue::VisibilityTypes Visibility,
3262 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003263 // Add the vtable pointer.
3264 BuildVTablePointer(cast<Type>(Ty));
3265
3266 // And the name.
Richard Smithbbb26552018-05-21 20:10:54 +00003267 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003268 llvm::Constant *TypeNameField;
3269
3270 // If we're supposed to demote the visibility, be sure to set a flag
3271 // to use a string comparison for type_info comparisons.
3272 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
Richard Smithbbb26552018-05-21 20:10:54 +00003273 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003274 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3275 // The flag is the sign bit, which on ARM64 is defined to be clear
3276 // for global pointers. This is very ARM64-specific.
3277 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3278 llvm::Constant *flag =
3279 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3280 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3281 TypeNameField =
3282 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3283 } else {
3284 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3285 }
3286 Fields.push_back(TypeNameField);
3287
3288 switch (Ty->getTypeClass()) {
3289#define TYPE(Class, Base)
3290#define ABSTRACT_TYPE(Class, Base)
3291#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3292#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3293#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3294#include "clang/AST/TypeNodes.def"
3295 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3296
3297 // GCC treats vector types as fundamental types.
3298 case Type::Builtin:
3299 case Type::Vector:
3300 case Type::ExtVector:
3301 case Type::Complex:
3302 case Type::BlockPointer:
3303 // Itanium C++ ABI 2.9.5p4:
3304 // abi::__fundamental_type_info adds no data members to std::type_info.
3305 break;
3306
3307 case Type::LValueReference:
3308 case Type::RValueReference:
3309 llvm_unreachable("References shouldn't get here");
3310
3311 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003312 case Type::DeducedTemplateSpecialization:
3313 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003314
Xiuli Pan9c14e282016-01-09 12:53:17 +00003315 case Type::Pipe:
3316 llvm_unreachable("Pipe type shouldn't get here");
3317
David Majnemere2cb8d12014-07-07 06:20:47 +00003318 case Type::ConstantArray:
3319 case Type::IncompleteArray:
3320 case Type::VariableArray:
3321 // Itanium C++ ABI 2.9.5p5:
3322 // abi::__array_type_info adds no data members to std::type_info.
3323 break;
3324
3325 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003326 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003327 // Itanium C++ ABI 2.9.5p5:
3328 // abi::__function_type_info adds no data members to std::type_info.
3329 break;
3330
3331 case Type::Enum:
3332 // Itanium C++ ABI 2.9.5p5:
3333 // abi::__enum_type_info adds no data members to std::type_info.
3334 break;
3335
3336 case Type::Record: {
3337 const CXXRecordDecl *RD =
3338 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3339 if (!RD->hasDefinition() || !RD->getNumBases()) {
3340 // We don't need to emit any fields.
3341 break;
3342 }
3343
3344 if (CanUseSingleInheritance(RD))
3345 BuildSIClassTypeInfo(RD);
3346 else
3347 BuildVMIClassTypeInfo(RD);
3348
3349 break;
3350 }
3351
3352 case Type::ObjCObject:
3353 case Type::ObjCInterface:
3354 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3355 break;
3356
3357 case Type::ObjCObjectPointer:
3358 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3359 break;
3360
3361 case Type::Pointer:
3362 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3363 break;
3364
3365 case Type::MemberPointer:
3366 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3367 break;
3368
3369 case Type::Atomic:
3370 // No fields, at least for the moment.
3371 break;
3372 }
3373
3374 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3375
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003376 SmallString<256> Name;
3377 llvm::raw_svector_ostream Out(Name);
3378 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003379 llvm::Module &M = CGM.getModule();
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003380 llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003381 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003382 new llvm::GlobalVariable(M, Init->getType(),
Richard Smithbbb26552018-05-21 20:10:54 +00003383 /*Constant=*/true, Linkage, Init, Name);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003384
David Majnemere2cb8d12014-07-07 06:20:47 +00003385 // If there's already an old global variable, replace it with the new one.
3386 if (OldGV) {
3387 GV->takeName(OldGV);
3388 llvm::Constant *NewPtr =
3389 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3390 OldGV->replaceAllUsesWith(NewPtr);
3391 OldGV->eraseFromParent();
3392 }
3393
Yaron Keren04da2382015-07-29 15:42:28 +00003394 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3395 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3396
David Greenbe0c5b62018-09-12 14:09:06 +00003397 CharUnits Align =
3398 CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
3399 GV->setAlignment(Align.getQuantity());
3400
David Majnemere2cb8d12014-07-07 06:20:47 +00003401 // The Itanium ABI specifies that type_info objects must be globally
3402 // unique, with one exception: if the type is an incomplete class
3403 // type or a (possibly indirect) pointer to one. That exception
3404 // affects the general case of comparing type_info objects produced
3405 // by the typeid operator, which is why the comparison operators on
3406 // std::type_info generally use the type_info name pointers instead
3407 // of the object addresses. However, the language's built-in uses
3408 // of RTTI generally require class types to be complete, even when
3409 // manipulating pointers to those class types. This allows the
3410 // implementation of dynamic_cast to rely on address equality tests,
3411 // which is much faster.
3412
3413 // All of this is to say that it's important that both the type_info
3414 // object and the type_info name be uniqued when weakly emitted.
3415
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003416 TypeName->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003417 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003418
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003419 GV->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003420 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003421
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003422 TypeName->setDLLStorageClass(DLLStorageClass);
3423 GV->setDLLStorageClass(DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00003424
Peter Collingbournee08e68d2019-06-07 19:10:08 +00003425 TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3426 GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3427
David Majnemere2cb8d12014-07-07 06:20:47 +00003428 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3429}
3430
David Majnemere2cb8d12014-07-07 06:20:47 +00003431/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3432/// for the given Objective-C object type.
3433void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3434 // Drop qualifiers.
3435 const Type *T = OT->getBaseType().getTypePtr();
3436 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3437
3438 // The builtin types are abi::__class_type_infos and don't require
3439 // extra fields.
3440 if (isa<BuiltinType>(T)) return;
3441
3442 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3443 ObjCInterfaceDecl *Super = Class->getSuperClass();
3444
3445 // Root classes are also __class_type_info.
3446 if (!Super) return;
3447
3448 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3449
3450 // Everything else is single inheritance.
3451 llvm::Constant *BaseTypeInfo =
3452 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3453 Fields.push_back(BaseTypeInfo);
3454}
3455
3456/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3457/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3458void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3459 // Itanium C++ ABI 2.9.5p6b:
3460 // It adds to abi::__class_type_info a single member pointing to the
3461 // type_info structure for the base type,
3462 llvm::Constant *BaseTypeInfo =
3463 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3464 Fields.push_back(BaseTypeInfo);
3465}
3466
3467namespace {
3468 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3469 /// a class hierarchy.
3470 struct SeenBases {
3471 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3472 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3473 };
3474}
3475
3476/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3477/// abi::__vmi_class_type_info.
3478///
3479static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3480 SeenBases &Bases) {
3481
3482 unsigned Flags = 0;
3483
3484 const CXXRecordDecl *BaseDecl =
3485 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3486
3487 if (Base->isVirtual()) {
3488 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003489 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003490 // If this virtual base has been seen before, then the class is diamond
3491 // shaped.
3492 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3493 } else {
3494 if (Bases.NonVirtualBases.count(BaseDecl))
3495 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3496 }
3497 } else {
3498 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003499 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003500 // If this non-virtual base has been seen before, then the class has non-
3501 // diamond shaped repeated inheritance.
3502 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3503 } else {
3504 if (Bases.VirtualBases.count(BaseDecl))
3505 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3506 }
3507 }
3508
3509 // Walk all bases.
3510 for (const auto &I : BaseDecl->bases())
3511 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3512
3513 return Flags;
3514}
3515
3516static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3517 unsigned Flags = 0;
3518 SeenBases Bases;
3519
3520 // Walk all bases.
3521 for (const auto &I : RD->bases())
3522 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3523
3524 return Flags;
3525}
3526
3527/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3528/// classes with bases that do not satisfy the abi::__si_class_type_info
3529/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3530void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3531 llvm::Type *UnsignedIntLTy =
3532 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3533
3534 // Itanium C++ ABI 2.9.5p6c:
3535 // __flags is a word with flags describing details about the class
3536 // structure, which may be referenced by using the __flags_masks
3537 // enumeration. These flags refer to both direct and indirect bases.
3538 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3539 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3540
3541 // Itanium C++ ABI 2.9.5p6c:
3542 // __base_count is a word with the number of direct proper base class
3543 // descriptions that follow.
3544 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3545
3546 if (!RD->getNumBases())
3547 return;
3548
David Majnemere2cb8d12014-07-07 06:20:47 +00003549 // Now add the base class descriptions.
3550
3551 // Itanium C++ ABI 2.9.5p6c:
3552 // __base_info[] is an array of base class descriptions -- one for every
3553 // direct proper base. Each description is of the type:
3554 //
3555 // struct abi::__base_class_type_info {
3556 // public:
3557 // const __class_type_info *__base_type;
3558 // long __offset_flags;
3559 //
3560 // enum __offset_flags_masks {
3561 // __virtual_mask = 0x1,
3562 // __public_mask = 0x2,
3563 // __offset_shift = 8
3564 // };
3565 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003566
3567 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3568 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3569 // LLP64 platforms.
3570 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3571 // LLP64 platforms.
3572 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3573 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3574 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3575 OffsetFlagsTy = CGM.getContext().LongLongTy;
3576 llvm::Type *OffsetFlagsLTy =
3577 CGM.getTypes().ConvertType(OffsetFlagsTy);
3578
David Majnemere2cb8d12014-07-07 06:20:47 +00003579 for (const auto &Base : RD->bases()) {
3580 // The __base_type member points to the RTTI for the base type.
3581 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3582
3583 const CXXRecordDecl *BaseDecl =
3584 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3585
3586 int64_t OffsetFlags = 0;
3587
3588 // All but the lower 8 bits of __offset_flags are a signed offset.
3589 // For a non-virtual base, this is the offset in the object of the base
3590 // subobject. For a virtual base, this is the offset in the virtual table of
3591 // the virtual base offset for the virtual base referenced (negative).
3592 CharUnits Offset;
3593 if (Base.isVirtual())
3594 Offset =
3595 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3596 else {
3597 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3598 Offset = Layout.getBaseClassOffset(BaseDecl);
3599 };
3600
3601 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3602
3603 // The low-order byte of __offset_flags contains flags, as given by the
3604 // masks from the enumeration __offset_flags_masks.
3605 if (Base.isVirtual())
3606 OffsetFlags |= BCTI_Virtual;
3607 if (Base.getAccessSpecifier() == AS_public)
3608 OffsetFlags |= BCTI_Public;
3609
Reid Klecknerd8b04662016-08-25 22:16:30 +00003610 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003611 }
3612}
3613
Richard Smitha7d93782016-12-01 03:32:42 +00003614/// Compute the flags for a __pbase_type_info, and remove the corresponding
3615/// pieces from \p Type.
3616static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3617 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003618
Richard Smitha7d93782016-12-01 03:32:42 +00003619 if (Type.isConstQualified())
3620 Flags |= ItaniumRTTIBuilder::PTI_Const;
3621 if (Type.isVolatileQualified())
3622 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3623 if (Type.isRestrictQualified())
3624 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3625 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003626
3627 // Itanium C++ ABI 2.9.5p7:
3628 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3629 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003630 if (ContainsIncompleteClassType(Type))
3631 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3632
3633 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003634 if (Proto->isNothrow()) {
Richard Smitha7d93782016-12-01 03:32:42 +00003635 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003636 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003637 }
3638 }
3639
3640 return Flags;
3641}
3642
3643/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3644/// used for pointer types.
3645void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3646 // Itanium C++ ABI 2.9.5p7:
3647 // __flags is a flag word describing the cv-qualification and other
3648 // attributes of the type pointed to
3649 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003650
3651 llvm::Type *UnsignedIntLTy =
3652 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3653 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3654
3655 // Itanium C++ ABI 2.9.5p7:
3656 // __pointee is a pointer to the std::type_info derivation for the
3657 // unqualified type being pointed to.
3658 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003659 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003660 Fields.push_back(PointeeTypeInfo);
3661}
3662
3663/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3664/// struct, used for member pointer types.
3665void
3666ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3667 QualType PointeeTy = Ty->getPointeeType();
3668
David Majnemere2cb8d12014-07-07 06:20:47 +00003669 // Itanium C++ ABI 2.9.5p7:
3670 // __flags is a flag word describing the cv-qualification and other
3671 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003672 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003673
3674 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003675 if (IsIncompleteClassType(ClassType))
3676 Flags |= PTI_ContainingClassIncomplete;
3677
3678 llvm::Type *UnsignedIntLTy =
3679 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3680 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3681
3682 // Itanium C++ ABI 2.9.5p7:
3683 // __pointee is a pointer to the std::type_info derivation for the
3684 // unqualified type being pointed to.
3685 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003686 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003687 Fields.push_back(PointeeTypeInfo);
3688
3689 // Itanium C++ ABI 2.9.5p9:
3690 // __context is a pointer to an abi::__class_type_info corresponding to the
3691 // class type containing the member pointed to
3692 // (e.g., the "A" in "int A::*").
3693 Fields.push_back(
3694 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3695}
3696
David Majnemer443250f2015-03-17 20:35:00 +00003697llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003698 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3699}
3700
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003701void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
Richard Smith4a382012016-02-03 01:32:42 +00003702 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003703 QualType FundamentalTypes[] = {
3704 getContext().VoidTy, getContext().NullPtrTy,
3705 getContext().BoolTy, getContext().WCharTy,
3706 getContext().CharTy, getContext().UnsignedCharTy,
3707 getContext().SignedCharTy, getContext().ShortTy,
3708 getContext().UnsignedShortTy, getContext().IntTy,
3709 getContext().UnsignedIntTy, getContext().LongTy,
3710 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003711 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3712 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003713 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003714 getContext().LongDoubleTy, getContext().Float128Ty,
Richard Smith3a8244d2018-05-01 05:02:45 +00003715 getContext().Char8Ty, getContext().Char16Ty,
3716 getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003717 };
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003718 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3719 RD->hasAttr<DLLExportAttr>()
3720 ? llvm::GlobalValue::DLLExportStorageClass
3721 : llvm::GlobalValue::DefaultStorageClass;
3722 llvm::GlobalValue::VisibilityTypes Visibility =
3723 CodeGenModule::GetLLVMVisibility(RD->getVisibility());
3724 for (const QualType &FundamentalType : FundamentalTypes) {
3725 QualType PointerType = getContext().getPointerType(FundamentalType);
3726 QualType PointerTypeConst = getContext().getPointerType(
3727 FundamentalType.withConst());
3728 for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
3729 ItaniumRTTIBuilder(*this).BuildTypeInfo(
3730 Type, llvm::GlobalValue::ExternalLinkage,
3731 Visibility, DLLStorageClass);
3732 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003733}
3734
3735/// What sort of uniqueness rules should we use for the RTTI for the
3736/// given type?
3737ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3738 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3739 if (shouldRTTIBeUnique())
3740 return RUK_Unique;
3741
3742 // It's only necessary for linkonce_odr or weak_odr linkage.
3743 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3744 Linkage != llvm::GlobalValue::WeakODRLinkage)
3745 return RUK_Unique;
3746
3747 // It's only necessary with default visibility.
3748 if (CanTy->getVisibility() != DefaultVisibility)
3749 return RUK_Unique;
3750
3751 // If we're not required to publish this symbol, hide it.
3752 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3753 return RUK_NonUniqueHidden;
3754
3755 // If we're required to publish this symbol, as we might be under an
3756 // explicit instantiation, leave it with default visibility but
3757 // enable string-comparisons.
3758 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3759 return RUK_NonUniqueVisible;
3760}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003761
Rafael Espindola1e4df922014-09-16 15:18:21 +00003762// Find out how to codegen the complete destructor and constructor
3763namespace {
3764enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3765}
3766static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3767 const CXXMethodDecl *MD) {
3768 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3769 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003770
Rafael Espindola1e4df922014-09-16 15:18:21 +00003771 // The complete and base structors are not equivalent if there are any virtual
3772 // bases, so emit separate functions.
3773 if (MD->getParent()->getNumVBases())
3774 return StructorCodegen::Emit;
3775
3776 GlobalDecl AliasDecl;
3777 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3778 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3779 } else {
3780 const auto *CD = cast<CXXConstructorDecl>(MD);
3781 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3782 }
3783 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3784
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003785 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3786 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003787
Pavel Labathc370f262018-05-14 11:35:44 +00003788 // FIXME: Should we allow available_externally aliases?
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003789 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3790 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003791
Rafael Espindola0806f982014-09-16 20:19:43 +00003792 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003793 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3794 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3795 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003796 return StructorCodegen::COMDAT;
3797 return StructorCodegen::Emit;
3798 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003799
3800 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003801}
3802
Rafael Espindola1e4df922014-09-16 15:18:21 +00003803static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3804 GlobalDecl AliasDecl,
3805 GlobalDecl TargetDecl) {
3806 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3807
3808 StringRef MangledName = CGM.getMangledName(AliasDecl);
3809 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3810 if (Entry && !Entry->isDeclaration())
3811 return;
3812
3813 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003814
3815 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003816 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003817
Peter Collingbourned914fd22018-06-18 20:58:54 +00003818 // Constructors and destructors are always unnamed_addr.
3819 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3820
Rafael Espindola1e4df922014-09-16 15:18:21 +00003821 // Switch any previous uses to the alias.
3822 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003823 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003824 "declaration exists with different type");
3825 Alias->takeName(Entry);
3826 Entry->replaceAllUsesWith(Alias);
3827 Entry->eraseFromParent();
3828 } else {
3829 Alias->setName(MangledName);
3830 }
3831
3832 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003833 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003834}
3835
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003836void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
3837 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003838 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3839 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3840
3841 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3842
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003843 if (CD ? GD.getCtorType() == Ctor_Complete
3844 : GD.getDtorType() == Dtor_Complete) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00003845 GlobalDecl BaseDecl;
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003846 if (CD)
3847 BaseDecl = GD.getWithCtorType(Ctor_Base);
3848 else
3849 BaseDecl = GD.getWithDtorType(Dtor_Base);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003850
3851 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003852 emitConstructorDestructorAlias(CGM, GD, BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003853 return;
3854 }
3855
3856 if (CGType == StructorCodegen::RAUW) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003857 StringRef MangledName = CGM.getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003858 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003859 CGM.addReplacement(MangledName, Aliasee);
3860 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003861 }
3862 }
3863
3864 // The base destructor is equivalent to the base destructor of its
3865 // base class if there is exactly one non-virtual base class with a
3866 // non-trivial destructor, there are no fields with a non-trivial
3867 // destructor, and the body of the destructor is trivial.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003868 if (DD && GD.getDtorType() == Dtor_Base &&
3869 CGType != StructorCodegen::COMDAT &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003870 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003871 return;
3872
Richard Smith5b349582017-10-13 01:55:36 +00003873 // FIXME: The deleting destructor is equivalent to the selected operator
3874 // delete if:
3875 // * either the delete is a destroying operator delete or the destructor
3876 // would be trivial if it weren't virtual,
3877 // * the conversion from the 'this' parameter to the first parameter of the
3878 // destructor is equivalent to a bitcast,
3879 // * the destructor does not have an implicit "this" return, and
3880 // * the operator delete has the same calling convention and IR function type
3881 // as the destructor.
3882 // In such cases we should try to emit the deleting dtor as an alias to the
3883 // selected 'operator delete'.
3884
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003885 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003886
Rafael Espindola1e4df922014-09-16 15:18:21 +00003887 if (CGType == StructorCodegen::COMDAT) {
3888 SmallString<256> Buffer;
3889 llvm::raw_svector_ostream Out(Buffer);
3890 if (DD)
3891 getMangleContext().mangleCXXDtorComdat(DD, Out);
3892 else
3893 getMangleContext().mangleCXXCtorComdat(CD, Out);
3894 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3895 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003896 } else {
3897 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003898 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003899}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003900
James Y Knight9871db02019-02-05 16:42:33 +00003901static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003902 // void *__cxa_begin_catch(void*);
3903 llvm::FunctionType *FTy = llvm::FunctionType::get(
3904 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3905
3906 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3907}
3908
James Y Knight9871db02019-02-05 16:42:33 +00003909static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003910 // void __cxa_end_catch();
3911 llvm::FunctionType *FTy =
3912 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3913
3914 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3915}
3916
James Y Knight9871db02019-02-05 16:42:33 +00003917static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003918 // void *__cxa_get_exception_ptr(void*);
3919 llvm::FunctionType *FTy = llvm::FunctionType::get(
3920 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3921
3922 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3923}
3924
3925namespace {
3926 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3927 /// exception type lets us state definitively that the thrown exception
3928 /// type does not have a destructor. In particular:
3929 /// - Catch-alls tell us nothing, so we have to conservatively
3930 /// assume that the thrown exception might have a destructor.
3931 /// - Catches by reference behave according to their base types.
3932 /// - Catches of non-record types will only trigger for exceptions
3933 /// of non-record types, which never have destructors.
3934 /// - Catches of record types can trigger for arbitrary subclasses
3935 /// of the caught type, so we have to assume the actual thrown
3936 /// exception type might have a throwing destructor, even if the
3937 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003938 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003939 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3940 bool MightThrow;
3941
3942 void Emit(CodeGenFunction &CGF, Flags flags) override {
3943 if (!MightThrow) {
3944 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3945 return;
3946 }
3947
3948 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3949 }
3950 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003951}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003952
3953/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3954/// __cxa_end_catch.
3955///
3956/// \param EndMightThrow - true if __cxa_end_catch might throw
3957static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3958 llvm::Value *Exn,
3959 bool EndMightThrow) {
3960 llvm::CallInst *call =
3961 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3962
3963 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3964
3965 return call;
3966}
3967
3968/// A "special initializer" callback for initializing a catch
3969/// parameter during catch initialization.
3970static void InitCatchParam(CodeGenFunction &CGF,
3971 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003972 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003973 SourceLocation Loc) {
3974 // Load the exception from where the landing pad saved it.
3975 llvm::Value *Exn = CGF.getExceptionFromSlot();
3976
3977 CanQualType CatchType =
3978 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3979 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3980
3981 // If we're catching by reference, we can just cast the object
3982 // pointer to the appropriate pointer.
3983 if (isa<ReferenceType>(CatchType)) {
3984 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3985 bool EndCatchMightThrow = CaughtType->isRecordType();
3986
3987 // __cxa_begin_catch returns the adjusted object pointer.
3988 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3989
3990 // We have no way to tell the personality function that we're
3991 // catching by reference, so if we're catching a pointer,
3992 // __cxa_begin_catch will actually return that pointer by value.
3993 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3994 QualType PointeeType = PT->getPointeeType();
3995
3996 // When catching by reference, generally we should just ignore
3997 // this by-value pointer and use the exception object instead.
3998 if (!PointeeType->isRecordType()) {
3999
4000 // Exn points to the struct _Unwind_Exception header, which
4001 // we have to skip past in order to reach the exception data.
4002 unsigned HeaderSize =
4003 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
4004 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
4005
4006 // However, if we're catching a pointer-to-record type that won't
4007 // work, because the personality function might have adjusted
4008 // the pointer. There's actually no way for us to fully satisfy
4009 // the language/ABI contract here: we can't use Exn because it
4010 // might have the wrong adjustment, but we can't use the by-value
4011 // pointer because it's off by a level of abstraction.
4012 //
4013 // The current solution is to dump the adjusted pointer into an
4014 // alloca, which breaks language semantics (because changing the
4015 // pointer doesn't change the exception) but at least works.
4016 // The better solution would be to filter out non-exact matches
4017 // and rethrow them, but this is tricky because the rethrow
4018 // really needs to be catchable by other sites at this landing
4019 // pad. The best solution is to fix the personality function.
4020 } else {
4021 // Pull the pointer for the reference type off.
4022 llvm::Type *PtrTy =
4023 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
4024
4025 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00004026 Address ExnPtrTmp =
4027 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004028 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4029 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
4030
4031 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00004032 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004033 }
4034 }
4035
4036 llvm::Value *ExnCast =
4037 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
4038 CGF.Builder.CreateStore(ExnCast, ParamAddr);
4039 return;
4040 }
4041
4042 // Scalars and complexes.
4043 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
4044 if (TEK != TEK_Aggregate) {
4045 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
4046
4047 // If the catch type is a pointer type, __cxa_begin_catch returns
4048 // the pointer by value.
4049 if (CatchType->hasPointerRepresentation()) {
4050 llvm::Value *CastExn =
4051 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
4052
4053 switch (CatchType.getQualifiers().getObjCLifetime()) {
4054 case Qualifiers::OCL_Strong:
4055 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004056 LLVM_FALLTHROUGH;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004057
4058 case Qualifiers::OCL_None:
4059 case Qualifiers::OCL_ExplicitNone:
4060 case Qualifiers::OCL_Autoreleasing:
4061 CGF.Builder.CreateStore(CastExn, ParamAddr);
4062 return;
4063
4064 case Qualifiers::OCL_Weak:
4065 CGF.EmitARCInitWeak(ParamAddr, CastExn);
4066 return;
4067 }
4068 llvm_unreachable("bad ownership qualifier!");
4069 }
4070
4071 // Otherwise, it returns a pointer into the exception object.
4072
4073 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4074 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4075
4076 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00004077 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004078 switch (TEK) {
4079 case TEK_Complex:
4080 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
4081 /*init*/ true);
4082 return;
4083 case TEK_Scalar: {
4084 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
4085 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
4086 return;
4087 }
4088 case TEK_Aggregate:
4089 llvm_unreachable("evaluation kind filtered out!");
4090 }
4091 llvm_unreachable("bad evaluation kind");
4092 }
4093
4094 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00004095 auto catchRD = CatchType->getAsCXXRecordDecl();
4096 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004097
4098 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4099
4100 // Check for a copy expression. If we don't have a copy expression,
4101 // that means a trivial copy is okay.
4102 const Expr *copyExpr = CatchParam.getInit();
4103 if (!copyExpr) {
4104 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00004105 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4106 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004107 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
4108 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
Richard Smithe78fac52018-04-05 20:52:58 +00004109 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004110 return;
4111 }
4112
4113 // We have to call __cxa_get_exception_ptr to get the adjusted
4114 // pointer before copying.
4115 llvm::CallInst *rawAdjustedExn =
4116 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
4117
4118 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00004119 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4120 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004121
4122 // The copy expression is defined in terms of an OpaqueValueExpr.
4123 // Find it and map it to the adjusted expression.
4124 CodeGenFunction::OpaqueValueMapping
4125 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
4126 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
4127
4128 // Call the copy ctor in a terminate scope.
4129 CGF.EHStack.pushTerminate();
4130
4131 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004132 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00004133 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004134 AggValueSlot::IsNotDestructed,
4135 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00004136 AggValueSlot::IsNotAliased,
4137 AggValueSlot::DoesNotOverlap));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004138
4139 // Leave the terminate scope.
4140 CGF.EHStack.popTerminate();
4141
4142 // Undo the opaque value mapping.
4143 opaque.pop();
4144
4145 // Finally we can call __cxa_begin_catch.
4146 CallBeginCatch(CGF, Exn, true);
4147}
4148
4149/// Begins a catch statement by initializing the catch variable and
4150/// calling __cxa_begin_catch.
4151void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4152 const CXXCatchStmt *S) {
4153 // We have to be very careful with the ordering of cleanups here:
4154 // C++ [except.throw]p4:
4155 // The destruction [of the exception temporary] occurs
4156 // immediately after the destruction of the object declared in
4157 // the exception-declaration in the handler.
4158 //
4159 // So the precise ordering is:
4160 // 1. Construct catch variable.
4161 // 2. __cxa_begin_catch
4162 // 3. Enter __cxa_end_catch cleanup
4163 // 4. Enter dtor cleanup
4164 //
4165 // We do this by using a slightly abnormal initialization process.
4166 // Delegation sequence:
4167 // - ExitCXXTryStmt opens a RunCleanupsScope
4168 // - EmitAutoVarAlloca creates the variable and debug info
4169 // - InitCatchParam initializes the variable from the exception
4170 // - CallBeginCatch calls __cxa_begin_catch
4171 // - CallBeginCatch enters the __cxa_end_catch cleanup
4172 // - EmitAutoVarCleanups enters the variable destructor cleanup
4173 // - EmitCXXTryStmt emits the code for the catch body
4174 // - EmitCXXTryStmt close the RunCleanupsScope
4175
4176 VarDecl *CatchParam = S->getExceptionDecl();
4177 if (!CatchParam) {
4178 llvm::Value *Exn = CGF.getExceptionFromSlot();
4179 CallBeginCatch(CGF, Exn, true);
4180 return;
4181 }
4182
4183 // Emit the local.
4184 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004185 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004186 CGF.EmitAutoVarCleanups(var);
4187}
4188
4189/// Get or define the following function:
4190/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
4191/// This code is used only in C++.
James Y Knight9871db02019-02-05 16:42:33 +00004192static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004193 llvm::FunctionType *fnTy =
4194 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
James Y Knight9871db02019-02-05 16:42:33 +00004195 llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
4196 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*IsLocal=*/true);
4197 llvm::Function *fn =
4198 cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
4199 if (fn->empty()) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004200 fn->setDoesNotThrow();
4201 fn->setDoesNotReturn();
4202
4203 // What we really want is to massively penalize inlining without
4204 // forbidding it completely. The difference between that and
4205 // 'noinline' is negligible.
4206 fn->addFnAttr(llvm::Attribute::NoInline);
4207
4208 // Allow this function to be shared across translation units, but
4209 // we don't want it to turn into an exported symbol.
4210 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4211 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004212 if (CGM.supportsCOMDAT())
4213 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004214
4215 // Set up the function.
4216 llvm::BasicBlock *entry =
James Y Knight9871db02019-02-05 16:42:33 +00004217 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004218 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004219
4220 // Pull the exception pointer out of the parameter list.
4221 llvm::Value *exn = &*fn->arg_begin();
4222
4223 // Call __cxa_begin_catch(exn).
4224 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4225 catchCall->setDoesNotThrow();
4226 catchCall->setCallingConv(CGM.getRuntimeCC());
4227
4228 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004229 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004230 termCall->setDoesNotThrow();
4231 termCall->setDoesNotReturn();
4232 termCall->setCallingConv(CGM.getRuntimeCC());
4233
4234 // std::terminate cannot return.
4235 builder.CreateUnreachable();
4236 }
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004237 return fnRef;
4238}
4239
4240llvm::CallInst *
4241ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4242 llvm::Value *Exn) {
4243 // In C++, we want to call __cxa_begin_catch() before terminating.
4244 if (Exn) {
4245 assert(CGF.CGM.getLangOpts().CPlusPlus);
4246 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4247 }
4248 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4249}
Peter Collingbourne60108802017-12-13 21:53:04 +00004250
4251std::pair<llvm::Value *, const CXXRecordDecl *>
4252ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4253 const CXXRecordDecl *RD) {
4254 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4255}
Heejin Ahnc6479192018-05-31 22:18:13 +00004256
4257void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4258 const CXXCatchStmt *C) {
Heejin Ahn1eb074d2018-06-01 01:01:37 +00004259 if (CGF.getTarget().hasFeature("exception-handling"))
4260 CGF.EHStack.pushCleanup<CatchRetScope>(
4261 NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
Heejin Ahnc6479192018-05-31 22:18:13 +00004262 ItaniumCXXABI::emitBeginCatch(CGF, C);
4263}