blob: 7367ff37cf45c84599f01318f16f3b96fda344a5 [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 =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001141 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
David Majnemer442d0a22014-11-25 07:20:20 +00001142
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 =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001155 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
David Majnemer7c237072015-03-05 00:46:22 +00001156
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 =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001166 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
David Majnemer7c237072015-03-05 00:46:22 +00001167
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
Anastasia Stulova960ff082019-07-15 11:58:10 +00002287 // Preserve address space of addr.
2288 auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
2289 auto AddrInt8PtrTy =
2290 AddrAS ? CGF.Int8Ty->getPointerTo(AddrAS) : CGF.Int8PtrTy;
2291
2292 // Create a variable that binds the atexit to this shared object.
2293 llvm::Constant *handle =
2294 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2295 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2296 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2297
John McCallc84ed6a2012-05-01 06:13:13 +00002298 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
Anastasia Stulova960ff082019-07-15 11:58:10 +00002299 llvm::Type *paramTys[] = {dtorTy, AddrInt8PtrTy, handle->getType()};
John McCallc84ed6a2012-05-01 06:13:13 +00002300 llvm::FunctionType *atexitTy =
2301 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2302
2303 // Fetch the actual function.
James Y Knight9871db02019-02-05 16:42:33 +00002304 llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2305 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
John McCallc84ed6a2012-05-01 06:13:13 +00002306 fn->setDoesNotThrow();
2307
Akira Hatanaka617e2612018-04-17 18:41:52 +00002308 if (!addr)
2309 // addr is null when we are trying to register a dtor annotated with
2310 // __attribute__((destructor)) in a constructor function. Using null here is
2311 // okay because this argument is just passed back to the destructor
2312 // function.
2313 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2314
James Y Knightf7321542019-02-07 01:14:17 +00002315 llvm::Value *args[] = {llvm::ConstantExpr::getBitCast(
2316 cast<llvm::Constant>(dtor.getCallee()), dtorTy),
Anastasia Stulova960ff082019-07-15 11:58:10 +00002317 llvm::ConstantExpr::getBitCast(addr, AddrInt8PtrTy),
James Y Knightf7321542019-02-07 01:14:17 +00002318 handle};
John McCall882987f2013-02-28 19:01:20 +00002319 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002320}
2321
Akira Hatanaka617e2612018-04-17 18:41:52 +00002322void CodeGenModule::registerGlobalDtorsWithAtExit() {
2323 for (const auto I : DtorsUsingAtExit) {
2324 int Priority = I.first;
2325 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2326
2327 // Create a function that registers destructors that have the same priority.
2328 //
2329 // Since constructor functions are run in non-descending order of their
2330 // priorities, destructors are registered in non-descending order of their
2331 // priorities, and since destructor functions are run in the reverse order
2332 // of their registration, destructor functions are run in non-ascending
2333 // order of their priorities.
2334 CodeGenFunction CGF(*this);
2335 std::string GlobalInitFnName =
2336 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2337 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2338 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2339 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2340 SourceLocation());
2341 ASTContext &Ctx = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002342 QualType ReturnTy = Ctx.VoidTy;
2343 QualType FunctionTy = Ctx.getFunctionType(ReturnTy, llvm::None, {});
Akira Hatanaka617e2612018-04-17 18:41:52 +00002344 FunctionDecl *FD = FunctionDecl::Create(
2345 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002346 &Ctx.Idents.get(GlobalInitFnName), FunctionTy, nullptr, SC_Static,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002347 false, false);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002348 CGF.StartFunction(GlobalDecl(FD), ReturnTy, GlobalInitFn,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002349 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2350 SourceLocation(), SourceLocation());
2351
2352 for (auto *Dtor : Dtors) {
2353 // Register the destructor function calling __cxa_atexit if it is
2354 // available. Otherwise fall back on calling atexit.
2355 if (getCodeGenOpts().CXAAtExit)
2356 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2357 else
2358 CGF.registerGlobalDtorWithAtExit(Dtor);
2359 }
2360
2361 CGF.FinishFunction();
2362 AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2363 }
2364}
2365
John McCallc84ed6a2012-05-01 06:13:13 +00002366/// Register a global destructor as best as we know how.
James Y Knightf7321542019-02-07 01:14:17 +00002367void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2368 llvm::FunctionCallee dtor,
John McCallc84ed6a2012-05-01 06:13:13 +00002369 llvm::Constant *addr) {
Erik Pilkington5a559e62018-08-21 17:24:06 +00002370 if (D.isNoDestroy(CGM.getContext()))
2371 return;
2372
Erich Keane34ec6922019-06-13 18:20:19 +00002373 // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
2374 // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
2375 // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
2376 // We can always use __cxa_thread_atexit.
2377 if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
Richard Smithdbf74ba2013-04-14 23:01:42 +00002378 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2379
John McCallc84ed6a2012-05-01 06:13:13 +00002380 // In Apple kexts, we want to add a global destructor entry.
2381 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002382 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002383 // Generate a global destructor entry.
2384 return CGM.AddCXXDtorEntry(dtor, addr);
2385 }
2386
David Blaikieebe87e12013-08-27 23:57:18 +00002387 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002388}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002389
David Majnemer9b21c332014-07-11 20:28:10 +00002390static bool isThreadWrapperReplaceable(const VarDecl *VD,
2391 CodeGen::CodeGenModule &CGM) {
2392 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002393 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002394 // the thread wrapper instead of directly referencing the backing variable.
2395 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002396 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002397}
2398
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002399/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002400/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002401/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002402static llvm::GlobalValue::LinkageTypes
2403getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2404 llvm::GlobalValue::LinkageTypes VarLinkage =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002405 CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
David Majnemer35ab3282014-06-11 04:08:55 +00002406
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002407 // For internal linkage variables, we don't need an external or weak wrapper.
2408 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2409 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002410
David Majnemer9b21c332014-07-11 20:28:10 +00002411 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002412 if (isThreadWrapperReplaceable(VD, CGM))
2413 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2414 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2415 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002416 return llvm::GlobalValue::WeakODRLinkage;
2417}
2418
2419llvm::Function *
2420ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002421 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002422 // Mangle the name for the thread_local wrapper function.
2423 SmallString<256> WrapperName;
2424 {
2425 llvm::raw_svector_ostream Out(WrapperName);
2426 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002427 }
2428
Akira Hatanaka26907f92016-01-15 03:34:06 +00002429 // FIXME: If VD is a definition, we should regenerate the function attributes
2430 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002431 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002432 return cast<llvm::Function>(V);
2433
Akira Hatanaka26907f92016-01-15 03:34:06 +00002434 QualType RetQT = VD->getType();
2435 if (RetQT->isReferenceType())
2436 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002437
John McCallc56a8b32016-03-11 04:30:31 +00002438 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2439 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002440
2441 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002442 llvm::Function *Wrapper =
2443 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2444 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002445
Erich Keanede6480a32018-11-13 15:48:08 +00002446 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper);
Akira Hatanaka26907f92016-01-15 03:34:06 +00002447
2448 if (VD->hasDefinition())
2449 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2450
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002451 // Always resolve references to the wrapper at link time.
Vlad Tsyrklevichc93390b2019-01-17 17:53:45 +00002452 if (!Wrapper->hasLocalLinkage())
2453 if (!isThreadWrapperReplaceable(VD, CGM) ||
2454 llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
2455 llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
2456 VD->getVisibility() == HiddenVisibility)
2457 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002458
2459 if (isThreadWrapperReplaceable(VD, CGM)) {
2460 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2461 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2462 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002463 return Wrapper;
2464}
2465
2466void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002467 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2468 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2469 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002470 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002471
2472 // Separate initializers into those with ordered (or partially-ordered)
2473 // initialization and those with unordered initialization.
2474 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2475 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2476 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2477 if (isTemplateInstantiation(
2478 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2479 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2480 CXXThreadLocalInits[I];
2481 else
2482 OrderedInits.push_back(CXXThreadLocalInits[I]);
2483 }
2484
2485 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002486 // Generate a guarded initialization function.
2487 llvm::FunctionType *FTy =
2488 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002489 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2490 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002491 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002492 /*TLS=*/true);
2493 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2494 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2495 llvm::GlobalVariable::InternalLinkage,
2496 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2497 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002498
2499 CharUnits GuardAlign = CharUnits::One();
2500 Guard->setAlignment(GuardAlign.getQuantity());
2501
Richard Smith3ad06362018-10-31 20:39:26 +00002502 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
2503 InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002504 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2505 if (CGM.getTarget().getTriple().isOSDarwin()) {
2506 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2507 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2508 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002509 }
Richard Smithfbe23692017-01-13 00:43:31 +00002510
2511 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002512 for (const VarDecl *VD : CXXThreadLocals) {
2513 llvm::GlobalVariable *Var =
2514 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002515 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002516
David Majnemer9b21c332014-07-11 20:28:10 +00002517 // Some targets require that all access to thread local variables go through
2518 // the thread wrapper. This means that we cannot attempt to create a thread
2519 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002520 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2521 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002522 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002523 }
David Majnemer9b21c332014-07-11 20:28:10 +00002524
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002525 // Mangle the name for the thread_local initialization function.
2526 SmallString<256> InitFnName;
2527 {
2528 llvm::raw_svector_ostream Out(InitFnName);
2529 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002530 }
2531
James Y Knightf7321542019-02-07 01:14:17 +00002532 llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2533
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002534 // If we have a definition for the variable, emit the initialization
2535 // function as an alias to the global Init function (if any). Otherwise,
2536 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002537 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002538 bool InitIsInitFunc = false;
2539 if (VD->hasDefinition()) {
2540 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002541 llvm::Function *InitFuncToUse = InitFunc;
2542 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2543 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2544 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002545 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002546 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002547 } else {
2548 // Emit a weak global function referring to the initialization function.
2549 // This function will not exist if the TU defining the thread_local
2550 // variable in question does not need any dynamic initialization for
2551 // its thread_local variables.
James Y Knightf7321542019-02-07 01:14:17 +00002552 Init = llvm::Function::Create(InitFnTy,
Richard Smithfbe23692017-01-13 00:43:31 +00002553 llvm::GlobalVariable::ExternalWeakLinkage,
2554 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002555 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Erich Keanede6480a32018-11-13 15:48:08 +00002556 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
2557 cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002558 }
2559
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002560 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002561 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002562 Init->setDSOLocal(Var->isDSOLocal());
2563 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002564
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002565 llvm::LLVMContext &Context = CGM.getModule().getContext();
2566 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002567 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002568 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002569 if (Init) {
James Y Knightf7321542019-02-07 01:14:17 +00002570 llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002571 if (isThreadWrapperReplaceable(VD, CGM)) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002572 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002573 llvm::Function *Fn =
2574 cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
2575 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2576 }
Manman Ren5e5d0462016-03-18 23:35:21 +00002577 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002578 } else {
2579 // Don't know whether we have an init function. Call it if it exists.
2580 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2581 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2582 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2583 Builder.CreateCondBr(Have, InitBB, ExitBB);
2584
2585 Builder.SetInsertPoint(InitBB);
James Y Knightf7321542019-02-07 01:14:17 +00002586 Builder.CreateCall(InitFnTy, Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002587 Builder.CreateBr(ExitBB);
2588
2589 Builder.SetInsertPoint(ExitBB);
2590 }
2591
2592 // For a reference, the result of the wrapper function is a pointer to
2593 // the referenced object.
2594 llvm::Value *Val = Var;
2595 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002596 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2597 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002598 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002599 if (Val->getType() != Wrapper->getReturnType())
2600 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2601 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002602 Builder.CreateRet(Val);
2603 }
2604}
2605
Richard Smith0f383742014-03-26 22:48:22 +00002606LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2607 const VarDecl *VD,
2608 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002609 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002610 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002611
Manman Renb0b3af72015-12-17 00:42:36 +00002612 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002613 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002614
2615 LValue LV;
2616 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002617 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002618 else
Manman Renb0b3af72015-12-17 00:42:36 +00002619 LV = CGF.MakeAddrLValue(CallVal, LValType,
2620 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002621 // FIXME: need setObjCGCLValueClass?
2622 return LV;
2623}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002624
2625/// Return whether the given global decl needs a VTT parameter, which it does
2626/// if it's a base constructor or destructor with virtual bases.
2627bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2628 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002629
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002630 // We don't have any virtual bases, just return early.
2631 if (!MD->getParent()->getNumVBases())
2632 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002633
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002634 // Check if we have a base constructor.
2635 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2636 return true;
2637
2638 // Check if we have a base destructor.
2639 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2640 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002641
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002642 return false;
2643}
David Majnemere2cb8d12014-07-07 06:20:47 +00002644
2645namespace {
2646class ItaniumRTTIBuilder {
2647 CodeGenModule &CGM; // Per-module state.
2648 llvm::LLVMContext &VMContext;
2649 const ItaniumCXXABI &CXXABI; // Per-module state.
2650
2651 /// Fields - The fields of the RTTI descriptor currently being built.
2652 SmallVector<llvm::Constant *, 16> Fields;
2653
2654 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2655 llvm::GlobalVariable *
2656 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2657
2658 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2659 /// descriptor of the given type.
2660 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2661
2662 /// BuildVTablePointer - Build the vtable pointer for the given type.
2663 void BuildVTablePointer(const Type *Ty);
2664
2665 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2666 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2667 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2668
2669 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2670 /// classes with bases that do not satisfy the abi::__si_class_type_info
2671 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2672 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2673
2674 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2675 /// for pointer types.
2676 void BuildPointerTypeInfo(QualType PointeeTy);
2677
2678 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2679 /// type_info for an object type.
2680 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2681
2682 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2683 /// struct, used for member pointer types.
2684 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2685
2686public:
2687 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2688 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2689
2690 // Pointer type info flags.
2691 enum {
2692 /// PTI_Const - Type has const qualifier.
2693 PTI_Const = 0x1,
2694
2695 /// PTI_Volatile - Type has volatile qualifier.
2696 PTI_Volatile = 0x2,
2697
2698 /// PTI_Restrict - Type has restrict qualifier.
2699 PTI_Restrict = 0x4,
2700
2701 /// PTI_Incomplete - Type is incomplete.
2702 PTI_Incomplete = 0x8,
2703
2704 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2705 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002706 PTI_ContainingClassIncomplete = 0x10,
2707
2708 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2709 //PTI_TransactionSafe = 0x20,
2710
2711 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2712 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002713 };
2714
2715 // VMI type info flags.
2716 enum {
2717 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2718 VMI_NonDiamondRepeat = 0x1,
2719
2720 /// VMI_DiamondShaped - Class is diamond shaped.
2721 VMI_DiamondShaped = 0x2
2722 };
2723
2724 // Base class type info flags.
2725 enum {
2726 /// BCTI_Virtual - Base class is virtual.
2727 BCTI_Virtual = 0x1,
2728
2729 /// BCTI_Public - Base class is public.
2730 BCTI_Public = 0x2
2731 };
2732
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002733 /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
2734 /// link to an existing RTTI descriptor if one already exists.
2735 llvm::Constant *BuildTypeInfo(QualType Ty);
2736
David Majnemere2cb8d12014-07-07 06:20:47 +00002737 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002738 llvm::Constant *BuildTypeInfo(
2739 QualType Ty,
2740 llvm::GlobalVariable::LinkageTypes Linkage,
2741 llvm::GlobalValue::VisibilityTypes Visibility,
2742 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00002743};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002744}
David Majnemere2cb8d12014-07-07 06:20:47 +00002745
2746llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2747 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002748 SmallString<256> Name;
2749 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002750 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002751
2752 // We know that the mangled name of the type starts at index 4 of the
2753 // mangled name of the typename, so we can just index into it in order to
2754 // get the mangled name of the type.
2755 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2756 Name.substr(4));
David Greenbe0c5b62018-09-12 14:09:06 +00002757 auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00002758
David Greenbe0c5b62018-09-12 14:09:06 +00002759 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2760 Name, Init->getType(), Linkage, Align.getQuantity());
David Majnemere2cb8d12014-07-07 06:20:47 +00002761
2762 GV->setInitializer(Init);
2763
2764 return GV;
2765}
2766
2767llvm::Constant *
2768ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2769 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002770 SmallString<256> Name;
2771 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002772 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002773
2774 // Look for an existing global.
2775 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2776
2777 if (!GV) {
2778 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002779 // Note for the future: If we would ever like to do deferred emission of
2780 // RTTI, check if emitting vtables opportunistically need any adjustment.
2781
David Majnemere2cb8d12014-07-07 06:20:47 +00002782 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002783 /*isConstant=*/true,
David Majnemere2cb8d12014-07-07 06:20:47 +00002784 llvm::GlobalValue::ExternalLinkage, nullptr,
2785 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002786 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2787 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002788 }
2789
2790 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2791}
2792
2793/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2794/// info for that type is defined in the standard library.
2795static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2796 // Itanium C++ ABI 2.9.2:
2797 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2798 // the run-time support library. Specifically, the run-time support
2799 // library should contain type_info objects for the types X, X* and
2800 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2801 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2802 // long, unsigned long, long long, unsigned long long, float, double,
2803 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2804 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002805 //
2806 // GCC also emits RTTI for __int128.
2807 // FIXME: We do not emit RTTI information for decimal types here.
2808
2809 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002810 switch (Ty->getKind()) {
2811 case BuiltinType::Void:
2812 case BuiltinType::NullPtr:
2813 case BuiltinType::Bool:
2814 case BuiltinType::WChar_S:
2815 case BuiltinType::WChar_U:
2816 case BuiltinType::Char_U:
2817 case BuiltinType::Char_S:
2818 case BuiltinType::UChar:
2819 case BuiltinType::SChar:
2820 case BuiltinType::Short:
2821 case BuiltinType::UShort:
2822 case BuiltinType::Int:
2823 case BuiltinType::UInt:
2824 case BuiltinType::Long:
2825 case BuiltinType::ULong:
2826 case BuiltinType::LongLong:
2827 case BuiltinType::ULongLong:
2828 case BuiltinType::Half:
2829 case BuiltinType::Float:
2830 case BuiltinType::Double:
2831 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002832 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002833 case BuiltinType::Float128:
Richard Smith3a8244d2018-05-01 05:02:45 +00002834 case BuiltinType::Char8:
David Majnemere2cb8d12014-07-07 06:20:47 +00002835 case BuiltinType::Char16:
2836 case BuiltinType::Char32:
2837 case BuiltinType::Int128:
2838 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002839 return true;
2840
Alexey Bader954ba212016-04-08 13:40:33 +00002841#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2842 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002843#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002844#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2845 case BuiltinType::Id:
2846#include "clang/Basic/OpenCLExtensionTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002847 case BuiltinType::OCLSampler:
2848 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002849 case BuiltinType::OCLClkEvent:
2850 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002851 case BuiltinType::OCLReserveID:
Leonard Chanf921d852018-06-04 16:07:52 +00002852 case BuiltinType::ShortAccum:
2853 case BuiltinType::Accum:
2854 case BuiltinType::LongAccum:
2855 case BuiltinType::UShortAccum:
2856 case BuiltinType::UAccum:
2857 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002858 case BuiltinType::ShortFract:
2859 case BuiltinType::Fract:
2860 case BuiltinType::LongFract:
2861 case BuiltinType::UShortFract:
2862 case BuiltinType::UFract:
2863 case BuiltinType::ULongFract:
2864 case BuiltinType::SatShortAccum:
2865 case BuiltinType::SatAccum:
2866 case BuiltinType::SatLongAccum:
2867 case BuiltinType::SatUShortAccum:
2868 case BuiltinType::SatUAccum:
2869 case BuiltinType::SatULongAccum:
2870 case BuiltinType::SatShortFract:
2871 case BuiltinType::SatFract:
2872 case BuiltinType::SatLongFract:
2873 case BuiltinType::SatUShortFract:
2874 case BuiltinType::SatUFract:
2875 case BuiltinType::SatULongFract:
Richard Smith4a382012016-02-03 01:32:42 +00002876 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002877
2878 case BuiltinType::Dependent:
2879#define BUILTIN_TYPE(Id, SingletonId)
2880#define PLACEHOLDER_TYPE(Id, SingletonId) \
2881 case BuiltinType::Id:
2882#include "clang/AST/BuiltinTypes.def"
2883 llvm_unreachable("asking for RRTI for a placeholder type!");
2884
2885 case BuiltinType::ObjCId:
2886 case BuiltinType::ObjCClass:
2887 case BuiltinType::ObjCSel:
2888 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2889 }
2890
2891 llvm_unreachable("Invalid BuiltinType Kind!");
2892}
2893
2894static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2895 QualType PointeeTy = PointerTy->getPointeeType();
2896 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2897 if (!BuiltinTy)
2898 return false;
2899
2900 // Check the qualifiers.
2901 Qualifiers Quals = PointeeTy.getQualifiers();
2902 Quals.removeConst();
2903
2904 if (!Quals.empty())
2905 return false;
2906
2907 return TypeInfoIsInStandardLibrary(BuiltinTy);
2908}
2909
2910/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2911/// information for the given type exists in the standard library.
2912static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2913 // Type info for builtin types is defined in the standard library.
2914 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2915 return TypeInfoIsInStandardLibrary(BuiltinTy);
2916
2917 // Type info for some pointer types to builtin types is defined in the
2918 // standard library.
2919 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2920 return TypeInfoIsInStandardLibrary(PointerTy);
2921
2922 return false;
2923}
2924
2925/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2926/// the given type exists somewhere else, and that we should not emit the type
2927/// information in this translation unit. Assumes that it is not a
2928/// standard-library type.
2929static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2930 QualType Ty) {
2931 ASTContext &Context = CGM.getContext();
2932
2933 // If RTTI is disabled, assume it might be disabled in the
2934 // translation unit that defines any potential key function, too.
2935 if (!Context.getLangOpts().RTTI) return false;
2936
2937 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2938 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2939 if (!RD->hasDefinition())
2940 return false;
2941
2942 if (!RD->isDynamicClass())
2943 return false;
2944
2945 // FIXME: this may need to be reconsidered if the key function
2946 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002947 // N.B. We must always emit the RTTI data ourselves if there exists a key
2948 // function.
2949 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002950
2951 // Don't import the RTTI but emit it locally.
Martin Storsjo228ccd62019-04-26 19:31:51 +00002952 if (CGM.getTriple().isWindowsGNUEnvironment())
Martin Storsjo3b528942018-02-02 06:22:35 +00002953 return false;
2954
David Majnemer1fb1a042014-11-07 07:26:38 +00002955 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002956 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2957 ? false
2958 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002959
David Majnemerbe9022c2015-08-06 20:56:55 +00002960 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002961 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002962 }
2963
2964 return false;
2965}
2966
2967/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2968static bool IsIncompleteClassType(const RecordType *RecordTy) {
2969 return !RecordTy->getDecl()->isCompleteDefinition();
2970}
2971
2972/// ContainsIncompleteClassType - Returns whether the given type contains an
2973/// incomplete class type. This is true if
2974///
2975/// * The given type is an incomplete class type.
2976/// * The given type is a pointer type whose pointee type contains an
2977/// incomplete class type.
2978/// * The given type is a member pointer type whose class is an incomplete
2979/// class type.
2980/// * The given type is a member pointer type whoise pointee type contains an
2981/// incomplete class type.
2982/// is an indirect or direct pointer to an incomplete class type.
2983static bool ContainsIncompleteClassType(QualType Ty) {
2984 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2985 if (IsIncompleteClassType(RecordTy))
2986 return true;
2987 }
2988
2989 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2990 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2991
2992 if (const MemberPointerType *MemberPointerTy =
2993 dyn_cast<MemberPointerType>(Ty)) {
2994 // Check if the class type is incomplete.
2995 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2996 if (IsIncompleteClassType(ClassType))
2997 return true;
2998
2999 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
3000 }
3001
3002 return false;
3003}
3004
3005// CanUseSingleInheritance - Return whether the given record decl has a "single,
3006// public, non-virtual base at offset zero (i.e. the derived class is dynamic
3007// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3008static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
3009 // Check the number of bases.
3010 if (RD->getNumBases() != 1)
3011 return false;
3012
3013 // Get the base.
3014 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
3015
3016 // Check that the base is not virtual.
3017 if (Base->isVirtual())
3018 return false;
3019
3020 // Check that the base is public.
3021 if (Base->getAccessSpecifier() != AS_public)
3022 return false;
3023
3024 // Check that the class is dynamic iff the base is.
3025 const CXXRecordDecl *BaseDecl =
3026 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3027 if (!BaseDecl->isEmpty() &&
3028 BaseDecl->isDynamicClass() != RD->isDynamicClass())
3029 return false;
3030
3031 return true;
3032}
3033
3034void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
3035 // abi::__class_type_info.
3036 static const char * const ClassTypeInfo =
3037 "_ZTVN10__cxxabiv117__class_type_infoE";
3038 // abi::__si_class_type_info.
3039 static const char * const SIClassTypeInfo =
3040 "_ZTVN10__cxxabiv120__si_class_type_infoE";
3041 // abi::__vmi_class_type_info.
3042 static const char * const VMIClassTypeInfo =
3043 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3044
3045 const char *VTableName = nullptr;
3046
3047 switch (Ty->getTypeClass()) {
3048#define TYPE(Class, Base)
3049#define ABSTRACT_TYPE(Class, Base)
3050#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3051#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3052#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3053#include "clang/AST/TypeNodes.def"
3054 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3055
3056 case Type::LValueReference:
3057 case Type::RValueReference:
3058 llvm_unreachable("References shouldn't get here");
3059
3060 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003061 case Type::DeducedTemplateSpecialization:
3062 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003063
Xiuli Pan9c14e282016-01-09 12:53:17 +00003064 case Type::Pipe:
3065 llvm_unreachable("Pipe types shouldn't get here");
3066
David Majnemere2cb8d12014-07-07 06:20:47 +00003067 case Type::Builtin:
3068 // GCC treats vector and complex types as fundamental types.
3069 case Type::Vector:
3070 case Type::ExtVector:
3071 case Type::Complex:
3072 case Type::Atomic:
3073 // FIXME: GCC treats block pointers as fundamental types?!
3074 case Type::BlockPointer:
3075 // abi::__fundamental_type_info.
3076 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
3077 break;
3078
3079 case Type::ConstantArray:
3080 case Type::IncompleteArray:
3081 case Type::VariableArray:
3082 // abi::__array_type_info.
3083 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
3084 break;
3085
3086 case Type::FunctionNoProto:
3087 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003088 // abi::__function_type_info.
3089 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00003090 break;
3091
3092 case Type::Enum:
3093 // abi::__enum_type_info.
3094 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
3095 break;
3096
3097 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00003098 const CXXRecordDecl *RD =
3099 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00003100
3101 if (!RD->hasDefinition() || !RD->getNumBases()) {
3102 VTableName = ClassTypeInfo;
3103 } else if (CanUseSingleInheritance(RD)) {
3104 VTableName = SIClassTypeInfo;
3105 } else {
3106 VTableName = VMIClassTypeInfo;
3107 }
3108
3109 break;
3110 }
3111
3112 case Type::ObjCObject:
3113 // Ignore protocol qualifiers.
3114 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
3115
3116 // Handle id and Class.
3117 if (isa<BuiltinType>(Ty)) {
3118 VTableName = ClassTypeInfo;
3119 break;
3120 }
3121
3122 assert(isa<ObjCInterfaceType>(Ty));
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003123 LLVM_FALLTHROUGH;
David Majnemere2cb8d12014-07-07 06:20:47 +00003124
3125 case Type::ObjCInterface:
3126 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
3127 VTableName = SIClassTypeInfo;
3128 } else {
3129 VTableName = ClassTypeInfo;
3130 }
3131 break;
3132
3133 case Type::ObjCObjectPointer:
3134 case Type::Pointer:
3135 // abi::__pointer_type_info.
3136 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
3137 break;
3138
3139 case Type::MemberPointer:
3140 // abi::__pointer_to_member_type_info.
3141 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
3142 break;
3143 }
3144
3145 llvm::Constant *VTable =
3146 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00003147 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00003148
3149 llvm::Type *PtrDiffTy =
3150 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
3151
3152 // The vtable address point is 2.
3153 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00003154 VTable =
3155 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00003156 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3157
3158 Fields.push_back(VTable);
3159}
3160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003161/// Return the linkage that the type info and type info name constants
David Majnemere2cb8d12014-07-07 06:20:47 +00003162/// should have for the given type.
Richard Smithbbb26552018-05-21 20:10:54 +00003163static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
3164 QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003165 // Itanium C++ ABI 2.9.5p7:
3166 // In addition, it and all of the intermediate abi::__pointer_type_info
3167 // structs in the chain down to the abi::__class_type_info for the
3168 // incomplete class type must be prevented from resolving to the
3169 // corresponding type_info structs for the complete class type, possibly
3170 // by making them local static objects. Finally, a dummy class RTTI is
3171 // generated for the incomplete type that will not resolve to the final
3172 // complete class RTTI (because the latter need not exist), possibly by
3173 // making it a local static object.
3174 if (ContainsIncompleteClassType(Ty))
Richard Smithbbb26552018-05-21 20:10:54 +00003175 return llvm::GlobalValue::InternalLinkage;
3176
3177 switch (Ty->getLinkage()) {
3178 case NoLinkage:
3179 case InternalLinkage:
3180 case UniqueExternalLinkage:
3181 return llvm::GlobalValue::InternalLinkage;
3182
3183 case VisibleNoLinkage:
3184 case ModuleInternalLinkage:
3185 case ModuleLinkage:
3186 case ExternalLinkage:
3187 // RTTI is not enabled, which means that this type info struct is going
3188 // to be used for exception handling. Give it linkonce_odr linkage.
3189 if (!CGM.getLangOpts().RTTI)
3190 return llvm::GlobalValue::LinkOnceODRLinkage;
3191
3192 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3193 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3194 if (RD->hasAttr<WeakAttr>())
3195 return llvm::GlobalValue::WeakODRLinkage;
3196 if (CGM.getTriple().isWindowsItaniumEnvironment())
3197 if (RD->hasAttr<DLLImportAttr>() &&
3198 ShouldUseExternalRTTIDescriptor(CGM, Ty))
3199 return llvm::GlobalValue::ExternalLinkage;
3200 // MinGW always uses LinkOnceODRLinkage for type info.
3201 if (RD->isDynamicClass() &&
3202 !CGM.getContext()
3203 .getTargetInfo()
3204 .getTriple()
3205 .isWindowsGNUEnvironment())
3206 return CGM.getVTableLinkage(RD);
3207 }
3208
3209 return llvm::GlobalValue::LinkOnceODRLinkage;
3210 }
3211
3212 llvm_unreachable("Invalid linkage!");
David Majnemere2cb8d12014-07-07 06:20:47 +00003213}
3214
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003215llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003216 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003217 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003218
3219 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003220 SmallString<256> Name;
3221 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003222 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003223
3224 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3225 if (OldGV && !OldGV->isDeclaration()) {
3226 assert(!OldGV->hasAvailableExternallyLinkage() &&
3227 "available_externally typeinfos not yet implemented");
3228
3229 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3230 }
3231
3232 // Check if there is already an external RTTI descriptor for this type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003233 if (IsStandardLibraryRTTIDescriptor(Ty) ||
3234 ShouldUseExternalRTTIDescriptor(CGM, Ty))
David Majnemere2cb8d12014-07-07 06:20:47 +00003235 return GetAddrOfExternalRTTIDescriptor(Ty);
3236
3237 // Emit the standard library with external linkage.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003238 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
Richard Smithbbb26552018-05-21 20:10:54 +00003239
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003240 // Give the type_info object and name the formal visibility of the
3241 // type itself.
3242 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3243 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3244 // If the linkage is local, only default visibility makes sense.
3245 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3246 else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
3247 ItaniumCXXABI::RUK_NonUniqueHidden)
3248 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3249 else
3250 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3251
3252 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3253 llvm::GlobalValue::DefaultStorageClass;
3254 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3255 auto RD = Ty->getAsCXXRecordDecl();
3256 if (RD && RD->hasAttr<DLLExportAttr>())
3257 DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
3258 }
3259
3260 return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
3261}
3262
3263llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
3264 QualType Ty,
3265 llvm::GlobalVariable::LinkageTypes Linkage,
3266 llvm::GlobalValue::VisibilityTypes Visibility,
3267 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003268 // Add the vtable pointer.
3269 BuildVTablePointer(cast<Type>(Ty));
3270
3271 // And the name.
Richard Smithbbb26552018-05-21 20:10:54 +00003272 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003273 llvm::Constant *TypeNameField;
3274
3275 // If we're supposed to demote the visibility, be sure to set a flag
3276 // to use a string comparison for type_info comparisons.
3277 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
Richard Smithbbb26552018-05-21 20:10:54 +00003278 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003279 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3280 // The flag is the sign bit, which on ARM64 is defined to be clear
3281 // for global pointers. This is very ARM64-specific.
3282 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3283 llvm::Constant *flag =
3284 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3285 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3286 TypeNameField =
3287 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3288 } else {
3289 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3290 }
3291 Fields.push_back(TypeNameField);
3292
3293 switch (Ty->getTypeClass()) {
3294#define TYPE(Class, Base)
3295#define ABSTRACT_TYPE(Class, Base)
3296#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3297#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3298#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3299#include "clang/AST/TypeNodes.def"
3300 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3301
3302 // GCC treats vector types as fundamental types.
3303 case Type::Builtin:
3304 case Type::Vector:
3305 case Type::ExtVector:
3306 case Type::Complex:
3307 case Type::BlockPointer:
3308 // Itanium C++ ABI 2.9.5p4:
3309 // abi::__fundamental_type_info adds no data members to std::type_info.
3310 break;
3311
3312 case Type::LValueReference:
3313 case Type::RValueReference:
3314 llvm_unreachable("References shouldn't get here");
3315
3316 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003317 case Type::DeducedTemplateSpecialization:
3318 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003319
Xiuli Pan9c14e282016-01-09 12:53:17 +00003320 case Type::Pipe:
3321 llvm_unreachable("Pipe type shouldn't get here");
3322
David Majnemere2cb8d12014-07-07 06:20:47 +00003323 case Type::ConstantArray:
3324 case Type::IncompleteArray:
3325 case Type::VariableArray:
3326 // Itanium C++ ABI 2.9.5p5:
3327 // abi::__array_type_info adds no data members to std::type_info.
3328 break;
3329
3330 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003331 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003332 // Itanium C++ ABI 2.9.5p5:
3333 // abi::__function_type_info adds no data members to std::type_info.
3334 break;
3335
3336 case Type::Enum:
3337 // Itanium C++ ABI 2.9.5p5:
3338 // abi::__enum_type_info adds no data members to std::type_info.
3339 break;
3340
3341 case Type::Record: {
3342 const CXXRecordDecl *RD =
3343 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3344 if (!RD->hasDefinition() || !RD->getNumBases()) {
3345 // We don't need to emit any fields.
3346 break;
3347 }
3348
3349 if (CanUseSingleInheritance(RD))
3350 BuildSIClassTypeInfo(RD);
3351 else
3352 BuildVMIClassTypeInfo(RD);
3353
3354 break;
3355 }
3356
3357 case Type::ObjCObject:
3358 case Type::ObjCInterface:
3359 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3360 break;
3361
3362 case Type::ObjCObjectPointer:
3363 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3364 break;
3365
3366 case Type::Pointer:
3367 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3368 break;
3369
3370 case Type::MemberPointer:
3371 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3372 break;
3373
3374 case Type::Atomic:
3375 // No fields, at least for the moment.
3376 break;
3377 }
3378
3379 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3380
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003381 SmallString<256> Name;
3382 llvm::raw_svector_ostream Out(Name);
3383 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003384 llvm::Module &M = CGM.getModule();
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003385 llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003386 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003387 new llvm::GlobalVariable(M, Init->getType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003388 /*isConstant=*/true, Linkage, Init, Name);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003389
David Majnemere2cb8d12014-07-07 06:20:47 +00003390 // If there's already an old global variable, replace it with the new one.
3391 if (OldGV) {
3392 GV->takeName(OldGV);
3393 llvm::Constant *NewPtr =
3394 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3395 OldGV->replaceAllUsesWith(NewPtr);
3396 OldGV->eraseFromParent();
3397 }
3398
Yaron Keren04da2382015-07-29 15:42:28 +00003399 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3400 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3401
David Greenbe0c5b62018-09-12 14:09:06 +00003402 CharUnits Align =
3403 CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
3404 GV->setAlignment(Align.getQuantity());
3405
David Majnemere2cb8d12014-07-07 06:20:47 +00003406 // The Itanium ABI specifies that type_info objects must be globally
3407 // unique, with one exception: if the type is an incomplete class
3408 // type or a (possibly indirect) pointer to one. That exception
3409 // affects the general case of comparing type_info objects produced
3410 // by the typeid operator, which is why the comparison operators on
3411 // std::type_info generally use the type_info name pointers instead
3412 // of the object addresses. However, the language's built-in uses
3413 // of RTTI generally require class types to be complete, even when
3414 // manipulating pointers to those class types. This allows the
3415 // implementation of dynamic_cast to rely on address equality tests,
3416 // which is much faster.
3417
3418 // All of this is to say that it's important that both the type_info
3419 // object and the type_info name be uniqued when weakly emitted.
3420
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003421 TypeName->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003422 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003423
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003424 GV->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003425 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003426
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003427 TypeName->setDLLStorageClass(DLLStorageClass);
3428 GV->setDLLStorageClass(DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00003429
Peter Collingbournee08e68d2019-06-07 19:10:08 +00003430 TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3431 GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3432
David Majnemere2cb8d12014-07-07 06:20:47 +00003433 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3434}
3435
David Majnemere2cb8d12014-07-07 06:20:47 +00003436/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3437/// for the given Objective-C object type.
3438void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3439 // Drop qualifiers.
3440 const Type *T = OT->getBaseType().getTypePtr();
3441 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3442
3443 // The builtin types are abi::__class_type_infos and don't require
3444 // extra fields.
3445 if (isa<BuiltinType>(T)) return;
3446
3447 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3448 ObjCInterfaceDecl *Super = Class->getSuperClass();
3449
3450 // Root classes are also __class_type_info.
3451 if (!Super) return;
3452
3453 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3454
3455 // Everything else is single inheritance.
3456 llvm::Constant *BaseTypeInfo =
3457 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3458 Fields.push_back(BaseTypeInfo);
3459}
3460
3461/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3462/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3463void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3464 // Itanium C++ ABI 2.9.5p6b:
3465 // It adds to abi::__class_type_info a single member pointing to the
3466 // type_info structure for the base type,
3467 llvm::Constant *BaseTypeInfo =
3468 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3469 Fields.push_back(BaseTypeInfo);
3470}
3471
3472namespace {
3473 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3474 /// a class hierarchy.
3475 struct SeenBases {
3476 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3477 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3478 };
3479}
3480
3481/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3482/// abi::__vmi_class_type_info.
3483///
3484static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3485 SeenBases &Bases) {
3486
3487 unsigned Flags = 0;
3488
3489 const CXXRecordDecl *BaseDecl =
3490 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3491
3492 if (Base->isVirtual()) {
3493 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003494 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003495 // If this virtual base has been seen before, then the class is diamond
3496 // shaped.
3497 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3498 } else {
3499 if (Bases.NonVirtualBases.count(BaseDecl))
3500 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3501 }
3502 } else {
3503 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003504 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003505 // If this non-virtual base has been seen before, then the class has non-
3506 // diamond shaped repeated inheritance.
3507 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3508 } else {
3509 if (Bases.VirtualBases.count(BaseDecl))
3510 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3511 }
3512 }
3513
3514 // Walk all bases.
3515 for (const auto &I : BaseDecl->bases())
3516 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3517
3518 return Flags;
3519}
3520
3521static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3522 unsigned Flags = 0;
3523 SeenBases Bases;
3524
3525 // Walk all bases.
3526 for (const auto &I : RD->bases())
3527 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3528
3529 return Flags;
3530}
3531
3532/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3533/// classes with bases that do not satisfy the abi::__si_class_type_info
3534/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3535void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3536 llvm::Type *UnsignedIntLTy =
3537 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3538
3539 // Itanium C++ ABI 2.9.5p6c:
3540 // __flags is a word with flags describing details about the class
3541 // structure, which may be referenced by using the __flags_masks
3542 // enumeration. These flags refer to both direct and indirect bases.
3543 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3544 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3545
3546 // Itanium C++ ABI 2.9.5p6c:
3547 // __base_count is a word with the number of direct proper base class
3548 // descriptions that follow.
3549 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3550
3551 if (!RD->getNumBases())
3552 return;
3553
David Majnemere2cb8d12014-07-07 06:20:47 +00003554 // Now add the base class descriptions.
3555
3556 // Itanium C++ ABI 2.9.5p6c:
3557 // __base_info[] is an array of base class descriptions -- one for every
3558 // direct proper base. Each description is of the type:
3559 //
3560 // struct abi::__base_class_type_info {
3561 // public:
3562 // const __class_type_info *__base_type;
3563 // long __offset_flags;
3564 //
3565 // enum __offset_flags_masks {
3566 // __virtual_mask = 0x1,
3567 // __public_mask = 0x2,
3568 // __offset_shift = 8
3569 // };
3570 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003571
3572 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3573 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3574 // LLP64 platforms.
3575 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3576 // LLP64 platforms.
3577 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3578 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3579 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3580 OffsetFlagsTy = CGM.getContext().LongLongTy;
3581 llvm::Type *OffsetFlagsLTy =
3582 CGM.getTypes().ConvertType(OffsetFlagsTy);
3583
David Majnemere2cb8d12014-07-07 06:20:47 +00003584 for (const auto &Base : RD->bases()) {
3585 // The __base_type member points to the RTTI for the base type.
3586 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3587
3588 const CXXRecordDecl *BaseDecl =
3589 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3590
3591 int64_t OffsetFlags = 0;
3592
3593 // All but the lower 8 bits of __offset_flags are a signed offset.
3594 // For a non-virtual base, this is the offset in the object of the base
3595 // subobject. For a virtual base, this is the offset in the virtual table of
3596 // the virtual base offset for the virtual base referenced (negative).
3597 CharUnits Offset;
3598 if (Base.isVirtual())
3599 Offset =
3600 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3601 else {
3602 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3603 Offset = Layout.getBaseClassOffset(BaseDecl);
3604 };
3605
3606 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3607
3608 // The low-order byte of __offset_flags contains flags, as given by the
3609 // masks from the enumeration __offset_flags_masks.
3610 if (Base.isVirtual())
3611 OffsetFlags |= BCTI_Virtual;
3612 if (Base.getAccessSpecifier() == AS_public)
3613 OffsetFlags |= BCTI_Public;
3614
Reid Klecknerd8b04662016-08-25 22:16:30 +00003615 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003616 }
3617}
3618
Richard Smitha7d93782016-12-01 03:32:42 +00003619/// Compute the flags for a __pbase_type_info, and remove the corresponding
3620/// pieces from \p Type.
3621static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3622 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003623
Richard Smitha7d93782016-12-01 03:32:42 +00003624 if (Type.isConstQualified())
3625 Flags |= ItaniumRTTIBuilder::PTI_Const;
3626 if (Type.isVolatileQualified())
3627 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3628 if (Type.isRestrictQualified())
3629 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3630 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003631
3632 // Itanium C++ ABI 2.9.5p7:
3633 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3634 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003635 if (ContainsIncompleteClassType(Type))
3636 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3637
3638 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003639 if (Proto->isNothrow()) {
Richard Smitha7d93782016-12-01 03:32:42 +00003640 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003641 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003642 }
3643 }
3644
3645 return Flags;
3646}
3647
3648/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3649/// used for pointer types.
3650void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3651 // Itanium C++ ABI 2.9.5p7:
3652 // __flags is a flag word describing the cv-qualification and other
3653 // attributes of the type pointed to
3654 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003655
3656 llvm::Type *UnsignedIntLTy =
3657 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3658 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3659
3660 // Itanium C++ ABI 2.9.5p7:
3661 // __pointee is a pointer to the std::type_info derivation for the
3662 // unqualified type being pointed to.
3663 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003664 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003665 Fields.push_back(PointeeTypeInfo);
3666}
3667
3668/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3669/// struct, used for member pointer types.
3670void
3671ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3672 QualType PointeeTy = Ty->getPointeeType();
3673
David Majnemere2cb8d12014-07-07 06:20:47 +00003674 // Itanium C++ ABI 2.9.5p7:
3675 // __flags is a flag word describing the cv-qualification and other
3676 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003677 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003678
3679 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003680 if (IsIncompleteClassType(ClassType))
3681 Flags |= PTI_ContainingClassIncomplete;
3682
3683 llvm::Type *UnsignedIntLTy =
3684 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3685 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3686
3687 // Itanium C++ ABI 2.9.5p7:
3688 // __pointee is a pointer to the std::type_info derivation for the
3689 // unqualified type being pointed to.
3690 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003691 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003692 Fields.push_back(PointeeTypeInfo);
3693
3694 // Itanium C++ ABI 2.9.5p9:
3695 // __context is a pointer to an abi::__class_type_info corresponding to the
3696 // class type containing the member pointed to
3697 // (e.g., the "A" in "int A::*").
3698 Fields.push_back(
3699 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3700}
3701
David Majnemer443250f2015-03-17 20:35:00 +00003702llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003703 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3704}
3705
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003706void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
Richard Smith4a382012016-02-03 01:32:42 +00003707 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003708 QualType FundamentalTypes[] = {
3709 getContext().VoidTy, getContext().NullPtrTy,
3710 getContext().BoolTy, getContext().WCharTy,
3711 getContext().CharTy, getContext().UnsignedCharTy,
3712 getContext().SignedCharTy, getContext().ShortTy,
3713 getContext().UnsignedShortTy, getContext().IntTy,
3714 getContext().UnsignedIntTy, getContext().LongTy,
3715 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003716 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3717 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003718 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003719 getContext().LongDoubleTy, getContext().Float128Ty,
Richard Smith3a8244d2018-05-01 05:02:45 +00003720 getContext().Char8Ty, getContext().Char16Ty,
3721 getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003722 };
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003723 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3724 RD->hasAttr<DLLExportAttr>()
3725 ? llvm::GlobalValue::DLLExportStorageClass
3726 : llvm::GlobalValue::DefaultStorageClass;
3727 llvm::GlobalValue::VisibilityTypes Visibility =
3728 CodeGenModule::GetLLVMVisibility(RD->getVisibility());
3729 for (const QualType &FundamentalType : FundamentalTypes) {
3730 QualType PointerType = getContext().getPointerType(FundamentalType);
3731 QualType PointerTypeConst = getContext().getPointerType(
3732 FundamentalType.withConst());
3733 for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
3734 ItaniumRTTIBuilder(*this).BuildTypeInfo(
3735 Type, llvm::GlobalValue::ExternalLinkage,
3736 Visibility, DLLStorageClass);
3737 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003738}
3739
3740/// What sort of uniqueness rules should we use for the RTTI for the
3741/// given type?
3742ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3743 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3744 if (shouldRTTIBeUnique())
3745 return RUK_Unique;
3746
3747 // It's only necessary for linkonce_odr or weak_odr linkage.
3748 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3749 Linkage != llvm::GlobalValue::WeakODRLinkage)
3750 return RUK_Unique;
3751
3752 // It's only necessary with default visibility.
3753 if (CanTy->getVisibility() != DefaultVisibility)
3754 return RUK_Unique;
3755
3756 // If we're not required to publish this symbol, hide it.
3757 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3758 return RUK_NonUniqueHidden;
3759
3760 // If we're required to publish this symbol, as we might be under an
3761 // explicit instantiation, leave it with default visibility but
3762 // enable string-comparisons.
3763 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3764 return RUK_NonUniqueVisible;
3765}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003766
Rafael Espindola1e4df922014-09-16 15:18:21 +00003767// Find out how to codegen the complete destructor and constructor
3768namespace {
3769enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3770}
3771static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3772 const CXXMethodDecl *MD) {
3773 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3774 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003775
Rafael Espindola1e4df922014-09-16 15:18:21 +00003776 // The complete and base structors are not equivalent if there are any virtual
3777 // bases, so emit separate functions.
3778 if (MD->getParent()->getNumVBases())
3779 return StructorCodegen::Emit;
3780
3781 GlobalDecl AliasDecl;
3782 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3783 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3784 } else {
3785 const auto *CD = cast<CXXConstructorDecl>(MD);
3786 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3787 }
3788 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3789
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003790 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3791 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003792
Pavel Labathc370f262018-05-14 11:35:44 +00003793 // FIXME: Should we allow available_externally aliases?
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003794 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3795 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003796
Rafael Espindola0806f982014-09-16 20:19:43 +00003797 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003798 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3799 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3800 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003801 return StructorCodegen::COMDAT;
3802 return StructorCodegen::Emit;
3803 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003804
3805 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003806}
3807
Rafael Espindola1e4df922014-09-16 15:18:21 +00003808static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3809 GlobalDecl AliasDecl,
3810 GlobalDecl TargetDecl) {
3811 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3812
3813 StringRef MangledName = CGM.getMangledName(AliasDecl);
3814 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3815 if (Entry && !Entry->isDeclaration())
3816 return;
3817
3818 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003819
3820 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003821 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003822
Peter Collingbourned914fd22018-06-18 20:58:54 +00003823 // Constructors and destructors are always unnamed_addr.
3824 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3825
Rafael Espindola1e4df922014-09-16 15:18:21 +00003826 // Switch any previous uses to the alias.
3827 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003828 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003829 "declaration exists with different type");
3830 Alias->takeName(Entry);
3831 Entry->replaceAllUsesWith(Alias);
3832 Entry->eraseFromParent();
3833 } else {
3834 Alias->setName(MangledName);
3835 }
3836
3837 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003838 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003839}
3840
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003841void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
3842 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003843 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3844 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3845
3846 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3847
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003848 if (CD ? GD.getCtorType() == Ctor_Complete
3849 : GD.getDtorType() == Dtor_Complete) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00003850 GlobalDecl BaseDecl;
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003851 if (CD)
3852 BaseDecl = GD.getWithCtorType(Ctor_Base);
3853 else
3854 BaseDecl = GD.getWithDtorType(Dtor_Base);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003855
3856 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003857 emitConstructorDestructorAlias(CGM, GD, BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003858 return;
3859 }
3860
3861 if (CGType == StructorCodegen::RAUW) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003862 StringRef MangledName = CGM.getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003863 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003864 CGM.addReplacement(MangledName, Aliasee);
3865 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003866 }
3867 }
3868
3869 // The base destructor is equivalent to the base destructor of its
3870 // base class if there is exactly one non-virtual base class with a
3871 // non-trivial destructor, there are no fields with a non-trivial
3872 // destructor, and the body of the destructor is trivial.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003873 if (DD && GD.getDtorType() == Dtor_Base &&
3874 CGType != StructorCodegen::COMDAT &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003875 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003876 return;
3877
Richard Smith5b349582017-10-13 01:55:36 +00003878 // FIXME: The deleting destructor is equivalent to the selected operator
3879 // delete if:
3880 // * either the delete is a destroying operator delete or the destructor
3881 // would be trivial if it weren't virtual,
3882 // * the conversion from the 'this' parameter to the first parameter of the
3883 // destructor is equivalent to a bitcast,
3884 // * the destructor does not have an implicit "this" return, and
3885 // * the operator delete has the same calling convention and IR function type
3886 // as the destructor.
3887 // In such cases we should try to emit the deleting dtor as an alias to the
3888 // selected 'operator delete'.
3889
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003890 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003891
Rafael Espindola1e4df922014-09-16 15:18:21 +00003892 if (CGType == StructorCodegen::COMDAT) {
3893 SmallString<256> Buffer;
3894 llvm::raw_svector_ostream Out(Buffer);
3895 if (DD)
3896 getMangleContext().mangleCXXDtorComdat(DD, Out);
3897 else
3898 getMangleContext().mangleCXXCtorComdat(CD, Out);
3899 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3900 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003901 } else {
3902 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003903 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003904}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003905
James Y Knight9871db02019-02-05 16:42:33 +00003906static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003907 // void *__cxa_begin_catch(void*);
3908 llvm::FunctionType *FTy = llvm::FunctionType::get(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003909 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003910
3911 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3912}
3913
James Y Knight9871db02019-02-05 16:42:33 +00003914static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003915 // void __cxa_end_catch();
3916 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003917 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003918
3919 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3920}
3921
James Y Knight9871db02019-02-05 16:42:33 +00003922static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003923 // void *__cxa_get_exception_ptr(void*);
3924 llvm::FunctionType *FTy = llvm::FunctionType::get(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003925 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003926
3927 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3928}
3929
3930namespace {
3931 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3932 /// exception type lets us state definitively that the thrown exception
3933 /// type does not have a destructor. In particular:
3934 /// - Catch-alls tell us nothing, so we have to conservatively
3935 /// assume that the thrown exception might have a destructor.
3936 /// - Catches by reference behave according to their base types.
3937 /// - Catches of non-record types will only trigger for exceptions
3938 /// of non-record types, which never have destructors.
3939 /// - Catches of record types can trigger for arbitrary subclasses
3940 /// of the caught type, so we have to assume the actual thrown
3941 /// exception type might have a throwing destructor, even if the
3942 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003943 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003944 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3945 bool MightThrow;
3946
3947 void Emit(CodeGenFunction &CGF, Flags flags) override {
3948 if (!MightThrow) {
3949 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3950 return;
3951 }
3952
3953 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3954 }
3955 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003956}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003957
3958/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3959/// __cxa_end_catch.
3960///
3961/// \param EndMightThrow - true if __cxa_end_catch might throw
3962static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3963 llvm::Value *Exn,
3964 bool EndMightThrow) {
3965 llvm::CallInst *call =
3966 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3967
3968 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3969
3970 return call;
3971}
3972
3973/// A "special initializer" callback for initializing a catch
3974/// parameter during catch initialization.
3975static void InitCatchParam(CodeGenFunction &CGF,
3976 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003977 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003978 SourceLocation Loc) {
3979 // Load the exception from where the landing pad saved it.
3980 llvm::Value *Exn = CGF.getExceptionFromSlot();
3981
3982 CanQualType CatchType =
3983 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3984 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3985
3986 // If we're catching by reference, we can just cast the object
3987 // pointer to the appropriate pointer.
3988 if (isa<ReferenceType>(CatchType)) {
3989 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3990 bool EndCatchMightThrow = CaughtType->isRecordType();
3991
3992 // __cxa_begin_catch returns the adjusted object pointer.
3993 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3994
3995 // We have no way to tell the personality function that we're
3996 // catching by reference, so if we're catching a pointer,
3997 // __cxa_begin_catch will actually return that pointer by value.
3998 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3999 QualType PointeeType = PT->getPointeeType();
4000
4001 // When catching by reference, generally we should just ignore
4002 // this by-value pointer and use the exception object instead.
4003 if (!PointeeType->isRecordType()) {
4004
4005 // Exn points to the struct _Unwind_Exception header, which
4006 // we have to skip past in order to reach the exception data.
4007 unsigned HeaderSize =
4008 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
4009 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
4010
4011 // However, if we're catching a pointer-to-record type that won't
4012 // work, because the personality function might have adjusted
4013 // the pointer. There's actually no way for us to fully satisfy
4014 // the language/ABI contract here: we can't use Exn because it
4015 // might have the wrong adjustment, but we can't use the by-value
4016 // pointer because it's off by a level of abstraction.
4017 //
4018 // The current solution is to dump the adjusted pointer into an
4019 // alloca, which breaks language semantics (because changing the
4020 // pointer doesn't change the exception) but at least works.
4021 // The better solution would be to filter out non-exact matches
4022 // and rethrow them, but this is tricky because the rethrow
4023 // really needs to be catchable by other sites at this landing
4024 // pad. The best solution is to fix the personality function.
4025 } else {
4026 // Pull the pointer for the reference type off.
4027 llvm::Type *PtrTy =
4028 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
4029
4030 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00004031 Address ExnPtrTmp =
4032 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004033 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4034 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
4035
4036 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00004037 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004038 }
4039 }
4040
4041 llvm::Value *ExnCast =
4042 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
4043 CGF.Builder.CreateStore(ExnCast, ParamAddr);
4044 return;
4045 }
4046
4047 // Scalars and complexes.
4048 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
4049 if (TEK != TEK_Aggregate) {
4050 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
4051
4052 // If the catch type is a pointer type, __cxa_begin_catch returns
4053 // the pointer by value.
4054 if (CatchType->hasPointerRepresentation()) {
4055 llvm::Value *CastExn =
4056 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
4057
4058 switch (CatchType.getQualifiers().getObjCLifetime()) {
4059 case Qualifiers::OCL_Strong:
4060 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004061 LLVM_FALLTHROUGH;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004062
4063 case Qualifiers::OCL_None:
4064 case Qualifiers::OCL_ExplicitNone:
4065 case Qualifiers::OCL_Autoreleasing:
4066 CGF.Builder.CreateStore(CastExn, ParamAddr);
4067 return;
4068
4069 case Qualifiers::OCL_Weak:
4070 CGF.EmitARCInitWeak(ParamAddr, CastExn);
4071 return;
4072 }
4073 llvm_unreachable("bad ownership qualifier!");
4074 }
4075
4076 // Otherwise, it returns a pointer into the exception object.
4077
4078 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4079 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4080
4081 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00004082 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004083 switch (TEK) {
4084 case TEK_Complex:
4085 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
4086 /*init*/ true);
4087 return;
4088 case TEK_Scalar: {
4089 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
4090 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
4091 return;
4092 }
4093 case TEK_Aggregate:
4094 llvm_unreachable("evaluation kind filtered out!");
4095 }
4096 llvm_unreachable("bad evaluation kind");
4097 }
4098
4099 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00004100 auto catchRD = CatchType->getAsCXXRecordDecl();
4101 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004102
4103 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4104
4105 // Check for a copy expression. If we don't have a copy expression,
4106 // that means a trivial copy is okay.
4107 const Expr *copyExpr = CatchParam.getInit();
4108 if (!copyExpr) {
4109 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00004110 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4111 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004112 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
4113 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
Richard Smithe78fac52018-04-05 20:52:58 +00004114 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004115 return;
4116 }
4117
4118 // We have to call __cxa_get_exception_ptr to get the adjusted
4119 // pointer before copying.
4120 llvm::CallInst *rawAdjustedExn =
4121 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
4122
4123 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00004124 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4125 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004126
4127 // The copy expression is defined in terms of an OpaqueValueExpr.
4128 // Find it and map it to the adjusted expression.
4129 CodeGenFunction::OpaqueValueMapping
4130 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
4131 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
4132
4133 // Call the copy ctor in a terminate scope.
4134 CGF.EHStack.pushTerminate();
4135
4136 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004137 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00004138 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004139 AggValueSlot::IsNotDestructed,
4140 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00004141 AggValueSlot::IsNotAliased,
4142 AggValueSlot::DoesNotOverlap));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004143
4144 // Leave the terminate scope.
4145 CGF.EHStack.popTerminate();
4146
4147 // Undo the opaque value mapping.
4148 opaque.pop();
4149
4150 // Finally we can call __cxa_begin_catch.
4151 CallBeginCatch(CGF, Exn, true);
4152}
4153
4154/// Begins a catch statement by initializing the catch variable and
4155/// calling __cxa_begin_catch.
4156void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4157 const CXXCatchStmt *S) {
4158 // We have to be very careful with the ordering of cleanups here:
4159 // C++ [except.throw]p4:
4160 // The destruction [of the exception temporary] occurs
4161 // immediately after the destruction of the object declared in
4162 // the exception-declaration in the handler.
4163 //
4164 // So the precise ordering is:
4165 // 1. Construct catch variable.
4166 // 2. __cxa_begin_catch
4167 // 3. Enter __cxa_end_catch cleanup
4168 // 4. Enter dtor cleanup
4169 //
4170 // We do this by using a slightly abnormal initialization process.
4171 // Delegation sequence:
4172 // - ExitCXXTryStmt opens a RunCleanupsScope
4173 // - EmitAutoVarAlloca creates the variable and debug info
4174 // - InitCatchParam initializes the variable from the exception
4175 // - CallBeginCatch calls __cxa_begin_catch
4176 // - CallBeginCatch enters the __cxa_end_catch cleanup
4177 // - EmitAutoVarCleanups enters the variable destructor cleanup
4178 // - EmitCXXTryStmt emits the code for the catch body
4179 // - EmitCXXTryStmt close the RunCleanupsScope
4180
4181 VarDecl *CatchParam = S->getExceptionDecl();
4182 if (!CatchParam) {
4183 llvm::Value *Exn = CGF.getExceptionFromSlot();
4184 CallBeginCatch(CGF, Exn, true);
4185 return;
4186 }
4187
4188 // Emit the local.
4189 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004190 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004191 CGF.EmitAutoVarCleanups(var);
4192}
4193
4194/// Get or define the following function:
4195/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
4196/// This code is used only in C++.
James Y Knight9871db02019-02-05 16:42:33 +00004197static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004198 llvm::FunctionType *fnTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004199 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
James Y Knight9871db02019-02-05 16:42:33 +00004200 llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004201 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00004202 llvm::Function *fn =
4203 cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
4204 if (fn->empty()) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004205 fn->setDoesNotThrow();
4206 fn->setDoesNotReturn();
4207
4208 // What we really want is to massively penalize inlining without
4209 // forbidding it completely. The difference between that and
4210 // 'noinline' is negligible.
4211 fn->addFnAttr(llvm::Attribute::NoInline);
4212
4213 // Allow this function to be shared across translation units, but
4214 // we don't want it to turn into an exported symbol.
4215 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4216 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004217 if (CGM.supportsCOMDAT())
4218 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004219
4220 // Set up the function.
4221 llvm::BasicBlock *entry =
James Y Knight9871db02019-02-05 16:42:33 +00004222 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004223 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004224
4225 // Pull the exception pointer out of the parameter list.
4226 llvm::Value *exn = &*fn->arg_begin();
4227
4228 // Call __cxa_begin_catch(exn).
4229 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4230 catchCall->setDoesNotThrow();
4231 catchCall->setCallingConv(CGM.getRuntimeCC());
4232
4233 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004234 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004235 termCall->setDoesNotThrow();
4236 termCall->setDoesNotReturn();
4237 termCall->setCallingConv(CGM.getRuntimeCC());
4238
4239 // std::terminate cannot return.
4240 builder.CreateUnreachable();
4241 }
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004242 return fnRef;
4243}
4244
4245llvm::CallInst *
4246ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4247 llvm::Value *Exn) {
4248 // In C++, we want to call __cxa_begin_catch() before terminating.
4249 if (Exn) {
4250 assert(CGF.CGM.getLangOpts().CPlusPlus);
4251 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4252 }
4253 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4254}
Peter Collingbourne60108802017-12-13 21:53:04 +00004255
4256std::pair<llvm::Value *, const CXXRecordDecl *>
4257ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4258 const CXXRecordDecl *RD) {
4259 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4260}
Heejin Ahnc6479192018-05-31 22:18:13 +00004261
4262void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4263 const CXXCatchStmt *C) {
Heejin Ahn1eb074d2018-06-01 01:01:37 +00004264 if (CGF.getTarget().hasFeature("exception-handling"))
4265 CGF.EHStack.pushCleanup<CatchRetScope>(
4266 NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
Heejin Ahnc6479192018-05-31 22:18:13 +00004267 ItaniumCXXABI::emitBeginCatch(CGF, C);
4268}