blob: d6e51c60cc7f87820b10e5ae1f63ab35b39ad451 [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
Richard Smith00223822019-09-12 20:00:24 +000046 /// All the thread wrapper functions that have been used.
47 llvm::SmallVector<std::pair<const VarDecl *, llvm::Function *>, 8>
48 ThreadWrappers;
49
John McCall475999d2010-08-22 00:05:51 +000050protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000051 bool UseARMMethodPtrABI;
52 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000053 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000054
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000055 ItaniumMangleContext &getMangleContext() {
56 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
57 }
58
Charles Davis4e786dd2010-05-25 19:52:27 +000059public:
Mark Seabornedf0d382013-07-24 16:25:13 +000060 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
61 bool UseARMMethodPtrABI = false,
62 bool UseARMGuardVarABI = false) :
63 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000064 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000065 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000066
Reid Kleckner40ca9132014-05-13 22:05:45 +000067 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000068
Craig Topper4f12f102014-03-12 06:41:41 +000069 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Richard Smith96cd6712017-08-16 01:49:53 +000070 // If C++ prohibits us from making a copy, pass by address.
Reid Kleckneradb41982019-04-30 22:23:20 +000071 if (!RD->canPassInRegisters())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000072 return RAA_Indirect;
73 return RAA_Default;
74 }
75
John McCall7f416cc2015-09-08 08:05:57 +000076 bool isThisCompleteObject(GlobalDecl GD) const override {
77 // The Itanium ABI has separate complete-object vs. base-object
78 // variants of both constructors and destructors.
79 if (isa<CXXDestructorDecl>(GD.getDecl())) {
80 switch (GD.getDtorType()) {
81 case Dtor_Complete:
82 case Dtor_Deleting:
83 return true;
84
85 case Dtor_Base:
86 return false;
87
88 case Dtor_Comdat:
89 llvm_unreachable("emitting dtor comdat as function?");
90 }
91 llvm_unreachable("bad dtor kind");
92 }
93 if (isa<CXXConstructorDecl>(GD.getDecl())) {
94 switch (GD.getCtorType()) {
95 case Ctor_Complete:
96 return true;
97
98 case Ctor_Base:
99 return false;
100
101 case Ctor_CopyingClosure:
102 case Ctor_DefaultClosure:
103 llvm_unreachable("closure ctors in Itanium ABI?");
104
105 case Ctor_Comdat:
106 llvm_unreachable("emitting ctor comdat as function?");
107 }
108 llvm_unreachable("bad dtor kind");
109 }
110
111 // No other kinds.
112 return false;
113 }
114
Craig Topper4f12f102014-03-12 06:41:41 +0000115 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000116
Craig Topper4f12f102014-03-12 06:41:41 +0000117 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000118
John McCallb92ab1a2016-10-26 23:46:34 +0000119 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000120 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
121 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000122 Address This,
123 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000124 llvm::Value *MemFnPtr,
125 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000126
Craig Topper4f12f102014-03-12 06:41:41 +0000127 llvm::Value *
128 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000129 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000130 llvm::Value *MemPtr,
131 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000132
John McCall7a9aac22010-08-23 01:21:21 +0000133 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
134 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000135 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000136 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000137 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000138
Craig Topper4f12f102014-03-12 06:41:41 +0000139 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000140
David Majnemere2be95b2015-06-23 07:31:01 +0000141 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000142 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000143 CharUnits offset) override;
144 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000145 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
146 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000147
John McCall7a9aac22010-08-23 01:21:21 +0000148 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000149 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000150 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000151 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000152
John McCall7a9aac22010-08-23 01:21:21 +0000153 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000154 llvm::Value *Addr,
155 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000156
David Majnemer08681372014-11-01 07:37:17 +0000157 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000158 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000159 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000160
David Majnemer442d0a22014-11-25 07:20:20 +0000161 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000162 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000163
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000164 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
165
166 llvm::CallInst *
167 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
168 llvm::Value *Exn) override;
169
Thomas Andersonb6d87cf2018-07-24 00:43:47 +0000170 void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
David Majnemer443250f2015-03-17 20:35:00 +0000171 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000172 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000173 getAddrOfCXXCatchHandlerType(QualType Ty,
174 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000175 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000176 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000177
David Majnemer1162d252014-06-22 19:05:33 +0000178 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
179 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
180 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000181 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000182 llvm::Type *StdTypeInfoPtrTy) override;
183
184 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
185 QualType SrcRecordTy) override;
186
John McCall7f416cc2015-09-08 08:05:57 +0000187 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000188 QualType SrcRecordTy, QualType DestTy,
189 QualType DestRecordTy,
190 llvm::BasicBlock *CastEnd) override;
191
John McCall7f416cc2015-09-08 08:05:57 +0000192 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000193 QualType SrcRecordTy,
194 QualType DestTy) override;
195
196 bool EmitBadCastCall(CodeGenFunction &CGF) override;
197
Craig Topper4f12f102014-03-12 06:41:41 +0000198 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000199 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000200 const CXXRecordDecl *ClassDecl,
201 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000202
Craig Topper4f12f102014-03-12 06:41:41 +0000203 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000204
George Burgess IVf203dbf2017-02-22 20:28:02 +0000205 AddedStructorArgs
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000206 buildStructorSignature(GlobalDecl GD,
George Burgess IVf203dbf2017-02-22 20:28:02 +0000207 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000208
Reid Klecknere7de47e2013-07-22 13:51:44 +0000209 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000210 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000211 // Itanium does not emit any destructor variant as an inline thunk.
212 // Delegating may occur as an optimization, but all variants are either
213 // emitted with external linkage or as linkonce if they are inline and used.
214 return false;
215 }
216
Craig Topper4f12f102014-03-12 06:41:41 +0000217 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000218
Reid Kleckner89077a12013-12-17 19:46:40 +0000219 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000220 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000221
Craig Topper4f12f102014-03-12 06:41:41 +0000222 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000223
George Burgess IVf203dbf2017-02-22 20:28:02 +0000224 AddedStructorArgs
225 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
226 CXXCtorType Type, bool ForVirtualBase,
227 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000228
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000229 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
230 CXXDtorType Type, bool ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +0000231 bool Delegating, Address This,
232 QualType ThisTy) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000233
Craig Topper4f12f102014-03-12 06:41:41 +0000234 void emitVTableDefinitions(CodeGenVTables &CGVT,
235 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000236
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000237 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
238 CodeGenFunction::VPtr Vptr) override;
239
240 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
241 return true;
242 }
243
244 llvm::Constant *
245 getVTableAddressPoint(BaseSubobject Base,
246 const CXXRecordDecl *VTableClass) override;
247
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000248 llvm::Value *getVTableAddressPointInStructor(
249 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000250 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
251
252 llvm::Value *getVTableAddressPointInStructorWithVTT(
253 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
254 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000255
256 llvm::Constant *
257 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000258 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000259
260 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000261 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000262
John McCall9831b842018-02-06 18:52:44 +0000263 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
264 Address This, llvm::Type *Ty,
265 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000266
David Majnemer0c0b6d92014-10-31 20:09:12 +0000267 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
268 const CXXDestructorDecl *Dtor,
Marco Antognini88559632019-07-22 09:39:13 +0000269 CXXDtorType DtorType, Address This,
270 DeleteOrMemberCallExpr E) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000271
Craig Topper4f12f102014-03-12 06:41:41 +0000272 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000273
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000274 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Richard Smithc195c252018-11-27 19:33:49 +0000275 bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000276
Hans Wennborgc94391d2014-06-06 20:04:01 +0000277 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
278 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000279 // Allow inlining of thunks by emitting them with available_externally
280 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000281 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000282 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Rafael Espindolab7350042018-03-01 00:35:47 +0000283 CGM.setGVProperties(Thunk, GD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000284 }
285
Rafael Espindolab7350042018-03-01 00:35:47 +0000286 bool exportThunk() override { return true; }
287
John McCall7f416cc2015-09-08 08:05:57 +0000288 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000289 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000290
John McCall7f416cc2015-09-08 08:05:57 +0000291 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000292 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000293
David Majnemer196ac332014-09-11 23:05:02 +0000294 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
295 FunctionArgList &Args) const override {
296 assert(!Args.empty() && "expected the arglist to not be empty!");
297 return Args.size() - 1;
298 }
299
Craig Topper4f12f102014-03-12 06:41:41 +0000300 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
301 StringRef GetDeletedVirtualCallName() override
302 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000303
Craig Topper4f12f102014-03-12 06:41:41 +0000304 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000305 Address InitializeArrayCookie(CodeGenFunction &CGF,
306 Address NewPtr,
307 llvm::Value *NumElements,
308 const CXXNewExpr *expr,
309 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000310 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000311 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000312 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000313
John McCallcdf7ef52010-11-06 09:44:32 +0000314 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000315 llvm::GlobalVariable *DeclPtr,
316 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000317 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
James Y Knightf7321542019-02-07 01:14:17 +0000318 llvm::FunctionCallee dtor,
319 llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000320
321 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000322 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000323 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000324 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000325 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000326 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000327 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000328
Richard Smith00223822019-09-12 20:00:24 +0000329 /// Determine whether we will definitely emit this variable with a constant
330 /// initializer, either because the language semantics demand it or because
331 /// we know that the initializer is a constant.
332 bool isEmittedWithConstantInitializer(const VarDecl *VD) const {
333 VD = VD->getMostRecentDecl();
334 if (VD->hasAttr<ConstInitAttr>())
335 return true;
336
337 // All later checks examine the initializer specified on the variable. If
338 // the variable is weak, such examination would not be correct.
339 if (VD->isWeak() || VD->hasAttr<SelectAnyAttr>())
340 return false;
341
342 const VarDecl *InitDecl = VD->getInitializingDeclaration();
343 if (!InitDecl)
344 return false;
345
346 // If there's no initializer to run, this is constant initialization.
347 if (!InitDecl->hasInit())
348 return true;
349
350 // If we have the only definition, we don't need a thread wrapper if we
351 // will emit the value as a constant.
352 if (isUniqueGVALinkage(getContext().GetGVALinkageForVariable(VD)))
Richard Smith2b4fa532019-09-29 05:08:46 +0000353 return !VD->needsDestruction(getContext()) && InitDecl->evaluateValue();
Richard Smith00223822019-09-12 20:00:24 +0000354
355 // Otherwise, we need a thread wrapper unless we know that every
356 // translation unit will emit the value as a constant. We rely on
357 // ICE-ness not varying between translation units, which isn't actually
358 // guaranteed by the standard but is necessary for sanity.
359 return InitDecl->isInitKnownICE() && InitDecl->isInitICE();
360 }
361
362 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
Richard Smith8ac5c742019-10-01 01:23:23 +0000363 return !isEmittedWithConstantInitializer(VD) ||
364 VD->needsDestruction(getContext());
Richard Smith00223822019-09-12 20:00:24 +0000365 }
Richard Smith0f383742014-03-26 22:48:22 +0000366 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
367 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000368
Craig Topper4f12f102014-03-12 06:41:41 +0000369 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000370
371 /**************************** RTTI Uniqueness ******************************/
372
373protected:
374 /// Returns true if the ABI requires RTTI type_info objects to be unique
375 /// across a program.
376 virtual bool shouldRTTIBeUnique() const { return true; }
377
378public:
379 /// What sort of unique-RTTI behavior should we use?
380 enum RTTIUniquenessKind {
381 /// We are guaranteeing, or need to guarantee, that the RTTI string
382 /// is unique.
383 RUK_Unique,
384
385 /// We are not guaranteeing uniqueness for the RTTI string, so we
386 /// can demote to hidden visibility but must use string comparisons.
387 RUK_NonUniqueHidden,
388
389 /// We are not guaranteeing uniqueness for the RTTI string, so we
390 /// have to use string comparisons, but we also have to emit it with
391 /// non-hidden visibility.
392 RUK_NonUniqueVisible
393 };
394
395 /// Return the required visibility status for the given type and linkage in
396 /// the current ABI.
397 RTTIUniquenessKind
398 classifyRTTIUniqueness(QualType CanTy,
399 llvm::GlobalValue::LinkageTypes Linkage) const;
400 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000401
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000402 void emitCXXStructor(GlobalDecl GD) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000403
Peter Collingbourne60108802017-12-13 21:53:04 +0000404 std::pair<llvm::Value *, const CXXRecordDecl *>
405 LoadVTablePtr(CodeGenFunction &CGF, Address This,
406 const CXXRecordDecl *RD) override;
407
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000408 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000409 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
410 const auto &VtableLayout =
411 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000412
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000413 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
414 // Skip empty slot.
415 if (!VtableComponent.isUsedFunctionPointerKind())
416 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000417
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000418 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
419 if (!Method->getCanonicalDecl()->isInlined())
420 continue;
421
422 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
423 auto *Entry = CGM.GetGlobalValue(Name);
424 // This checks if virtual inline function has already been emitted.
425 // Note that it is possible that this inline function would be emitted
426 // after trying to emit vtable speculatively. Because of this we do
427 // an extra pass after emitting all deferred vtables to find and emit
428 // these vtables opportunistically.
429 if (!Entry || Entry->isDeclaration())
430 return true;
431 }
432 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000433 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000434
435 bool isVTableHidden(const CXXRecordDecl *RD) const {
436 const auto &VtableLayout =
437 CGM.getItaniumVTableContext().getVTableLayout(RD);
438
439 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
440 if (VtableComponent.isRTTIKind()) {
441 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
442 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
443 return true;
444 } else if (VtableComponent.isUsedFunctionPointerKind()) {
445 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
446 if (Method->getVisibility() == Visibility::HiddenVisibility &&
447 !Method->isDefined())
448 return true;
449 }
450 }
451 return false;
452 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000453};
John McCall86353412010-08-21 22:46:04 +0000454
455class ARMCXXABI : public ItaniumCXXABI {
456public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000457 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
Sam Clegga5ee6392019-07-19 00:30:23 +0000458 ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
459 /*UseARMGuardVarABI=*/true) {}
John McCall5d865c322010-08-31 07:33:07 +0000460
Craig Topper4f12f102014-03-12 06:41:41 +0000461 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000462 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
463 isa<CXXDestructorDecl>(GD.getDecl()) &&
464 GD.getDtorType() != Dtor_Deleting));
465 }
John McCall5d865c322010-08-31 07:33:07 +0000466
Craig Topper4f12f102014-03-12 06:41:41 +0000467 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
468 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000469
Craig Topper4f12f102014-03-12 06:41:41 +0000470 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000471 Address InitializeArrayCookie(CodeGenFunction &CGF,
472 Address NewPtr,
473 llvm::Value *NumElements,
474 const CXXNewExpr *expr,
475 QualType ElementType) override;
476 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000477 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000478};
Tim Northovera2ee4332014-03-29 15:09:45 +0000479
480class iOS64CXXABI : public ARMCXXABI {
481public:
John McCalld23b27e2016-09-16 02:40:45 +0000482 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
483 Use32BitVTableOffsetABI = true;
484 }
Tim Northover65f582f2014-03-30 17:32:48 +0000485
486 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000487 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000488};
Dan Gohmanc2853072015-09-03 22:51:53 +0000489
490class WebAssemblyCXXABI final : public ItaniumCXXABI {
491public:
492 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
493 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
494 /*UseARMGuardVarABI=*/true) {}
Heejin Ahnc6479192018-05-31 22:18:13 +0000495 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000496
497private:
498 bool HasThisReturn(GlobalDecl GD) const override {
499 return isa<CXXConstructorDecl>(GD.getDecl()) ||
500 (isa<CXXDestructorDecl>(GD.getDecl()) &&
501 GD.getDtorType() != Dtor_Deleting);
502 }
Derek Schuff8179be42016-05-10 17:44:55 +0000503 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000504};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000505}
Charles Davis4e786dd2010-05-25 19:52:27 +0000506
Charles Davis53c59df2010-08-16 03:33:14 +0000507CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000508 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000509 // For IR-generation purposes, there's no significant difference
510 // between the ARM and iOS ABIs.
511 case TargetCXXABI::GenericARM:
512 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000513 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000514 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000515
Tim Northovera2ee4332014-03-29 15:09:45 +0000516 case TargetCXXABI::iOS64:
517 return new iOS64CXXABI(CGM);
518
Tim Northover9bb857a2013-01-31 12:13:10 +0000519 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
520 // include the other 32-bit ARM oddities: constructor/destructor return values
521 // and array cookies.
522 case TargetCXXABI::GenericAArch64:
Sam Clegga5ee6392019-07-19 00:30:23 +0000523 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
524 /*UseARMGuardVarABI=*/true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000525
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000526 case TargetCXXABI::GenericMIPS:
Sam Clegga5ee6392019-07-19 00:30:23 +0000527 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000528
Dan Gohmanc2853072015-09-03 22:51:53 +0000529 case TargetCXXABI::WebAssembly:
530 return new WebAssemblyCXXABI(CGM);
531
John McCall57625922013-01-25 23:36:14 +0000532 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000533 if (CGM.getContext().getTargetInfo().getTriple().getArch()
534 == llvm::Triple::le32) {
535 // For PNaCl, use ARM-style method pointers so that PNaCl code
536 // does not assume anything about the alignment of function
537 // pointers.
Sam Clegga5ee6392019-07-19 00:30:23 +0000538 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
Mark Seabornedf0d382013-07-24 16:25:13 +0000539 }
John McCall57625922013-01-25 23:36:14 +0000540 return new ItaniumCXXABI(CGM);
541
542 case TargetCXXABI::Microsoft:
543 llvm_unreachable("Microsoft ABI is not Itanium-based");
544 }
545 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000546}
547
Chris Lattnera5f58b02011-07-09 17:41:47 +0000548llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000549ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
550 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000551 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000552 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000553}
554
John McCalld9c6c0b2010-08-22 00:59:17 +0000555/// In the Itanium and ARM ABIs, method pointers have the form:
556/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
557///
558/// In the Itanium ABI:
559/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
560/// - the this-adjustment is (memptr.adj)
561/// - the virtual offset is (memptr.ptr - 1)
562///
563/// In the ARM ABI:
564/// - method pointers are virtual if (memptr.adj & 1) is nonzero
565/// - the this-adjustment is (memptr.adj >> 1)
566/// - the virtual offset is (memptr.ptr)
567/// ARM uses 'adj' for the virtual flag because Thumb functions
568/// may be only single-byte aligned.
569///
570/// If the member is virtual, the adjusted 'this' pointer points
571/// to a vtable pointer from which the virtual offset is applied.
572///
573/// If the member is non-virtual, memptr.ptr is the address of
574/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000575CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000576 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
577 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000578 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000579 CGBuilderTy &Builder = CGF.Builder;
580
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000581 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000582 MPT->getPointeeType()->getAs<FunctionProtoType>();
Simon Pilgrimf2805472019-10-02 20:45:16 +0000583 auto *RD =
584 cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
John McCall475999d2010-08-22 00:05:51 +0000585
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000586 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
587 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000588
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000589 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000590
John McCalld9c6c0b2010-08-22 00:59:17 +0000591 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
592 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
593 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
594
John McCalla1dee5302010-08-22 10:59:02 +0000595 // Extract memptr.adj, which is in the second field.
596 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000597
598 // Compute the true adjustment.
599 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000600 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000601 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000602
603 // Apply the adjustment and cast back to the original struct type
604 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000605 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000606 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
607 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
608 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000609 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000610
John McCall475999d2010-08-22 00:05:51 +0000611 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000612 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000613
John McCall475999d2010-08-22 00:05:51 +0000614 // If the LSB in the function pointer is 1, the function pointer points to
615 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000616 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000617 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000618 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
619 else
620 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
621 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000622 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
623
624 // In the virtual path, the adjustment left 'This' pointing to the
625 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000626 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000627 CGF.EmitBlock(FnVirtual);
628
629 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000630 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000631 CharUnits VTablePtrAlign =
632 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
633 CGF.getPointerAlign());
634 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000635 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000636
637 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000638 // On ARM64, to reserve extra space in virtual member function pointers,
639 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000640 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000641 if (!UseARMMethodPtrABI)
642 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000643 if (Use32BitVTableOffsetABI) {
644 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
645 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
646 }
Peter Collingbournee44acad2018-06-26 02:15:47 +0000647 // Compute the address of the virtual function pointer.
648 llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset);
649
650 // Check the address of the function pointer if CFI on member function
651 // pointers is enabled.
652 llvm::Constant *CheckSourceLocation;
653 llvm::Constant *CheckTypeDesc;
654 bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
655 CGM.HasHiddenLTOVisibility(RD);
656 if (ShouldEmitCFICheck) {
657 CodeGenFunction::SanitizerScope SanScope(&CGF);
658
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000659 CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
Peter Collingbournee44acad2018-06-26 02:15:47 +0000660 CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
661 llvm::Constant *StaticData[] = {
662 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
663 CheckSourceLocation,
664 CheckTypeDesc,
665 };
666
667 llvm::Metadata *MD =
668 CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
669 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
670
671 llvm::Value *TypeTest = Builder.CreateCall(
672 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VFPAddr, TypeId});
673
674 if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
675 CGF.EmitTrapCheck(TypeTest);
676 } else {
677 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
678 CGM.getLLVMContext(),
679 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
680 llvm::Value *ValidVtable = Builder.CreateCall(
681 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
682 CGF.EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIMFCall),
683 SanitizerHandler::CFICheckFail, StaticData,
684 {VTable, ValidVtable});
685 }
686
687 FnVirtual = Builder.GetInsertBlock();
688 }
John McCall475999d2010-08-22 00:05:51 +0000689
690 // Load the virtual function to call.
Peter Collingbournee44acad2018-06-26 02:15:47 +0000691 VFPAddr = Builder.CreateBitCast(VFPAddr, FTy->getPointerTo()->getPointerTo());
692 llvm::Value *VirtualFn = Builder.CreateAlignedLoad(
693 VFPAddr, CGF.getPointerAlign(), "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000694 CGF.EmitBranch(FnEnd);
695
696 // In the non-virtual path, the function pointer is actually a
697 // function pointer.
698 CGF.EmitBlock(FnNonVirtual);
699 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000700 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000701
Peter Collingbournee44acad2018-06-26 02:15:47 +0000702 // Check the function pointer if CFI on member function pointers is enabled.
703 if (ShouldEmitCFICheck) {
704 CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
705 if (RD->hasDefinition()) {
706 CodeGenFunction::SanitizerScope SanScope(&CGF);
707
708 llvm::Constant *StaticData[] = {
709 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
710 CheckSourceLocation,
711 CheckTypeDesc,
712 };
713
714 llvm::Value *Bit = Builder.getFalse();
715 llvm::Value *CastedNonVirtualFn =
716 Builder.CreateBitCast(NonVirtualFn, CGF.Int8PtrTy);
717 for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
718 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
719 getContext().getMemberPointerType(
720 MPT->getPointeeType(),
721 getContext().getRecordType(Base).getTypePtr()));
722 llvm::Value *TypeId =
723 llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
724
725 llvm::Value *TypeTest =
726 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
727 {CastedNonVirtualFn, TypeId});
728 Bit = Builder.CreateOr(Bit, TypeTest);
729 }
730
731 CGF.EmitCheck(std::make_pair(Bit, SanitizerKind::CFIMFCall),
732 SanitizerHandler::CFICheckFail, StaticData,
733 {CastedNonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
734
735 FnNonVirtual = Builder.GetInsertBlock();
736 }
737 }
738
John McCall475999d2010-08-22 00:05:51 +0000739 // We're done.
740 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000741 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
742 CalleePtr->addIncoming(VirtualFn, FnVirtual);
743 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
744
745 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000746 return Callee;
747}
John McCalla8bbb822010-08-22 03:04:22 +0000748
John McCallc134eb52010-08-31 21:07:20 +0000749/// Compute an l-value by applying the given pointer-to-member to a
750/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000751llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000752 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000753 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000754 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000755
756 CGBuilderTy &Builder = CGF.Builder;
757
John McCallc134eb52010-08-31 21:07:20 +0000758 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000759 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000760
761 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000762 llvm::Value *Addr =
763 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000764
765 // Cast the address to the appropriate pointer type, adopting the
766 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000767 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
768 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000769 return Builder.CreateBitCast(Addr, PType);
770}
771
John McCallc62bb392012-02-15 01:22:51 +0000772/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
773/// conversion.
774///
775/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000776///
777/// Obligatory offset/adjustment diagram:
778/// <-- offset --> <-- adjustment -->
779/// |--------------------------|----------------------|--------------------|
780/// ^Derived address point ^Base address point ^Member address point
781///
782/// So when converting a base member pointer to a derived member pointer,
783/// we add the offset to the adjustment because the address point has
784/// decreased; and conversely, when converting a derived MP to a base MP
785/// we subtract the offset from the adjustment because the address point
786/// has increased.
787///
788/// The standard forbids (at compile time) conversion to and from
789/// virtual bases, which is why we don't have to consider them here.
790///
791/// The standard forbids (at run time) casting a derived MP to a base
792/// MP when the derived MP does not point to a member of the base.
793/// This is why -1 is a reasonable choice for null data member
794/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000795llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000796ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
797 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000798 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000799 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000800 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
801 E->getCastKind() == CK_ReinterpretMemberPointer);
802
803 // Under Itanium, reinterprets don't require any additional processing.
804 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
805
806 // Use constant emission if we can.
807 if (isa<llvm::Constant>(src))
808 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
809
810 llvm::Constant *adj = getMemberPointerAdjustment(E);
811 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000812
813 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000814 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000815
John McCallc62bb392012-02-15 01:22:51 +0000816 const MemberPointerType *destTy =
817 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000818
John McCall7a9aac22010-08-23 01:21:21 +0000819 // For member data pointers, this is just a matter of adding the
820 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000821 if (destTy->isMemberDataPointer()) {
822 llvm::Value *dst;
823 if (isDerivedToBase)
824 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000825 else
John McCallc62bb392012-02-15 01:22:51 +0000826 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000827
828 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000829 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
830 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
831 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000832 }
833
John McCalla1dee5302010-08-22 10:59:02 +0000834 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000835 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000836 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
837 offset <<= 1;
838 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000839 }
840
John McCallc62bb392012-02-15 01:22:51 +0000841 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
842 llvm::Value *dstAdj;
843 if (isDerivedToBase)
844 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000845 else
John McCallc62bb392012-02-15 01:22:51 +0000846 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000847
John McCallc62bb392012-02-15 01:22:51 +0000848 return Builder.CreateInsertValue(src, dstAdj, 1);
849}
850
851llvm::Constant *
852ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
853 llvm::Constant *src) {
854 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
855 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
856 E->getCastKind() == CK_ReinterpretMemberPointer);
857
858 // Under Itanium, reinterprets don't require any additional processing.
859 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
860
861 // If the adjustment is trivial, we don't need to do anything.
862 llvm::Constant *adj = getMemberPointerAdjustment(E);
863 if (!adj) return src;
864
865 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
866
867 const MemberPointerType *destTy =
868 E->getType()->castAs<MemberPointerType>();
869
870 // For member data pointers, this is just a matter of adding the
871 // offset if the source is non-null.
872 if (destTy->isMemberDataPointer()) {
873 // null maps to null.
874 if (src->isAllOnesValue()) return src;
875
876 if (isDerivedToBase)
877 return llvm::ConstantExpr::getNSWSub(src, adj);
878 else
879 return llvm::ConstantExpr::getNSWAdd(src, adj);
880 }
881
882 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000883 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000884 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
885 offset <<= 1;
886 adj = llvm::ConstantInt::get(adj->getType(), offset);
887 }
888
889 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
890 llvm::Constant *dstAdj;
891 if (isDerivedToBase)
892 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
893 else
894 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
895
896 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000897}
John McCall84fa5102010-08-22 04:16:24 +0000898
899llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000900ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000901 // Itanium C++ ABI 2.3:
902 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000903 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000904 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000905
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000906 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000907 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000908 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000909}
910
John McCallf3a88602011-02-03 08:15:49 +0000911llvm::Constant *
912ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
913 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000914 // Itanium C++ ABI 2.3:
915 // A pointer to data member is an offset from the base address of
916 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000917 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000918}
919
David Majnemere2be95b2015-06-23 07:31:01 +0000920llvm::Constant *
921ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000922 return BuildMemberPointer(MD, CharUnits::Zero());
923}
924
925llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
926 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000927 assert(MD->isInstance() && "Member function must not be static!");
John McCalla1dee5302010-08-22 10:59:02 +0000928
929 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000930
931 // Get the function pointer (or index if this is a virtual function).
932 llvm::Constant *MemPtr[2];
933 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000934 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000935
Ken Dyckdf016282011-04-09 01:30:02 +0000936 const ASTContext &Context = getContext();
937 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000938 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000939 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000940
Mark Seabornedf0d382013-07-24 16:25:13 +0000941 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000942 // ARM C++ ABI 3.2.1:
943 // This ABI specifies that adj contains twice the this
944 // adjustment, plus 1 if the member function is virtual. The
945 // least significant bit of adj then makes exactly the same
946 // discrimination as the least significant bit of ptr does for
947 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000948 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
949 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000950 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000951 } else {
952 // Itanium C++ ABI 2.3:
953 // For a virtual function, [the pointer field] is 1 plus the
954 // virtual table offset (in bytes) of the function,
955 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000956 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
957 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000958 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000959 }
960 } else {
John McCall2979fe02011-04-12 00:42:48 +0000961 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000962 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000963 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000964 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000965 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000966 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000967 } else {
John McCall2979fe02011-04-12 00:42:48 +0000968 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
969 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000970 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000971 }
John McCall2979fe02011-04-12 00:42:48 +0000972 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000973
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000974 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000975 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
976 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000977 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000978 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000979
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000980 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000981}
982
Richard Smithdafff942012-01-14 04:30:29 +0000983llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
984 QualType MPType) {
985 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
986 const ValueDecl *MPD = MP.getMemberPointerDecl();
987 if (!MPD)
988 return EmitNullMemberPointer(MPT);
989
Reid Kleckner452abac2013-05-09 21:01:17 +0000990 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000991
992 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
993 return BuildMemberPointer(MD, ThisAdjustment);
994
995 CharUnits FieldOffset =
996 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
997 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
998}
999
John McCall131d97d2010-08-22 08:30:07 +00001000/// The comparison algorithm is pretty easy: the member pointers are
1001/// the same if they're either bitwise identical *or* both null.
1002///
1003/// ARM is different here only because null-ness is more complicated.
1004llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +00001005ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1006 llvm::Value *L,
1007 llvm::Value *R,
1008 const MemberPointerType *MPT,
1009 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +00001010 CGBuilderTy &Builder = CGF.Builder;
1011
John McCall131d97d2010-08-22 08:30:07 +00001012 llvm::ICmpInst::Predicate Eq;
1013 llvm::Instruction::BinaryOps And, Or;
1014 if (Inequality) {
1015 Eq = llvm::ICmpInst::ICMP_NE;
1016 And = llvm::Instruction::Or;
1017 Or = llvm::Instruction::And;
1018 } else {
1019 Eq = llvm::ICmpInst::ICMP_EQ;
1020 And = llvm::Instruction::And;
1021 Or = llvm::Instruction::Or;
1022 }
1023
John McCall7a9aac22010-08-23 01:21:21 +00001024 // Member data pointers are easy because there's a unique null
1025 // value, so it just comes down to bitwise equality.
1026 if (MPT->isMemberDataPointer())
1027 return Builder.CreateICmp(Eq, L, R);
1028
1029 // For member function pointers, the tautologies are more complex.
1030 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +00001031 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +00001032 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +00001033 // (L == R) <==> (L.ptr == R.ptr &&
1034 // (L.adj == R.adj ||
1035 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +00001036 // The inequality tautologies have exactly the same structure, except
1037 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001038
John McCall7a9aac22010-08-23 01:21:21 +00001039 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
1040 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
1041
John McCall131d97d2010-08-22 08:30:07 +00001042 // This condition tests whether L.ptr == R.ptr. This must always be
1043 // true for equality to hold.
1044 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
1045
1046 // This condition, together with the assumption that L.ptr == R.ptr,
1047 // tests whether the pointers are both null. ARM imposes an extra
1048 // condition.
1049 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
1050 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
1051
1052 // This condition tests whether L.adj == R.adj. If this isn't
1053 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +00001054 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
1055 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001056 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
1057
1058 // Null member function pointers on ARM clear the low bit of Adj,
1059 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001060 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001061 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
1062
1063 // Compute (l.adj | r.adj) & 1 and test it against zero.
1064 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
1065 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
1066 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
1067 "cmp.or.adj");
1068 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
1069 }
1070
1071 // Tie together all our conditions.
1072 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
1073 Result = Builder.CreateBinOp(And, PtrEq, Result,
1074 Inequality ? "memptr.ne" : "memptr.eq");
1075 return Result;
1076}
1077
1078llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +00001079ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1080 llvm::Value *MemPtr,
1081 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +00001082 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +00001083
1084 /// For member data pointers, this is just a check against -1.
1085 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +00001086 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +00001087 llvm::Value *NegativeOne =
1088 llvm::Constant::getAllOnesValue(MemPtr->getType());
1089 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
1090 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001091
Daniel Dunbar914bc412011-04-19 23:10:47 +00001092 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +00001093 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +00001094
1095 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1096 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1097
Daniel Dunbar914bc412011-04-19 23:10:47 +00001098 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1099 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001100 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001101 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001102 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001103 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001104 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1105 "memptr.isvirtual");
1106 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001107 }
1108
1109 return Result;
1110}
John McCall1c456c82010-08-22 06:43:33 +00001111
Reid Kleckner40ca9132014-05-13 22:05:45 +00001112bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1113 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1114 if (!RD)
1115 return false;
1116
Richard Smith96cd6712017-08-16 01:49:53 +00001117 // If C++ prohibits us from making a copy, return by address.
Reid Kleckneradb41982019-04-30 22:23:20 +00001118 if (!RD->canPassInRegisters()) {
John McCall7f416cc2015-09-08 08:05:57 +00001119 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1120 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001121 return true;
1122 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001123 return false;
1124}
1125
John McCall614dbdc2010-08-22 21:01:12 +00001126/// The Itanium ABI requires non-zero initialization only for data
1127/// member pointers, for which '0' is a valid offset.
1128bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001129 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001130}
John McCall5d865c322010-08-31 07:33:07 +00001131
John McCall82fb8922012-09-25 10:10:39 +00001132/// The Itanium ABI always places an offset to the complete object
1133/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001134void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1135 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001136 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001137 QualType ElementType,
1138 const CXXDestructorDecl *Dtor) {
1139 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001140 if (UseGlobalDelete) {
1141 // Derive the complete-object pointer, which is what we need
1142 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001143
David Majnemer0c0b6d92014-10-31 20:09:12 +00001144 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001145 auto *ClassDecl =
Simon Pilgrimf2805472019-10-02 20:45:16 +00001146 cast<CXXRecordDecl>(ElementType->castAs<RecordType>()->getDecl());
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001147 llvm::Value *VTable =
1148 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001149
David Majnemer0c0b6d92014-10-31 20:09:12 +00001150 // Track back to entry -2 and pull out the offset there.
1151 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1152 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001153 llvm::Value *Offset =
1154 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001155
1156 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001157 llvm::Value *CompletePtr =
1158 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001159 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1160
1161 // If we're supposed to call the global delete, make sure we do so
1162 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001163 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1164 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001165 }
1166
1167 // FIXME: Provide a source location here even though there's no
1168 // CXXMemberCallExpr for dtor call.
1169 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
Marco Antognini88559632019-07-22 09:39:13 +00001170 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001171
1172 if (UseGlobalDelete)
1173 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001174}
1175
David Majnemer442d0a22014-11-25 07:20:20 +00001176void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1177 // void __cxa_rethrow();
1178
1179 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001180 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
David Majnemer442d0a22014-11-25 07:20:20 +00001181
James Y Knight9871db02019-02-05 16:42:33 +00001182 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
David Majnemer442d0a22014-11-25 07:20:20 +00001183
1184 if (isNoReturn)
1185 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1186 else
1187 CGF.EmitRuntimeCallOrInvoke(Fn);
1188}
1189
James Y Knight9871db02019-02-05 16:42:33 +00001190static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
David Majnemer7c237072015-03-05 00:46:22 +00001191 // void *__cxa_allocate_exception(size_t thrown_size);
1192
1193 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001194 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
David Majnemer7c237072015-03-05 00:46:22 +00001195
1196 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1197}
1198
James Y Knight9871db02019-02-05 16:42:33 +00001199static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
David Majnemer7c237072015-03-05 00:46:22 +00001200 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1201 // void (*dest) (void *));
1202
1203 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1204 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001205 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
David Majnemer7c237072015-03-05 00:46:22 +00001206
1207 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1208}
1209
1210void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1211 QualType ThrowType = E->getSubExpr()->getType();
1212 // Now allocate the exception object.
1213 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1214 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1215
James Y Knight9871db02019-02-05 16:42:33 +00001216 llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
David Majnemer7c237072015-03-05 00:46:22 +00001217 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1218 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1219
Akira Hatanakac39a2432019-05-10 02:16:37 +00001220 CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
John McCall7f416cc2015-09-08 08:05:57 +00001221 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001222
1223 // Now throw the exception.
1224 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1225 /*ForEH=*/true);
1226
1227 // The address of the destructor. If the exception type has a
1228 // trivial destructor (or isn't a record), we just pass null.
1229 llvm::Constant *Dtor = nullptr;
1230 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1231 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1232 if (!Record->hasTrivialDestructor()) {
1233 CXXDestructorDecl *DtorD = Record->getDestructor();
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001234 Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
David Majnemer7c237072015-03-05 00:46:22 +00001235 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1236 }
1237 }
1238 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1239
1240 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1241 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1242}
1243
James Y Knight9871db02019-02-05 16:42:33 +00001244static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001245 // void *__dynamic_cast(const void *sub,
1246 // const abi::__class_type_info *src,
1247 // const abi::__class_type_info *dst,
1248 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001249
David Majnemer1162d252014-06-22 19:05:33 +00001250 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001251 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001252 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1253
1254 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1255
1256 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1257
1258 // Mark the function as nounwind readonly.
1259 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1260 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001261 llvm::AttributeList Attrs = llvm::AttributeList::get(
1262 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001263
1264 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1265}
1266
James Y Knight9871db02019-02-05 16:42:33 +00001267static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001268 // void __cxa_bad_cast();
1269 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1270 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1271}
1272
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001273/// Compute the src2dst_offset hint as described in the
David Majnemer1162d252014-06-22 19:05:33 +00001274/// Itanium C++ ABI [2.9.7]
1275static CharUnits computeOffsetHint(ASTContext &Context,
1276 const CXXRecordDecl *Src,
1277 const CXXRecordDecl *Dst) {
1278 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1279 /*DetectVirtual=*/false);
1280
1281 // If Dst is not derived from Src we can skip the whole computation below and
1282 // return that Src is not a public base of Dst. Record all inheritance paths.
1283 if (!Dst->isDerivedFrom(Src, Paths))
1284 return CharUnits::fromQuantity(-2ULL);
1285
1286 unsigned NumPublicPaths = 0;
1287 CharUnits Offset;
1288
1289 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001290 for (const CXXBasePath &Path : Paths) {
1291 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001292 continue;
1293
1294 ++NumPublicPaths;
1295
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001296 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001297 // If the path contains a virtual base class we can't give any hint.
1298 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001299 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001300 return CharUnits::fromQuantity(-1ULL);
1301
1302 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1303 continue;
1304
1305 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001306 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1307 Offset += L.getBaseClassOffset(
1308 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001309 }
1310 }
1311
1312 // -2: Src is not a public base of Dst.
1313 if (NumPublicPaths == 0)
1314 return CharUnits::fromQuantity(-2ULL);
1315
1316 // -3: Src is a multiple public base type but never a virtual base type.
1317 if (NumPublicPaths > 1)
1318 return CharUnits::fromQuantity(-3ULL);
1319
1320 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1321 // Return the offset of Src from the origin of Dst.
1322 return Offset;
1323}
1324
James Y Knight9871db02019-02-05 16:42:33 +00001325static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
David Majnemer1162d252014-06-22 19:05:33 +00001326 // void __cxa_bad_typeid();
1327 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1328
1329 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1330}
1331
1332bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1333 QualType SrcRecordTy) {
1334 return IsDeref;
1335}
1336
1337void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
James Y Knight9871db02019-02-05 16:42:33 +00001338 llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
James Y Knight3933add2019-01-30 02:54:28 +00001339 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1340 Call->setDoesNotReturn();
David Majnemer1162d252014-06-22 19:05:33 +00001341 CGF.Builder.CreateUnreachable();
1342}
1343
1344llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1345 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001346 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001347 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001348 auto *ClassDecl =
Simon Pilgrimf2805472019-10-02 20:45:16 +00001349 cast<CXXRecordDecl>(SrcRecordTy->castAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001350 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001351 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001352
1353 // Load the type info.
1354 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001355 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001356}
1357
1358bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1359 QualType SrcRecordTy) {
1360 return SrcIsPtr;
1361}
1362
1363llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001364 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001365 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1366 llvm::Type *PtrDiffLTy =
1367 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1368 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1369
1370 llvm::Value *SrcRTTI =
1371 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1372 llvm::Value *DestRTTI =
1373 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1374
1375 // Compute the offset hint.
1376 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1377 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1378 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1379 PtrDiffLTy,
1380 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1381
1382 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001383 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001384 Value = CGF.EmitCastToVoidPtr(Value);
1385
1386 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1387 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1388 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1389
1390 /// C++ [expr.dynamic.cast]p9:
1391 /// A failed cast to reference type throws std::bad_cast
1392 if (DestTy->isReferenceType()) {
1393 llvm::BasicBlock *BadCastBlock =
1394 CGF.createBasicBlock("dynamic_cast.bad_cast");
1395
1396 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1397 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1398
1399 CGF.EmitBlock(BadCastBlock);
1400 EmitBadCastCall(CGF);
1401 }
1402
1403 return Value;
1404}
1405
1406llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001407 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001408 QualType SrcRecordTy,
1409 QualType DestTy) {
1410 llvm::Type *PtrDiffLTy =
1411 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1412 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1413
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001414 auto *ClassDecl =
Simon Pilgrimf2805472019-10-02 20:45:16 +00001415 cast<CXXRecordDecl>(SrcRecordTy->castAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001416 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001417 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1418 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001419
1420 // Get the offset-to-top from the vtable.
1421 llvm::Value *OffsetToTop =
1422 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001423 OffsetToTop =
1424 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1425 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001426
1427 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001428 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001429 Value = CGF.EmitCastToVoidPtr(Value);
1430 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1431
1432 return CGF.Builder.CreateBitCast(Value, DestLTy);
1433}
1434
1435bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
James Y Knight9871db02019-02-05 16:42:33 +00001436 llvm::FunctionCallee Fn = getBadCastFn(CGF);
James Y Knight3933add2019-01-30 02:54:28 +00001437 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1438 Call->setDoesNotReturn();
David Majnemer1162d252014-06-22 19:05:33 +00001439 CGF.Builder.CreateUnreachable();
1440 return true;
1441}
1442
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001443llvm::Value *
1444ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001445 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001446 const CXXRecordDecl *ClassDecl,
1447 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001448 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001449 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001450 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1451 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001452
1453 llvm::Value *VBaseOffsetPtr =
1454 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1455 "vbase.offset.ptr");
1456 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1457 CGM.PtrDiffTy->getPointerTo());
1458
1459 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001460 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1461 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001462
1463 return VBaseOffset;
1464}
1465
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001466void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1467 // Just make sure we're in sync with TargetCXXABI.
1468 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1469
Rafael Espindolac3cde362013-12-09 14:51:17 +00001470 // The constructor used for constructing this as a base class;
1471 // ignores virtual bases.
1472 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1473
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001474 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001475 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001476 if (!D->getParent()->isAbstract()) {
1477 // We don't need to emit the complete ctor if the class is abstract.
1478 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1479 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001480}
1481
George Burgess IVf203dbf2017-02-22 20:28:02 +00001482CGCXXABI::AddedStructorArgs
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001483ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001484 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001485 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001486
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001487 // All parameters are already in place except VTT, which goes after 'this'.
1488 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001489
1490 // Check if we need to add a VTT parameter (which has type void **).
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001491 if ((isa<CXXConstructorDecl>(GD.getDecl()) ? GD.getCtorType() == Ctor_Base
1492 : GD.getDtorType() == Dtor_Base) &&
1493 cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001494 ArgTys.insert(ArgTys.begin() + 1,
1495 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001496 return AddedStructorArgs::prefix(1);
1497 }
1498 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001499}
1500
Reid Klecknere7de47e2013-07-22 13:51:44 +00001501void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001502 // The destructor used for destructing this as a base class; ignores
1503 // virtual bases.
1504 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001505
1506 // The destructor used for destructing this as a most-derived class;
1507 // call the base destructor and then destructs any virtual bases.
1508 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1509
Rafael Espindolac3cde362013-12-09 14:51:17 +00001510 // The destructor in a virtual table is always a 'deleting'
1511 // destructor, which calls the complete destructor and then uses the
1512 // appropriate operator delete.
1513 if (D->isVirtual())
1514 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001515}
1516
Reid Kleckner89077a12013-12-17 19:46:40 +00001517void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1518 QualType &ResTy,
1519 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001520 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001521 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001522
1523 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001524 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001525 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001526
1527 // FIXME: avoid the fake decl
1528 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001529 auto *VTTDecl = ImplicitParamDecl::Create(
1530 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1531 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001532 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001533 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001534 }
1535}
1536
John McCall5d865c322010-08-31 07:33:07 +00001537void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001538 // Naked functions have no prolog.
1539 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1540 return;
1541
Reid Kleckner06239e42017-11-16 19:09:36 +00001542 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001543 /// adjustments are required, because they are all handled by thunks.
Reid Kleckner06239e42017-11-16 19:09:36 +00001544 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001545
1546 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001547 if (getStructorImplicitParamDecl(CGF)) {
1548 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1549 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001550 }
John McCall5d865c322010-08-31 07:33:07 +00001551
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001552 /// If this is a function that the ABI specifies returns 'this', initialize
1553 /// the return slot to 'this' at the start of the function.
1554 ///
1555 /// Unlike the setting of return types, this is done within the ABI
1556 /// implementation instead of by clients of CGCXXABI because:
1557 /// 1) getThisValue is currently protected
1558 /// 2) in theory, an ABI could implement 'this' returns some other way;
1559 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001560 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001561 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001562}
1563
George Burgess IVf203dbf2017-02-22 20:28:02 +00001564CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001565 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1566 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1567 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001568 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001569
Reid Kleckner89077a12013-12-17 19:46:40 +00001570 // Insert the implicit 'vtt' argument as the second argument.
1571 llvm::Value *VTT =
1572 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1573 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
Yaxun Liu5b330e82018-03-15 15:25:19 +00001574 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001575 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001576}
1577
1578void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1579 const CXXDestructorDecl *DD,
1580 CXXDtorType Type, bool ForVirtualBase,
Marco Antognini88559632019-07-22 09:39:13 +00001581 bool Delegating, Address This,
1582 QualType ThisTy) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001583 GlobalDecl GD(DD, Type);
1584 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1585 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1586
John McCallb92ab1a2016-10-26 23:46:34 +00001587 CGCallee Callee;
1588 if (getContext().getLangOpts().AppleKext &&
1589 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001590 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001591 else
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001592 Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001593
Marco Antognini88559632019-07-22 09:39:13 +00001594 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, VTT, VTTTy,
1595 nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001596}
1597
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001598void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1599 const CXXRecordDecl *RD) {
1600 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1601 if (VTable->hasInitializer())
1602 return;
1603
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001604 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001605 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1606 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001607 llvm::Constant *RTTI =
1608 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001609
1610 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001611 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001612 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001613 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1614 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001615
1616 // Set the correct linkage.
1617 VTable->setLinkage(Linkage);
1618
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001619 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1620 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001621
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001622 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001623 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001624
1625 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1626 // we will emit the typeinfo for the fundamental types. This is the
1627 // same behaviour as GCC.
1628 const DeclContext *DC = RD->getDeclContext();
1629 if (RD->getIdentifier() &&
1630 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1631 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1632 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1633 DC->getParent()->isTranslationUnit())
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00001634 EmitFundamentalRTTIDescriptors(RD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001635
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001636 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001637 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001638}
1639
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001640bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1641 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1642 if (Vptr.NearestVBase == nullptr)
1643 return false;
1644 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001645}
1646
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001647llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1648 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1649 const CXXRecordDecl *NearestVBase) {
1650
1651 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1652 NeedsVTTParameter(CGF.CurGD)) {
1653 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1654 NearestVBase);
1655 }
1656 return getVTableAddressPoint(Base, VTableClass);
1657}
1658
1659llvm::Constant *
1660ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1661 const CXXRecordDecl *VTableClass) {
1662 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001663
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001664 // Find the appropriate vtable within the vtable group, and the address point
1665 // within that vtable.
1666 VTableLayout::AddressPointLocation AddressPoint =
1667 CGM.getItaniumVTableContext()
1668 .getVTableLayout(VTableClass)
1669 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001670 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001671 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001672 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1673 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001674 };
1675
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001676 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1677 Indices, /*InBounds=*/true,
1678 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001679}
1680
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001681llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1682 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1683 const CXXRecordDecl *NearestVBase) {
1684 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1685 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1686
1687 // Get the secondary vpointer index.
1688 uint64_t VirtualPointerIndex =
1689 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1690
1691 /// Load the VTT.
1692 llvm::Value *VTT = CGF.LoadCXXVTT();
1693 if (VirtualPointerIndex)
1694 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1695
1696 // And load the address point from the VTT.
1697 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1698}
1699
1700llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1701 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1702 return getVTableAddressPoint(Base, VTableClass);
1703}
1704
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001705llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1706 CharUnits VPtrOffset) {
1707 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1708
1709 llvm::GlobalVariable *&VTable = VTables[RD];
1710 if (VTable)
1711 return VTable;
1712
Eric Christopherd160c502016-01-29 01:35:53 +00001713 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001714 CGM.addDeferredVTable(RD);
1715
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001716 SmallString<256> Name;
1717 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001718 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001719
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001720 const VTableLayout &VTLayout =
1721 CGM.getItaniumVTableContext().getVTableLayout(RD);
1722 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001723
David Greenbe0c5b62018-09-12 14:09:06 +00001724 // Use pointer alignment for the vtable. Otherwise we would align them based
1725 // on the size of the initializer which doesn't make sense as only single
1726 // values are read.
1727 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1728
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001729 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
David Greenbe0c5b62018-09-12 14:09:06 +00001730 Name, VTableType, llvm::GlobalValue::ExternalLinkage,
1731 getContext().toCharUnitsFromBits(PAlign).getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001732 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001733
Rafael Espindola922f2aa2018-02-23 19:30:48 +00001734 CGM.setGVProperties(VTable, RD);
1735
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001736 return VTable;
1737}
1738
John McCall9831b842018-02-06 18:52:44 +00001739CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1740 GlobalDecl GD,
1741 Address This,
1742 llvm::Type *Ty,
1743 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001744 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001745 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1746 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001747
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001748 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001749 llvm::Value *VFunc;
1750 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1751 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001752 MethodDecl->getParent(), VTable,
1753 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001754 } else {
1755 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001756
John McCall9831b842018-02-06 18:52:44 +00001757 llvm::Value *VFuncPtr =
1758 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1759 auto *VFuncLoad =
1760 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001761
John McCall9831b842018-02-06 18:52:44 +00001762 // Add !invariant.load md to virtual function load to indicate that
1763 // function didn't change inside vtable.
1764 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1765 // help in devirtualization because it will only matter if we will have 2
1766 // the same virtual function loads from the same vtable load, which won't
1767 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1768 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1769 CGM.getCodeGenOpts().StrictVTablePointers)
1770 VFuncLoad->setMetadata(
1771 llvm::LLVMContext::MD_invariant_load,
1772 llvm::MDNode::get(CGM.getLLVMContext(),
1773 llvm::ArrayRef<llvm::Metadata *>()));
1774 VFunc = VFuncLoad;
1775 }
John McCallb92ab1a2016-10-26 23:46:34 +00001776
Erich Keanede6480a32018-11-13 15:48:08 +00001777 CGCallee Callee(GD, VFunc);
John McCall9831b842018-02-06 18:52:44 +00001778 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001779}
1780
David Majnemer0c0b6d92014-10-31 20:09:12 +00001781llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1782 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
Marco Antognini88559632019-07-22 09:39:13 +00001783 Address This, DeleteOrMemberCallExpr E) {
1784 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1785 auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1786 assert((CE != nullptr) ^ (D != nullptr));
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001787 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001788 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1789
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001790 GlobalDecl GD(Dtor, DtorType);
1791 const CGFunctionInfo *FInfo =
1792 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
George Burgess IV00f70bd2018-03-01 05:43:23 +00001793 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Peter Collingbourned1c5b282019-03-22 23:05:10 +00001794 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001795
Marco Antognini88559632019-07-22 09:39:13 +00001796 QualType ThisTy;
1797 if (CE) {
1798 ThisTy = CE->getObjectType();
1799 } else {
1800 ThisTy = D->getDestroyedType();
1801 }
1802
1803 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, nullptr,
1804 QualType(), nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001805 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001806}
1807
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001808void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001809 CodeGenVTables &VTables = CGM.getVTables();
1810 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001811 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001812}
1813
Richard Smithc195c252018-11-27 19:33:49 +00001814bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
1815 const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001816 // We don't emit available_externally vtables if we are in -fapple-kext mode
1817 // because kext mode does not permit devirtualization.
1818 if (CGM.getLangOpts().AppleKext)
1819 return false;
1820
Piotr Padlewskie368de32018-06-13 13:55:42 +00001821 // If the vtable is hidden then it is not safe to emit an available_externally
1822 // copy of vtable.
1823 if (isVTableHidden(RD))
1824 return false;
1825
1826 if (CGM.getCodeGenOpts().ForceEmitVTables)
1827 return true;
1828
1829 // If we don't have any not emitted inline virtual function then we are safe
1830 // to emit an available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001831 // FIXME we can still emit a copy of the vtable if we
1832 // can emit definition of the inline functions.
Richard Smithc195c252018-11-27 19:33:49 +00001833 if (hasAnyUnusedVirtualInlineFunction(RD))
1834 return false;
1835
1836 // For a class with virtual bases, we must also be able to speculatively
1837 // emit the VTT, because CodeGen doesn't have separate notions of "can emit
1838 // the vtable" and "can emit the VTT". For a base subobject, this means we
1839 // need to be able to emit non-virtual base vtables.
1840 if (RD->getNumVBases()) {
1841 for (const auto &B : RD->bases()) {
1842 auto *BRD = B.getType()->getAsCXXRecordDecl();
1843 assert(BRD && "no class for base specifier");
1844 if (B.isVirtual() || !BRD->isDynamicClass())
1845 continue;
1846 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1847 return false;
1848 }
1849 }
1850
1851 return true;
1852}
1853
1854bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
1855 if (!canSpeculativelyEmitVTableAsBaseClass(RD))
1856 return false;
1857
1858 // For a complete-object vtable (or more specifically, for the VTT), we need
1859 // to be able to speculatively emit the vtables of all dynamic virtual bases.
1860 for (const auto &B : RD->vbases()) {
1861 auto *BRD = B.getType()->getAsCXXRecordDecl();
1862 assert(BRD && "no class for base specifier");
1863 if (!BRD->isDynamicClass())
1864 continue;
1865 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
1866 return false;
1867 }
1868
1869 return true;
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001870}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001871static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001872 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001873 int64_t NonVirtualAdjustment,
1874 int64_t VirtualAdjustment,
1875 bool IsReturnAdjustment) {
1876 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001877 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001878
John McCall7f416cc2015-09-08 08:05:57 +00001879 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001880
John McCall7f416cc2015-09-08 08:05:57 +00001881 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001882 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001883 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1884 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001885 }
1886
John McCall7f416cc2015-09-08 08:05:57 +00001887 // Perform the virtual adjustment if we have one.
1888 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001889 if (VirtualAdjustment) {
1890 llvm::Type *PtrDiffTy =
1891 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1892
John McCall7f416cc2015-09-08 08:05:57 +00001893 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001894 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1895
1896 llvm::Value *OffsetPtr =
1897 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1898
1899 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1900
1901 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001902 llvm::Value *Offset =
1903 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001904
1905 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001906 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1907 } else {
1908 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001909 }
1910
John McCall7f416cc2015-09-08 08:05:57 +00001911 // In a derived-to-base conversion, the non-virtual adjustment is
1912 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001913 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001914 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1915 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001916 }
1917
1918 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001919 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001920}
1921
1922llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001923 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001924 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001925 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1926 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001927 /*IsReturnAdjustment=*/false);
1928}
1929
1930llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001931ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001932 const ReturnAdjustment &RA) {
1933 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1934 RA.Virtual.Itanium.VBaseOffsetOffset,
1935 /*IsReturnAdjustment=*/true);
1936}
1937
John McCall5d865c322010-08-31 07:33:07 +00001938void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1939 RValue RV, QualType ResultType) {
1940 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1941 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1942
1943 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001944 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001945 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1946 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1947}
John McCall8ed55a52010-09-02 09:58:18 +00001948
1949/************************** Array allocation cookies **************************/
1950
John McCallb91cd662012-05-01 05:23:51 +00001951CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1952 // The array cookie is a size_t; pad that up to the element alignment.
1953 // The cookie is actually right-justified in that space.
1954 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1955 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001956}
1957
John McCall7f416cc2015-09-08 08:05:57 +00001958Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1959 Address NewPtr,
1960 llvm::Value *NumElements,
1961 const CXXNewExpr *expr,
1962 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001963 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001964
John McCall7f416cc2015-09-08 08:05:57 +00001965 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001966
John McCall9bca9232010-09-02 10:25:57 +00001967 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001968 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001969
1970 // The size of the cookie.
1971 CharUnits CookieSize =
1972 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001973 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001974
1975 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001976 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001977 CharUnits CookieOffset = CookieSize - SizeSize;
1978 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001979 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001980
1981 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001982 Address NumElementsPtr =
1983 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001984 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001985
1986 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001987 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001988 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
Filipe Cabecinhas0eb50082018-11-02 17:29:04 +00001989 CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001990 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001991 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1992 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001993 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
James Y Knight9871db02019-02-05 16:42:33 +00001994 llvm::FunctionCallee F =
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001995 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001996 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001997 }
John McCall8ed55a52010-09-02 09:58:18 +00001998
1999 // Finally, compute a pointer to the actual data buffer by skipping
2000 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00002001 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00002002}
2003
John McCallb91cd662012-05-01 05:23:51 +00002004llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002005 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00002006 CharUnits cookieSize) {
2007 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00002008 Address numElementsPtr = allocPtr;
2009 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00002010 if (!numElementsOffset.isZero())
2011 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00002012 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00002013
John McCall7f416cc2015-09-08 08:05:57 +00002014 unsigned AS = allocPtr.getAddressSpace();
2015 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002016 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00002017 return CGF.Builder.CreateLoad(numElementsPtr);
2018 // In asan mode emit a function call instead of a regular load and let the
2019 // run-time deal with it: if the shadow is properly poisoned return the
2020 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
2021 // We can't simply ignore this load using nosanitize metadata because
2022 // the metadata may be lost.
2023 llvm::FunctionType *FTy =
2024 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
James Y Knight9871db02019-02-05 16:42:33 +00002025 llvm::FunctionCallee F =
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00002026 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00002027 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00002028}
2029
John McCallb91cd662012-05-01 05:23:51 +00002030CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00002031 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00002032 // struct array_cookie {
2033 // std::size_t element_size; // element_size != 0
2034 // std::size_t element_count;
2035 // };
John McCallc19c7062013-01-25 23:36:19 +00002036 // But the base ABI doesn't give anything an alignment greater than
2037 // 8, so we can dismiss this as typical ABI-author blindness to
2038 // actual language complexity and round up to the element alignment.
2039 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
2040 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00002041}
2042
John McCall7f416cc2015-09-08 08:05:57 +00002043Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2044 Address newPtr,
2045 llvm::Value *numElements,
2046 const CXXNewExpr *expr,
2047 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00002048 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00002049
John McCall8ed55a52010-09-02 09:58:18 +00002050 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00002051 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00002052
2053 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00002054 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00002055 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
2056 getContext().getTypeSizeInChars(elementType).getQuantity());
2057 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00002058
2059 // The second element is the element count.
James Y Knight751fe282019-02-09 22:22:28 +00002060 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
John McCallc19c7062013-01-25 23:36:19 +00002061 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00002062
2063 // Finally, compute a pointer to the actual data buffer by skipping
2064 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00002065 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00002066 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00002067}
2068
John McCallb91cd662012-05-01 05:23:51 +00002069llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002070 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00002071 CharUnits cookieSize) {
2072 // The number of elements is at offset sizeof(size_t) relative to
2073 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002074 Address numElementsPtr
2075 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00002076
John McCall7f416cc2015-09-08 08:05:57 +00002077 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00002078 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00002079}
2080
John McCall68ff0372010-09-08 01:44:27 +00002081/*********************** Static local initialization **************************/
2082
James Y Knight9871db02019-02-05 16:42:33 +00002083static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
2084 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002085 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002086 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00002087 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00002088 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002089 return CGM.CreateRuntimeFunction(
2090 FTy, "__cxa_guard_acquire",
2091 llvm::AttributeList::get(CGM.getLLVMContext(),
2092 llvm::AttributeList::FunctionIndex,
2093 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002094}
2095
James Y Knight9871db02019-02-05 16:42:33 +00002096static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
2097 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002098 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002099 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00002100 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002101 return CGM.CreateRuntimeFunction(
2102 FTy, "__cxa_guard_release",
2103 llvm::AttributeList::get(CGM.getLLVMContext(),
2104 llvm::AttributeList::FunctionIndex,
2105 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002106}
2107
James Y Knight9871db02019-02-05 16:42:33 +00002108static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
2109 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00002110 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00002111 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00002112 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00002113 return CGM.CreateRuntimeFunction(
2114 FTy, "__cxa_guard_abort",
2115 llvm::AttributeList::get(CGM.getLLVMContext(),
2116 llvm::AttributeList::FunctionIndex,
2117 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00002118}
2119
2120namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002121 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00002122 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00002123 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00002124
Craig Topper4f12f102014-03-12 06:41:41 +00002125 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00002126 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
2127 Guard);
John McCall68ff0372010-09-08 01:44:27 +00002128 }
2129 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002130}
John McCall68ff0372010-09-08 01:44:27 +00002131
2132/// The ARM code here follows the Itanium code closely enough that we
2133/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00002134void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
2135 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00002136 llvm::GlobalVariable *var,
2137 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00002138 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00002139
Richard Smith62f19e72016-06-25 00:15:56 +00002140 // Inline variables that weren't instantiated from variable templates have
2141 // partially-ordered initialization within their translation unit.
2142 bool NonTemplateInline =
2143 D.isInline() &&
2144 !isTemplateInstantiation(D.getTemplateSpecializationKind());
2145
2146 // We only need to use thread-safe statics for local non-TLS variables and
2147 // inline variables; other global initialization is always single-threaded
2148 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002149 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00002150 (D.isLocalVarDecl() || NonTemplateInline) &&
2151 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002152
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002153 // If we have a global variable with internal linkage and thread-safe statics
2154 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002155 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2156
2157 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002158 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002159 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002160 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002161 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002162 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002163 // Guard variables are 64 bits in the generic ABI and size width on ARM
2164 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002165 if (UseARMGuardVarABI) {
2166 guardTy = CGF.SizeTy;
2167 guardAlignment = CGF.getSizeAlign();
2168 } else {
2169 guardTy = CGF.Int64Ty;
2170 guardAlignment = CharUnits::fromQuantity(
2171 CGM.getDataLayout().getABITypeAlignment(guardTy));
2172 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002173 }
John McCallb88a5662012-03-30 21:00:39 +00002174 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002175
John McCallb88a5662012-03-30 21:00:39 +00002176 // Create the guard variable if we don't already have it (as we
2177 // might if we're double-emitting this function body).
2178 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2179 if (!guard) {
2180 // Mangle the name for the guard.
2181 SmallString<256> guardName;
2182 {
2183 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002184 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002185 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002186
John McCallb88a5662012-03-30 21:00:39 +00002187 // Create the guard variable with a zero-initializer.
2188 // Just absorb linkage and visibility from the guarded variable.
2189 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2190 false, var->getLinkage(),
2191 llvm::ConstantInt::get(guardTy, 0),
2192 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002193 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002194 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002195 // If the variable is thread-local, so is its guard variable.
2196 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002197 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002198
Yaron Keren5bfa1082015-09-03 20:33:29 +00002199 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2200 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002201 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002202 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002203 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002204 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2205 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002206 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002207 // An inline variable's guard function is run from the per-TU
2208 // initialization function, not via a dedicated global ctor function, so
2209 // we can't put it in a comdat.
2210 if (!NonTemplateInline)
2211 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002212 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2213 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002214 }
2215
John McCallb88a5662012-03-30 21:00:39 +00002216 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2217 }
John McCall87590e62012-03-30 07:09:50 +00002218
John McCall7f416cc2015-09-08 08:05:57 +00002219 Address guardAddr = Address(guard, guardAlignment);
2220
John McCall68ff0372010-09-08 01:44:27 +00002221 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002222 //
John McCall68ff0372010-09-08 01:44:27 +00002223 // Itanium C++ ABI 3.3.2:
2224 // The following is pseudo-code showing how these functions can be used:
2225 // if (obj_guard.first_byte == 0) {
2226 // if ( __cxa_guard_acquire (&obj_guard) ) {
2227 // try {
2228 // ... initialize the object ...;
2229 // } catch (...) {
2230 // __cxa_guard_abort (&obj_guard);
2231 // throw;
2232 // }
2233 // ... queue object destructor with __cxa_atexit() ...;
2234 // __cxa_guard_release (&obj_guard);
2235 // }
2236 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002237
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002238 // Load the first byte of the guard variable.
2239 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002240 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002241
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002242 // Itanium ABI:
2243 // An implementation supporting thread-safety on multiprocessor
2244 // systems must also guarantee that references to the initialized
2245 // object do not occur before the load of the initialization flag.
2246 //
2247 // In LLVM, we do this by marking the load Acquire.
2248 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002249 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002250
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002251 // For ARM, we should only check the first bit, rather than the entire byte:
2252 //
2253 // ARM C++ ABI 3.2.3.1:
2254 // To support the potential use of initialization guard variables
2255 // as semaphores that are the target of ARM SWP and LDREX/STREX
2256 // synchronizing instructions we define a static initialization
2257 // guard variable to be a 4-byte aligned, 4-byte word with the
2258 // following inline access protocol.
2259 // #define INITIALIZED 1
2260 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2261 // if (__cxa_guard_acquire(&obj_guard))
2262 // ...
2263 // }
2264 //
2265 // and similarly for ARM64:
2266 //
2267 // ARM64 C++ ABI 3.2.2:
2268 // This ABI instead only specifies the value bit 0 of the static guard
2269 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2270 // variable is not initialized and 1 when it is.
2271 llvm::Value *V =
2272 (UseARMGuardVarABI && !useInt8GuardVariable)
2273 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2274 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002275 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002276
2277 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2278 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2279
2280 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002281 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2282 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002283
2284 CGF.EmitBlock(InitCheckBlock);
2285
2286 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002287 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002288 // Call __cxa_guard_acquire.
2289 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002290 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002291
John McCall68ff0372010-09-08 01:44:27 +00002292 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002293
John McCall68ff0372010-09-08 01:44:27 +00002294 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2295 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002296
John McCall68ff0372010-09-08 01:44:27 +00002297 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002298 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002299
John McCall68ff0372010-09-08 01:44:27 +00002300 CGF.EmitBlock(InitBlock);
2301 }
2302
2303 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002304 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002305
John McCall5aa52592011-06-17 07:33:57 +00002306 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002307 // Pop the guard-abort cleanup if we pushed one.
2308 CGF.PopCleanupBlock();
2309
2310 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002311 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2312 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002313 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002314 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002315 }
2316
2317 CGF.EmitBlock(EndBlock);
2318}
John McCallc84ed6a2012-05-01 06:13:13 +00002319
2320/// Register a global destructor using __cxa_atexit.
2321static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
James Y Knightf7321542019-02-07 01:14:17 +00002322 llvm::FunctionCallee dtor,
2323 llvm::Constant *addr, bool TLS) {
Erich Keane34ec6922019-06-13 18:20:19 +00002324 assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
2325 "__cxa_atexit is disabled");
Bill Wendling95cae882013-05-02 19:18:03 +00002326 const char *Name = "__cxa_atexit";
2327 if (TLS) {
2328 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002329 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002330 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002331
John McCallc84ed6a2012-05-01 06:13:13 +00002332 // We're assuming that the destructor function is something we can
2333 // reasonably call with the default CC. Go ahead and cast it to the
2334 // right prototype.
2335 llvm::Type *dtorTy =
2336 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2337
Anastasia Stulova960ff082019-07-15 11:58:10 +00002338 // Preserve address space of addr.
2339 auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
2340 auto AddrInt8PtrTy =
2341 AddrAS ? CGF.Int8Ty->getPointerTo(AddrAS) : CGF.Int8PtrTy;
2342
2343 // Create a variable that binds the atexit to this shared object.
2344 llvm::Constant *handle =
2345 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2346 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2347 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2348
John McCallc84ed6a2012-05-01 06:13:13 +00002349 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
Anastasia Stulova960ff082019-07-15 11:58:10 +00002350 llvm::Type *paramTys[] = {dtorTy, AddrInt8PtrTy, handle->getType()};
John McCallc84ed6a2012-05-01 06:13:13 +00002351 llvm::FunctionType *atexitTy =
2352 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2353
2354 // Fetch the actual function.
James Y Knight9871db02019-02-05 16:42:33 +00002355 llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2356 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
John McCallc84ed6a2012-05-01 06:13:13 +00002357 fn->setDoesNotThrow();
2358
Akira Hatanaka617e2612018-04-17 18:41:52 +00002359 if (!addr)
2360 // addr is null when we are trying to register a dtor annotated with
2361 // __attribute__((destructor)) in a constructor function. Using null here is
2362 // okay because this argument is just passed back to the destructor
2363 // function.
2364 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2365
James Y Knightf7321542019-02-07 01:14:17 +00002366 llvm::Value *args[] = {llvm::ConstantExpr::getBitCast(
2367 cast<llvm::Constant>(dtor.getCallee()), dtorTy),
Anastasia Stulova960ff082019-07-15 11:58:10 +00002368 llvm::ConstantExpr::getBitCast(addr, AddrInt8PtrTy),
James Y Knightf7321542019-02-07 01:14:17 +00002369 handle};
John McCall882987f2013-02-28 19:01:20 +00002370 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002371}
2372
Akira Hatanaka617e2612018-04-17 18:41:52 +00002373void CodeGenModule::registerGlobalDtorsWithAtExit() {
2374 for (const auto I : DtorsUsingAtExit) {
2375 int Priority = I.first;
2376 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2377
2378 // Create a function that registers destructors that have the same priority.
2379 //
2380 // Since constructor functions are run in non-descending order of their
2381 // priorities, destructors are registered in non-descending order of their
2382 // priorities, and since destructor functions are run in the reverse order
2383 // of their registration, destructor functions are run in non-ascending
2384 // order of their priorities.
2385 CodeGenFunction CGF(*this);
2386 std::string GlobalInitFnName =
2387 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2388 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2389 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2390 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2391 SourceLocation());
2392 ASTContext &Ctx = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002393 QualType ReturnTy = Ctx.VoidTy;
2394 QualType FunctionTy = Ctx.getFunctionType(ReturnTy, llvm::None, {});
Akira Hatanaka617e2612018-04-17 18:41:52 +00002395 FunctionDecl *FD = FunctionDecl::Create(
2396 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002397 &Ctx.Idents.get(GlobalInitFnName), FunctionTy, nullptr, SC_Static,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002398 false, false);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002399 CGF.StartFunction(GlobalDecl(FD), ReturnTy, GlobalInitFn,
Akira Hatanaka617e2612018-04-17 18:41:52 +00002400 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2401 SourceLocation(), SourceLocation());
2402
2403 for (auto *Dtor : Dtors) {
2404 // Register the destructor function calling __cxa_atexit if it is
2405 // available. Otherwise fall back on calling atexit.
2406 if (getCodeGenOpts().CXAAtExit)
2407 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2408 else
2409 CGF.registerGlobalDtorWithAtExit(Dtor);
2410 }
2411
2412 CGF.FinishFunction();
2413 AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2414 }
2415}
2416
John McCallc84ed6a2012-05-01 06:13:13 +00002417/// Register a global destructor as best as we know how.
James Y Knightf7321542019-02-07 01:14:17 +00002418void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2419 llvm::FunctionCallee dtor,
John McCallc84ed6a2012-05-01 06:13:13 +00002420 llvm::Constant *addr) {
Erik Pilkington5a559e62018-08-21 17:24:06 +00002421 if (D.isNoDestroy(CGM.getContext()))
2422 return;
2423
Erich Keane34ec6922019-06-13 18:20:19 +00002424 // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
2425 // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
2426 // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
2427 // We can always use __cxa_thread_atexit.
2428 if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
Richard Smithdbf74ba2013-04-14 23:01:42 +00002429 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2430
John McCallc84ed6a2012-05-01 06:13:13 +00002431 // In Apple kexts, we want to add a global destructor entry.
2432 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002433 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002434 // Generate a global destructor entry.
2435 return CGM.AddCXXDtorEntry(dtor, addr);
2436 }
2437
David Blaikieebe87e12013-08-27 23:57:18 +00002438 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002439}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002440
David Majnemer9b21c332014-07-11 20:28:10 +00002441static bool isThreadWrapperReplaceable(const VarDecl *VD,
2442 CodeGen::CodeGenModule &CGM) {
2443 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002444 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002445 // the thread wrapper instead of directly referencing the backing variable.
2446 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002447 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002448}
2449
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002450/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002451/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002452/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002453static llvm::GlobalValue::LinkageTypes
2454getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2455 llvm::GlobalValue::LinkageTypes VarLinkage =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002456 CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
David Majnemer35ab3282014-06-11 04:08:55 +00002457
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002458 // For internal linkage variables, we don't need an external or weak wrapper.
2459 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2460 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002461
David Majnemer9b21c332014-07-11 20:28:10 +00002462 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002463 if (isThreadWrapperReplaceable(VD, CGM))
2464 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2465 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2466 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002467 return llvm::GlobalValue::WeakODRLinkage;
2468}
2469
2470llvm::Function *
2471ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002472 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002473 // Mangle the name for the thread_local wrapper function.
2474 SmallString<256> WrapperName;
2475 {
2476 llvm::raw_svector_ostream Out(WrapperName);
2477 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002478 }
2479
Akira Hatanaka26907f92016-01-15 03:34:06 +00002480 // FIXME: If VD is a definition, we should regenerate the function attributes
2481 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002482 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002483 return cast<llvm::Function>(V);
2484
Akira Hatanaka26907f92016-01-15 03:34:06 +00002485 QualType RetQT = VD->getType();
2486 if (RetQT->isReferenceType())
2487 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002488
John McCallc56a8b32016-03-11 04:30:31 +00002489 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2490 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002491
2492 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002493 llvm::Function *Wrapper =
2494 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2495 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002496
Erich Keanede6480a32018-11-13 15:48:08 +00002497 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper);
Akira Hatanaka26907f92016-01-15 03:34:06 +00002498
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002499 // Always resolve references to the wrapper at link time.
Vlad Tsyrklevichc93390b2019-01-17 17:53:45 +00002500 if (!Wrapper->hasLocalLinkage())
2501 if (!isThreadWrapperReplaceable(VD, CGM) ||
2502 llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
2503 llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
2504 VD->getVisibility() == HiddenVisibility)
2505 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002506
2507 if (isThreadWrapperReplaceable(VD, CGM)) {
2508 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2509 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2510 }
Richard Smith00223822019-09-12 20:00:24 +00002511
2512 ThreadWrappers.push_back({VD, Wrapper});
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002513 return Wrapper;
2514}
2515
2516void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002517 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2518 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2519 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002520 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002521
2522 // Separate initializers into those with ordered (or partially-ordered)
2523 // initialization and those with unordered initialization.
2524 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2525 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2526 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2527 if (isTemplateInstantiation(
2528 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2529 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2530 CXXThreadLocalInits[I];
2531 else
2532 OrderedInits.push_back(CXXThreadLocalInits[I]);
2533 }
2534
2535 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002536 // Generate a guarded initialization function.
2537 llvm::FunctionType *FTy =
2538 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002539 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2540 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002541 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002542 /*TLS=*/true);
2543 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2544 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2545 llvm::GlobalVariable::InternalLinkage,
2546 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2547 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002548
2549 CharUnits GuardAlign = CharUnits::One();
2550 Guard->setAlignment(GuardAlign.getQuantity());
2551
Richard Smith3ad06362018-10-31 20:39:26 +00002552 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
2553 InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002554 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2555 if (CGM.getTarget().getTriple().isOSDarwin()) {
2556 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2557 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2558 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002559 }
Richard Smithfbe23692017-01-13 00:43:31 +00002560
Richard Smith00223822019-09-12 20:00:24 +00002561 // Create declarations for thread wrappers for all thread-local variables
2562 // with non-discardable definitions in this translation unit.
Richard Smith5a99c492015-12-01 01:10:48 +00002563 for (const VarDecl *VD : CXXThreadLocals) {
Richard Smith00223822019-09-12 20:00:24 +00002564 if (VD->hasDefinition() &&
2565 !isDiscardableGVALinkage(getContext().GetGVALinkageForVariable(VD))) {
2566 llvm::GlobalValue *GV = CGM.GetGlobalValue(CGM.getMangledName(VD));
2567 getOrCreateThreadLocalWrapper(VD, GV);
2568 }
2569 }
2570
2571 // Emit all referenced thread wrappers.
2572 for (auto VDAndWrapper : ThreadWrappers) {
2573 const VarDecl *VD = VDAndWrapper.first;
Richard Smith5a99c492015-12-01 01:10:48 +00002574 llvm::GlobalVariable *Var =
2575 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smith00223822019-09-12 20:00:24 +00002576 llvm::Function *Wrapper = VDAndWrapper.second;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002577
David Majnemer9b21c332014-07-11 20:28:10 +00002578 // Some targets require that all access to thread local variables go through
2579 // the thread wrapper. This means that we cannot attempt to create a thread
2580 // wrapper or a thread helper.
Richard Smith00223822019-09-12 20:00:24 +00002581 if (!VD->hasDefinition()) {
2582 if (isThreadWrapperReplaceable(VD, CGM)) {
2583 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
2584 continue;
2585 }
2586
2587 // If this isn't a TU in which this variable is defined, the thread
2588 // wrapper is discardable.
2589 if (Wrapper->getLinkage() == llvm::Function::WeakODRLinkage)
2590 Wrapper->setLinkage(llvm::Function::LinkOnceODRLinkage);
Richard Smithfbe23692017-01-13 00:43:31 +00002591 }
David Majnemer9b21c332014-07-11 20:28:10 +00002592
Richard Smith00223822019-09-12 20:00:24 +00002593 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2594
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002595 // Mangle the name for the thread_local initialization function.
2596 SmallString<256> InitFnName;
2597 {
2598 llvm::raw_svector_ostream Out(InitFnName);
2599 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002600 }
2601
James Y Knightf7321542019-02-07 01:14:17 +00002602 llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2603
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002604 // If we have a definition for the variable, emit the initialization
2605 // function as an alias to the global Init function (if any). Otherwise,
2606 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002607 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002608 bool InitIsInitFunc = false;
Richard Smith00223822019-09-12 20:00:24 +00002609 bool HasConstantInitialization = false;
Richard Smith8ac5c742019-10-01 01:23:23 +00002610 if (!usesThreadWrapperFunction(VD)) {
Richard Smith00223822019-09-12 20:00:24 +00002611 HasConstantInitialization = true;
2612 } else if (VD->hasDefinition()) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002613 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002614 llvm::Function *InitFuncToUse = InitFunc;
2615 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2616 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2617 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002618 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002619 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002620 } else {
2621 // Emit a weak global function referring to the initialization function.
2622 // This function will not exist if the TU defining the thread_local
2623 // variable in question does not need any dynamic initialization for
2624 // its thread_local variables.
James Y Knightf7321542019-02-07 01:14:17 +00002625 Init = llvm::Function::Create(InitFnTy,
Richard Smithfbe23692017-01-13 00:43:31 +00002626 llvm::GlobalVariable::ExternalWeakLinkage,
2627 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002628 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Erich Keanede6480a32018-11-13 15:48:08 +00002629 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
2630 cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002631 }
2632
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002633 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002634 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002635 Init->setDSOLocal(Var->isDSOLocal());
2636 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002637
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002638 llvm::LLVMContext &Context = CGM.getModule().getContext();
2639 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002640 CGBuilderTy Builder(CGM, Entry);
Richard Smith00223822019-09-12 20:00:24 +00002641 if (HasConstantInitialization) {
2642 // No dynamic initialization to invoke.
2643 } else if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002644 if (Init) {
James Y Knightf7321542019-02-07 01:14:17 +00002645 llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002646 if (isThreadWrapperReplaceable(VD, CGM)) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002647 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002648 llvm::Function *Fn =
2649 cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
2650 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2651 }
Manman Ren5e5d0462016-03-18 23:35:21 +00002652 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002653 } else {
2654 // Don't know whether we have an init function. Call it if it exists.
2655 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2656 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2657 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2658 Builder.CreateCondBr(Have, InitBB, ExitBB);
2659
2660 Builder.SetInsertPoint(InitBB);
James Y Knightf7321542019-02-07 01:14:17 +00002661 Builder.CreateCall(InitFnTy, Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002662 Builder.CreateBr(ExitBB);
2663
2664 Builder.SetInsertPoint(ExitBB);
2665 }
2666
2667 // For a reference, the result of the wrapper function is a pointer to
2668 // the referenced object.
2669 llvm::Value *Val = Var;
2670 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002671 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2672 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002673 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002674 if (Val->getType() != Wrapper->getReturnType())
2675 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2676 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002677 Builder.CreateRet(Val);
2678 }
2679}
2680
Richard Smith0f383742014-03-26 22:48:22 +00002681LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2682 const VarDecl *VD,
2683 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002684 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002685 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002686
Manman Renb0b3af72015-12-17 00:42:36 +00002687 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002688 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002689
2690 LValue LV;
2691 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002692 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002693 else
Manman Renb0b3af72015-12-17 00:42:36 +00002694 LV = CGF.MakeAddrLValue(CallVal, LValType,
2695 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002696 // FIXME: need setObjCGCLValueClass?
2697 return LV;
2698}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002699
2700/// Return whether the given global decl needs a VTT parameter, which it does
2701/// if it's a base constructor or destructor with virtual bases.
2702bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2703 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002704
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002705 // We don't have any virtual bases, just return early.
2706 if (!MD->getParent()->getNumVBases())
2707 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002708
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002709 // Check if we have a base constructor.
2710 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2711 return true;
2712
2713 // Check if we have a base destructor.
2714 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2715 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002716
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002717 return false;
2718}
David Majnemere2cb8d12014-07-07 06:20:47 +00002719
2720namespace {
2721class ItaniumRTTIBuilder {
2722 CodeGenModule &CGM; // Per-module state.
2723 llvm::LLVMContext &VMContext;
2724 const ItaniumCXXABI &CXXABI; // Per-module state.
2725
2726 /// Fields - The fields of the RTTI descriptor currently being built.
2727 SmallVector<llvm::Constant *, 16> Fields;
2728
2729 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2730 llvm::GlobalVariable *
2731 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2732
2733 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2734 /// descriptor of the given type.
2735 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2736
2737 /// BuildVTablePointer - Build the vtable pointer for the given type.
2738 void BuildVTablePointer(const Type *Ty);
2739
2740 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2741 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2742 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2743
2744 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2745 /// classes with bases that do not satisfy the abi::__si_class_type_info
2746 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2747 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2748
2749 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2750 /// for pointer types.
2751 void BuildPointerTypeInfo(QualType PointeeTy);
2752
2753 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2754 /// type_info for an object type.
2755 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2756
2757 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2758 /// struct, used for member pointer types.
2759 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2760
2761public:
2762 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2763 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2764
2765 // Pointer type info flags.
2766 enum {
2767 /// PTI_Const - Type has const qualifier.
2768 PTI_Const = 0x1,
2769
2770 /// PTI_Volatile - Type has volatile qualifier.
2771 PTI_Volatile = 0x2,
2772
2773 /// PTI_Restrict - Type has restrict qualifier.
2774 PTI_Restrict = 0x4,
2775
2776 /// PTI_Incomplete - Type is incomplete.
2777 PTI_Incomplete = 0x8,
2778
2779 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2780 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002781 PTI_ContainingClassIncomplete = 0x10,
2782
2783 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2784 //PTI_TransactionSafe = 0x20,
2785
2786 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2787 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002788 };
2789
2790 // VMI type info flags.
2791 enum {
2792 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2793 VMI_NonDiamondRepeat = 0x1,
2794
2795 /// VMI_DiamondShaped - Class is diamond shaped.
2796 VMI_DiamondShaped = 0x2
2797 };
2798
2799 // Base class type info flags.
2800 enum {
2801 /// BCTI_Virtual - Base class is virtual.
2802 BCTI_Virtual = 0x1,
2803
2804 /// BCTI_Public - Base class is public.
2805 BCTI_Public = 0x2
2806 };
2807
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002808 /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
2809 /// link to an existing RTTI descriptor if one already exists.
2810 llvm::Constant *BuildTypeInfo(QualType Ty);
2811
David Majnemere2cb8d12014-07-07 06:20:47 +00002812 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00002813 llvm::Constant *BuildTypeInfo(
2814 QualType Ty,
2815 llvm::GlobalVariable::LinkageTypes Linkage,
2816 llvm::GlobalValue::VisibilityTypes Visibility,
2817 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00002818};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002819}
David Majnemere2cb8d12014-07-07 06:20:47 +00002820
2821llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2822 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002823 SmallString<256> Name;
2824 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002825 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002826
2827 // We know that the mangled name of the type starts at index 4 of the
2828 // mangled name of the typename, so we can just index into it in order to
2829 // get the mangled name of the type.
2830 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2831 Name.substr(4));
David Greenbe0c5b62018-09-12 14:09:06 +00002832 auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00002833
David Greenbe0c5b62018-09-12 14:09:06 +00002834 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2835 Name, Init->getType(), Linkage, Align.getQuantity());
David Majnemere2cb8d12014-07-07 06:20:47 +00002836
2837 GV->setInitializer(Init);
2838
2839 return GV;
2840}
2841
2842llvm::Constant *
2843ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2844 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002845 SmallString<256> Name;
2846 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002847 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002848
2849 // Look for an existing global.
2850 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2851
2852 if (!GV) {
2853 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002854 // Note for the future: If we would ever like to do deferred emission of
2855 // RTTI, check if emitting vtables opportunistically need any adjustment.
2856
David Majnemere2cb8d12014-07-07 06:20:47 +00002857 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002858 /*isConstant=*/true,
David Majnemere2cb8d12014-07-07 06:20:47 +00002859 llvm::GlobalValue::ExternalLinkage, nullptr,
2860 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002861 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2862 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002863 }
2864
2865 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2866}
2867
2868/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2869/// info for that type is defined in the standard library.
2870static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2871 // Itanium C++ ABI 2.9.2:
2872 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2873 // the run-time support library. Specifically, the run-time support
2874 // library should contain type_info objects for the types X, X* and
2875 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2876 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2877 // long, unsigned long, long long, unsigned long long, float, double,
2878 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2879 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002880 //
2881 // GCC also emits RTTI for __int128.
2882 // FIXME: We do not emit RTTI information for decimal types here.
2883
2884 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002885 switch (Ty->getKind()) {
2886 case BuiltinType::Void:
2887 case BuiltinType::NullPtr:
2888 case BuiltinType::Bool:
2889 case BuiltinType::WChar_S:
2890 case BuiltinType::WChar_U:
2891 case BuiltinType::Char_U:
2892 case BuiltinType::Char_S:
2893 case BuiltinType::UChar:
2894 case BuiltinType::SChar:
2895 case BuiltinType::Short:
2896 case BuiltinType::UShort:
2897 case BuiltinType::Int:
2898 case BuiltinType::UInt:
2899 case BuiltinType::Long:
2900 case BuiltinType::ULong:
2901 case BuiltinType::LongLong:
2902 case BuiltinType::ULongLong:
2903 case BuiltinType::Half:
2904 case BuiltinType::Float:
2905 case BuiltinType::Double:
2906 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002907 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002908 case BuiltinType::Float128:
Richard Smith3a8244d2018-05-01 05:02:45 +00002909 case BuiltinType::Char8:
David Majnemere2cb8d12014-07-07 06:20:47 +00002910 case BuiltinType::Char16:
2911 case BuiltinType::Char32:
2912 case BuiltinType::Int128:
2913 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002914 return true;
2915
Alexey Bader954ba212016-04-08 13:40:33 +00002916#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2917 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002918#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002919#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2920 case BuiltinType::Id:
2921#include "clang/Basic/OpenCLExtensionTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002922 case BuiltinType::OCLSampler:
2923 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002924 case BuiltinType::OCLClkEvent:
2925 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002926 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00002927#define SVE_TYPE(Name, Id, SingletonId) \
2928 case BuiltinType::Id:
2929#include "clang/Basic/AArch64SVEACLETypes.def"
Leonard Chanf921d852018-06-04 16:07:52 +00002930 case BuiltinType::ShortAccum:
2931 case BuiltinType::Accum:
2932 case BuiltinType::LongAccum:
2933 case BuiltinType::UShortAccum:
2934 case BuiltinType::UAccum:
2935 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002936 case BuiltinType::ShortFract:
2937 case BuiltinType::Fract:
2938 case BuiltinType::LongFract:
2939 case BuiltinType::UShortFract:
2940 case BuiltinType::UFract:
2941 case BuiltinType::ULongFract:
2942 case BuiltinType::SatShortAccum:
2943 case BuiltinType::SatAccum:
2944 case BuiltinType::SatLongAccum:
2945 case BuiltinType::SatUShortAccum:
2946 case BuiltinType::SatUAccum:
2947 case BuiltinType::SatULongAccum:
2948 case BuiltinType::SatShortFract:
2949 case BuiltinType::SatFract:
2950 case BuiltinType::SatLongFract:
2951 case BuiltinType::SatUShortFract:
2952 case BuiltinType::SatUFract:
2953 case BuiltinType::SatULongFract:
Richard Smith4a382012016-02-03 01:32:42 +00002954 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002955
2956 case BuiltinType::Dependent:
2957#define BUILTIN_TYPE(Id, SingletonId)
2958#define PLACEHOLDER_TYPE(Id, SingletonId) \
2959 case BuiltinType::Id:
2960#include "clang/AST/BuiltinTypes.def"
2961 llvm_unreachable("asking for RRTI for a placeholder type!");
2962
2963 case BuiltinType::ObjCId:
2964 case BuiltinType::ObjCClass:
2965 case BuiltinType::ObjCSel:
2966 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2967 }
2968
2969 llvm_unreachable("Invalid BuiltinType Kind!");
2970}
2971
2972static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2973 QualType PointeeTy = PointerTy->getPointeeType();
2974 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2975 if (!BuiltinTy)
2976 return false;
2977
2978 // Check the qualifiers.
2979 Qualifiers Quals = PointeeTy.getQualifiers();
2980 Quals.removeConst();
2981
2982 if (!Quals.empty())
2983 return false;
2984
2985 return TypeInfoIsInStandardLibrary(BuiltinTy);
2986}
2987
2988/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2989/// information for the given type exists in the standard library.
2990static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2991 // Type info for builtin types is defined in the standard library.
2992 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2993 return TypeInfoIsInStandardLibrary(BuiltinTy);
2994
2995 // Type info for some pointer types to builtin types is defined in the
2996 // standard library.
2997 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2998 return TypeInfoIsInStandardLibrary(PointerTy);
2999
3000 return false;
3001}
3002
3003/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
3004/// the given type exists somewhere else, and that we should not emit the type
3005/// information in this translation unit. Assumes that it is not a
3006/// standard-library type.
3007static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
3008 QualType Ty) {
3009 ASTContext &Context = CGM.getContext();
3010
3011 // If RTTI is disabled, assume it might be disabled in the
3012 // translation unit that defines any potential key function, too.
3013 if (!Context.getLangOpts().RTTI) return false;
3014
3015 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3016 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
3017 if (!RD->hasDefinition())
3018 return false;
3019
3020 if (!RD->isDynamicClass())
3021 return false;
3022
3023 // FIXME: this may need to be reconsidered if the key function
3024 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00003025 // N.B. We must always emit the RTTI data ourselves if there exists a key
3026 // function.
3027 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00003028
3029 // Don't import the RTTI but emit it locally.
Martin Storsjo228ccd62019-04-26 19:31:51 +00003030 if (CGM.getTriple().isWindowsGNUEnvironment())
Martin Storsjo3b528942018-02-02 06:22:35 +00003031 return false;
3032
David Majnemer1fb1a042014-11-07 07:26:38 +00003033 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00003034 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
3035 ? false
3036 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00003037
David Majnemerbe9022c2015-08-06 20:56:55 +00003038 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00003039 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00003040 }
3041
3042 return false;
3043}
3044
3045/// IsIncompleteClassType - Returns whether the given record type is incomplete.
3046static bool IsIncompleteClassType(const RecordType *RecordTy) {
3047 return !RecordTy->getDecl()->isCompleteDefinition();
3048}
3049
3050/// ContainsIncompleteClassType - Returns whether the given type contains an
3051/// incomplete class type. This is true if
3052///
3053/// * The given type is an incomplete class type.
3054/// * The given type is a pointer type whose pointee type contains an
3055/// incomplete class type.
3056/// * The given type is a member pointer type whose class is an incomplete
3057/// class type.
3058/// * The given type is a member pointer type whoise pointee type contains an
3059/// incomplete class type.
3060/// is an indirect or direct pointer to an incomplete class type.
3061static bool ContainsIncompleteClassType(QualType Ty) {
3062 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3063 if (IsIncompleteClassType(RecordTy))
3064 return true;
3065 }
3066
3067 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3068 return ContainsIncompleteClassType(PointerTy->getPointeeType());
3069
3070 if (const MemberPointerType *MemberPointerTy =
3071 dyn_cast<MemberPointerType>(Ty)) {
3072 // Check if the class type is incomplete.
3073 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
3074 if (IsIncompleteClassType(ClassType))
3075 return true;
3076
3077 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
3078 }
3079
3080 return false;
3081}
3082
3083// CanUseSingleInheritance - Return whether the given record decl has a "single,
3084// public, non-virtual base at offset zero (i.e. the derived class is dynamic
3085// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3086static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
3087 // Check the number of bases.
3088 if (RD->getNumBases() != 1)
3089 return false;
3090
3091 // Get the base.
3092 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
3093
3094 // Check that the base is not virtual.
3095 if (Base->isVirtual())
3096 return false;
3097
3098 // Check that the base is public.
3099 if (Base->getAccessSpecifier() != AS_public)
3100 return false;
3101
3102 // Check that the class is dynamic iff the base is.
Simon Pilgrimf2805472019-10-02 20:45:16 +00003103 auto *BaseDecl =
3104 cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00003105 if (!BaseDecl->isEmpty() &&
3106 BaseDecl->isDynamicClass() != RD->isDynamicClass())
3107 return false;
3108
3109 return true;
3110}
3111
3112void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
3113 // abi::__class_type_info.
3114 static const char * const ClassTypeInfo =
3115 "_ZTVN10__cxxabiv117__class_type_infoE";
3116 // abi::__si_class_type_info.
3117 static const char * const SIClassTypeInfo =
3118 "_ZTVN10__cxxabiv120__si_class_type_infoE";
3119 // abi::__vmi_class_type_info.
3120 static const char * const VMIClassTypeInfo =
3121 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3122
3123 const char *VTableName = nullptr;
3124
3125 switch (Ty->getTypeClass()) {
3126#define TYPE(Class, Base)
3127#define ABSTRACT_TYPE(Class, Base)
3128#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3129#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3130#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003131#include "clang/AST/TypeNodes.inc"
David Majnemere2cb8d12014-07-07 06:20:47 +00003132 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3133
3134 case Type::LValueReference:
3135 case Type::RValueReference:
3136 llvm_unreachable("References shouldn't get here");
3137
3138 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003139 case Type::DeducedTemplateSpecialization:
3140 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003141
Xiuli Pan9c14e282016-01-09 12:53:17 +00003142 case Type::Pipe:
3143 llvm_unreachable("Pipe types shouldn't get here");
3144
David Majnemere2cb8d12014-07-07 06:20:47 +00003145 case Type::Builtin:
3146 // GCC treats vector and complex types as fundamental types.
3147 case Type::Vector:
3148 case Type::ExtVector:
3149 case Type::Complex:
3150 case Type::Atomic:
3151 // FIXME: GCC treats block pointers as fundamental types?!
3152 case Type::BlockPointer:
3153 // abi::__fundamental_type_info.
3154 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
3155 break;
3156
3157 case Type::ConstantArray:
3158 case Type::IncompleteArray:
3159 case Type::VariableArray:
3160 // abi::__array_type_info.
3161 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
3162 break;
3163
3164 case Type::FunctionNoProto:
3165 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003166 // abi::__function_type_info.
3167 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00003168 break;
3169
3170 case Type::Enum:
3171 // abi::__enum_type_info.
3172 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
3173 break;
3174
3175 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00003176 const CXXRecordDecl *RD =
3177 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00003178
3179 if (!RD->hasDefinition() || !RD->getNumBases()) {
3180 VTableName = ClassTypeInfo;
3181 } else if (CanUseSingleInheritance(RD)) {
3182 VTableName = SIClassTypeInfo;
3183 } else {
3184 VTableName = VMIClassTypeInfo;
3185 }
3186
3187 break;
3188 }
3189
3190 case Type::ObjCObject:
3191 // Ignore protocol qualifiers.
3192 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
3193
3194 // Handle id and Class.
3195 if (isa<BuiltinType>(Ty)) {
3196 VTableName = ClassTypeInfo;
3197 break;
3198 }
3199
3200 assert(isa<ObjCInterfaceType>(Ty));
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003201 LLVM_FALLTHROUGH;
David Majnemere2cb8d12014-07-07 06:20:47 +00003202
3203 case Type::ObjCInterface:
3204 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
3205 VTableName = SIClassTypeInfo;
3206 } else {
3207 VTableName = ClassTypeInfo;
3208 }
3209 break;
3210
3211 case Type::ObjCObjectPointer:
3212 case Type::Pointer:
3213 // abi::__pointer_type_info.
3214 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
3215 break;
3216
3217 case Type::MemberPointer:
3218 // abi::__pointer_to_member_type_info.
3219 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
3220 break;
3221 }
3222
3223 llvm::Constant *VTable =
3224 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00003225 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00003226
3227 llvm::Type *PtrDiffTy =
3228 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
3229
3230 // The vtable address point is 2.
3231 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00003232 VTable =
3233 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00003234 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3235
3236 Fields.push_back(VTable);
3237}
3238
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003239/// Return the linkage that the type info and type info name constants
David Majnemere2cb8d12014-07-07 06:20:47 +00003240/// should have for the given type.
Richard Smithbbb26552018-05-21 20:10:54 +00003241static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
3242 QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003243 // Itanium C++ ABI 2.9.5p7:
3244 // In addition, it and all of the intermediate abi::__pointer_type_info
3245 // structs in the chain down to the abi::__class_type_info for the
3246 // incomplete class type must be prevented from resolving to the
3247 // corresponding type_info structs for the complete class type, possibly
3248 // by making them local static objects. Finally, a dummy class RTTI is
3249 // generated for the incomplete type that will not resolve to the final
3250 // complete class RTTI (because the latter need not exist), possibly by
3251 // making it a local static object.
3252 if (ContainsIncompleteClassType(Ty))
Richard Smithbbb26552018-05-21 20:10:54 +00003253 return llvm::GlobalValue::InternalLinkage;
3254
3255 switch (Ty->getLinkage()) {
3256 case NoLinkage:
3257 case InternalLinkage:
3258 case UniqueExternalLinkage:
3259 return llvm::GlobalValue::InternalLinkage;
3260
3261 case VisibleNoLinkage:
3262 case ModuleInternalLinkage:
3263 case ModuleLinkage:
3264 case ExternalLinkage:
3265 // RTTI is not enabled, which means that this type info struct is going
3266 // to be used for exception handling. Give it linkonce_odr linkage.
3267 if (!CGM.getLangOpts().RTTI)
3268 return llvm::GlobalValue::LinkOnceODRLinkage;
3269
3270 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3271 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3272 if (RD->hasAttr<WeakAttr>())
3273 return llvm::GlobalValue::WeakODRLinkage;
3274 if (CGM.getTriple().isWindowsItaniumEnvironment())
3275 if (RD->hasAttr<DLLImportAttr>() &&
3276 ShouldUseExternalRTTIDescriptor(CGM, Ty))
3277 return llvm::GlobalValue::ExternalLinkage;
3278 // MinGW always uses LinkOnceODRLinkage for type info.
3279 if (RD->isDynamicClass() &&
3280 !CGM.getContext()
3281 .getTargetInfo()
3282 .getTriple()
3283 .isWindowsGNUEnvironment())
3284 return CGM.getVTableLinkage(RD);
3285 }
3286
3287 return llvm::GlobalValue::LinkOnceODRLinkage;
3288 }
3289
3290 llvm_unreachable("Invalid linkage!");
David Majnemere2cb8d12014-07-07 06:20:47 +00003291}
3292
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003293llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003294 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003295 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003296
3297 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003298 SmallString<256> Name;
3299 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003300 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003301
3302 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3303 if (OldGV && !OldGV->isDeclaration()) {
3304 assert(!OldGV->hasAvailableExternallyLinkage() &&
3305 "available_externally typeinfos not yet implemented");
3306
3307 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3308 }
3309
3310 // Check if there is already an external RTTI descriptor for this type.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003311 if (IsStandardLibraryRTTIDescriptor(Ty) ||
3312 ShouldUseExternalRTTIDescriptor(CGM, Ty))
David Majnemere2cb8d12014-07-07 06:20:47 +00003313 return GetAddrOfExternalRTTIDescriptor(Ty);
3314
3315 // Emit the standard library with external linkage.
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003316 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
Richard Smithbbb26552018-05-21 20:10:54 +00003317
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003318 // Give the type_info object and name the formal visibility of the
3319 // type itself.
3320 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3321 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3322 // If the linkage is local, only default visibility makes sense.
3323 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3324 else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
3325 ItaniumCXXABI::RUK_NonUniqueHidden)
3326 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3327 else
3328 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3329
3330 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3331 llvm::GlobalValue::DefaultStorageClass;
3332 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3333 auto RD = Ty->getAsCXXRecordDecl();
3334 if (RD && RD->hasAttr<DLLExportAttr>())
3335 DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
3336 }
3337
3338 return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
3339}
3340
3341llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
3342 QualType Ty,
3343 llvm::GlobalVariable::LinkageTypes Linkage,
3344 llvm::GlobalValue::VisibilityTypes Visibility,
3345 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003346 // Add the vtable pointer.
3347 BuildVTablePointer(cast<Type>(Ty));
3348
3349 // And the name.
Richard Smithbbb26552018-05-21 20:10:54 +00003350 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003351 llvm::Constant *TypeNameField;
3352
3353 // If we're supposed to demote the visibility, be sure to set a flag
3354 // to use a string comparison for type_info comparisons.
3355 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
Richard Smithbbb26552018-05-21 20:10:54 +00003356 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003357 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3358 // The flag is the sign bit, which on ARM64 is defined to be clear
3359 // for global pointers. This is very ARM64-specific.
3360 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3361 llvm::Constant *flag =
3362 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3363 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3364 TypeNameField =
3365 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3366 } else {
3367 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3368 }
3369 Fields.push_back(TypeNameField);
3370
3371 switch (Ty->getTypeClass()) {
3372#define TYPE(Class, Base)
3373#define ABSTRACT_TYPE(Class, Base)
3374#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3375#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3376#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003377#include "clang/AST/TypeNodes.inc"
David Majnemere2cb8d12014-07-07 06:20:47 +00003378 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3379
3380 // GCC treats vector types as fundamental types.
3381 case Type::Builtin:
3382 case Type::Vector:
3383 case Type::ExtVector:
3384 case Type::Complex:
3385 case Type::BlockPointer:
3386 // Itanium C++ ABI 2.9.5p4:
3387 // abi::__fundamental_type_info adds no data members to std::type_info.
3388 break;
3389
3390 case Type::LValueReference:
3391 case Type::RValueReference:
3392 llvm_unreachable("References shouldn't get here");
3393
3394 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003395 case Type::DeducedTemplateSpecialization:
3396 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003397
Xiuli Pan9c14e282016-01-09 12:53:17 +00003398 case Type::Pipe:
3399 llvm_unreachable("Pipe type shouldn't get here");
3400
David Majnemere2cb8d12014-07-07 06:20:47 +00003401 case Type::ConstantArray:
3402 case Type::IncompleteArray:
3403 case Type::VariableArray:
3404 // Itanium C++ ABI 2.9.5p5:
3405 // abi::__array_type_info adds no data members to std::type_info.
3406 break;
3407
3408 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003409 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003410 // Itanium C++ ABI 2.9.5p5:
3411 // abi::__function_type_info adds no data members to std::type_info.
3412 break;
3413
3414 case Type::Enum:
3415 // Itanium C++ ABI 2.9.5p5:
3416 // abi::__enum_type_info adds no data members to std::type_info.
3417 break;
3418
3419 case Type::Record: {
3420 const CXXRecordDecl *RD =
3421 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3422 if (!RD->hasDefinition() || !RD->getNumBases()) {
3423 // We don't need to emit any fields.
3424 break;
3425 }
3426
3427 if (CanUseSingleInheritance(RD))
3428 BuildSIClassTypeInfo(RD);
3429 else
3430 BuildVMIClassTypeInfo(RD);
3431
3432 break;
3433 }
3434
3435 case Type::ObjCObject:
3436 case Type::ObjCInterface:
3437 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3438 break;
3439
3440 case Type::ObjCObjectPointer:
3441 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3442 break;
3443
3444 case Type::Pointer:
3445 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3446 break;
3447
3448 case Type::MemberPointer:
3449 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3450 break;
3451
3452 case Type::Atomic:
3453 // No fields, at least for the moment.
3454 break;
3455 }
3456
3457 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3458
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003459 SmallString<256> Name;
3460 llvm::raw_svector_ostream Out(Name);
3461 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003462 llvm::Module &M = CGM.getModule();
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003463 llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003464 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003465 new llvm::GlobalVariable(M, Init->getType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003466 /*isConstant=*/true, Linkage, Init, Name);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003467
David Majnemere2cb8d12014-07-07 06:20:47 +00003468 // If there's already an old global variable, replace it with the new one.
3469 if (OldGV) {
3470 GV->takeName(OldGV);
3471 llvm::Constant *NewPtr =
3472 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3473 OldGV->replaceAllUsesWith(NewPtr);
3474 OldGV->eraseFromParent();
3475 }
3476
Yaron Keren04da2382015-07-29 15:42:28 +00003477 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3478 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3479
David Greenbe0c5b62018-09-12 14:09:06 +00003480 CharUnits Align =
3481 CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
3482 GV->setAlignment(Align.getQuantity());
3483
David Majnemere2cb8d12014-07-07 06:20:47 +00003484 // The Itanium ABI specifies that type_info objects must be globally
3485 // unique, with one exception: if the type is an incomplete class
3486 // type or a (possibly indirect) pointer to one. That exception
3487 // affects the general case of comparing type_info objects produced
3488 // by the typeid operator, which is why the comparison operators on
3489 // std::type_info generally use the type_info name pointers instead
3490 // of the object addresses. However, the language's built-in uses
3491 // of RTTI generally require class types to be complete, even when
3492 // manipulating pointers to those class types. This allows the
3493 // implementation of dynamic_cast to rely on address equality tests,
3494 // which is much faster.
3495
3496 // All of this is to say that it's important that both the type_info
3497 // object and the type_info name be uniqued when weakly emitted.
3498
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003499 TypeName->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003500 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003501
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003502 GV->setVisibility(Visibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003503 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003504
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003505 TypeName->setDLLStorageClass(DLLStorageClass);
3506 GV->setDLLStorageClass(DLLStorageClass);
David Majnemere2cb8d12014-07-07 06:20:47 +00003507
Peter Collingbournee08e68d2019-06-07 19:10:08 +00003508 TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3509 GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
3510
David Majnemere2cb8d12014-07-07 06:20:47 +00003511 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3512}
3513
David Majnemere2cb8d12014-07-07 06:20:47 +00003514/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3515/// for the given Objective-C object type.
3516void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3517 // Drop qualifiers.
3518 const Type *T = OT->getBaseType().getTypePtr();
3519 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3520
3521 // The builtin types are abi::__class_type_infos and don't require
3522 // extra fields.
3523 if (isa<BuiltinType>(T)) return;
3524
3525 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3526 ObjCInterfaceDecl *Super = Class->getSuperClass();
3527
3528 // Root classes are also __class_type_info.
3529 if (!Super) return;
3530
3531 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3532
3533 // Everything else is single inheritance.
3534 llvm::Constant *BaseTypeInfo =
3535 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3536 Fields.push_back(BaseTypeInfo);
3537}
3538
3539/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3540/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3541void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3542 // Itanium C++ ABI 2.9.5p6b:
3543 // It adds to abi::__class_type_info a single member pointing to the
3544 // type_info structure for the base type,
3545 llvm::Constant *BaseTypeInfo =
3546 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3547 Fields.push_back(BaseTypeInfo);
3548}
3549
3550namespace {
3551 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3552 /// a class hierarchy.
3553 struct SeenBases {
3554 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3555 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3556 };
3557}
3558
3559/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3560/// abi::__vmi_class_type_info.
3561///
3562static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3563 SeenBases &Bases) {
3564
3565 unsigned Flags = 0;
3566
Simon Pilgrimf2805472019-10-02 20:45:16 +00003567 auto *BaseDecl =
3568 cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00003569
3570 if (Base->isVirtual()) {
3571 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003572 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003573 // If this virtual base has been seen before, then the class is diamond
3574 // shaped.
3575 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3576 } else {
3577 if (Bases.NonVirtualBases.count(BaseDecl))
3578 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3579 }
3580 } else {
3581 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003582 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003583 // If this non-virtual base has been seen before, then the class has non-
3584 // diamond shaped repeated inheritance.
3585 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3586 } else {
3587 if (Bases.VirtualBases.count(BaseDecl))
3588 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3589 }
3590 }
3591
3592 // Walk all bases.
3593 for (const auto &I : BaseDecl->bases())
3594 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3595
3596 return Flags;
3597}
3598
3599static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3600 unsigned Flags = 0;
3601 SeenBases Bases;
3602
3603 // Walk all bases.
3604 for (const auto &I : RD->bases())
3605 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3606
3607 return Flags;
3608}
3609
3610/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3611/// classes with bases that do not satisfy the abi::__si_class_type_info
3612/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3613void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3614 llvm::Type *UnsignedIntLTy =
3615 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3616
3617 // Itanium C++ ABI 2.9.5p6c:
3618 // __flags is a word with flags describing details about the class
3619 // structure, which may be referenced by using the __flags_masks
3620 // enumeration. These flags refer to both direct and indirect bases.
3621 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3622 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3623
3624 // Itanium C++ ABI 2.9.5p6c:
3625 // __base_count is a word with the number of direct proper base class
3626 // descriptions that follow.
3627 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3628
3629 if (!RD->getNumBases())
3630 return;
3631
David Majnemere2cb8d12014-07-07 06:20:47 +00003632 // Now add the base class descriptions.
3633
3634 // Itanium C++ ABI 2.9.5p6c:
3635 // __base_info[] is an array of base class descriptions -- one for every
3636 // direct proper base. Each description is of the type:
3637 //
3638 // struct abi::__base_class_type_info {
3639 // public:
3640 // const __class_type_info *__base_type;
3641 // long __offset_flags;
3642 //
3643 // enum __offset_flags_masks {
3644 // __virtual_mask = 0x1,
3645 // __public_mask = 0x2,
3646 // __offset_shift = 8
3647 // };
3648 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003649
3650 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3651 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3652 // LLP64 platforms.
3653 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3654 // LLP64 platforms.
3655 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3656 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3657 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3658 OffsetFlagsTy = CGM.getContext().LongLongTy;
3659 llvm::Type *OffsetFlagsLTy =
3660 CGM.getTypes().ConvertType(OffsetFlagsTy);
3661
David Majnemere2cb8d12014-07-07 06:20:47 +00003662 for (const auto &Base : RD->bases()) {
3663 // The __base_type member points to the RTTI for the base type.
3664 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3665
Simon Pilgrimf2805472019-10-02 20:45:16 +00003666 auto *BaseDecl =
3667 cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00003668
3669 int64_t OffsetFlags = 0;
3670
3671 // All but the lower 8 bits of __offset_flags are a signed offset.
3672 // For a non-virtual base, this is the offset in the object of the base
3673 // subobject. For a virtual base, this is the offset in the virtual table of
3674 // the virtual base offset for the virtual base referenced (negative).
3675 CharUnits Offset;
3676 if (Base.isVirtual())
3677 Offset =
3678 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3679 else {
3680 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3681 Offset = Layout.getBaseClassOffset(BaseDecl);
3682 };
3683
3684 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3685
3686 // The low-order byte of __offset_flags contains flags, as given by the
3687 // masks from the enumeration __offset_flags_masks.
3688 if (Base.isVirtual())
3689 OffsetFlags |= BCTI_Virtual;
3690 if (Base.getAccessSpecifier() == AS_public)
3691 OffsetFlags |= BCTI_Public;
3692
Reid Klecknerd8b04662016-08-25 22:16:30 +00003693 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003694 }
3695}
3696
Richard Smitha7d93782016-12-01 03:32:42 +00003697/// Compute the flags for a __pbase_type_info, and remove the corresponding
3698/// pieces from \p Type.
3699static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3700 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003701
Richard Smitha7d93782016-12-01 03:32:42 +00003702 if (Type.isConstQualified())
3703 Flags |= ItaniumRTTIBuilder::PTI_Const;
3704 if (Type.isVolatileQualified())
3705 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3706 if (Type.isRestrictQualified())
3707 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3708 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003709
3710 // Itanium C++ ABI 2.9.5p7:
3711 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3712 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003713 if (ContainsIncompleteClassType(Type))
3714 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3715
3716 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003717 if (Proto->isNothrow()) {
Richard Smitha7d93782016-12-01 03:32:42 +00003718 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003719 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003720 }
3721 }
3722
3723 return Flags;
3724}
3725
3726/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3727/// used for pointer types.
3728void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3729 // Itanium C++ ABI 2.9.5p7:
3730 // __flags is a flag word describing the cv-qualification and other
3731 // attributes of the type pointed to
3732 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003733
3734 llvm::Type *UnsignedIntLTy =
3735 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3736 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3737
3738 // Itanium C++ ABI 2.9.5p7:
3739 // __pointee is a pointer to the std::type_info derivation for the
3740 // unqualified type being pointed to.
3741 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003742 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003743 Fields.push_back(PointeeTypeInfo);
3744}
3745
3746/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3747/// struct, used for member pointer types.
3748void
3749ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3750 QualType PointeeTy = Ty->getPointeeType();
3751
David Majnemere2cb8d12014-07-07 06:20:47 +00003752 // Itanium C++ ABI 2.9.5p7:
3753 // __flags is a flag word describing the cv-qualification and other
3754 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003755 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003756
3757 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003758 if (IsIncompleteClassType(ClassType))
3759 Flags |= PTI_ContainingClassIncomplete;
3760
3761 llvm::Type *UnsignedIntLTy =
3762 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3763 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3764
3765 // Itanium C++ ABI 2.9.5p7:
3766 // __pointee is a pointer to the std::type_info derivation for the
3767 // unqualified type being pointed to.
3768 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003769 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003770 Fields.push_back(PointeeTypeInfo);
3771
3772 // Itanium C++ ABI 2.9.5p9:
3773 // __context is a pointer to an abi::__class_type_info corresponding to the
3774 // class type containing the member pointed to
3775 // (e.g., the "A" in "int A::*").
3776 Fields.push_back(
3777 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3778}
3779
David Majnemer443250f2015-03-17 20:35:00 +00003780llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003781 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3782}
3783
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003784void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
Richard Smith4a382012016-02-03 01:32:42 +00003785 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003786 QualType FundamentalTypes[] = {
3787 getContext().VoidTy, getContext().NullPtrTy,
3788 getContext().BoolTy, getContext().WCharTy,
3789 getContext().CharTy, getContext().UnsignedCharTy,
3790 getContext().SignedCharTy, getContext().ShortTy,
3791 getContext().UnsignedShortTy, getContext().IntTy,
3792 getContext().UnsignedIntTy, getContext().LongTy,
3793 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003794 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3795 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003796 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003797 getContext().LongDoubleTy, getContext().Float128Ty,
Richard Smith3a8244d2018-05-01 05:02:45 +00003798 getContext().Char8Ty, getContext().Char16Ty,
3799 getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003800 };
Thomas Andersonb6d87cf2018-07-24 00:43:47 +00003801 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
3802 RD->hasAttr<DLLExportAttr>()
3803 ? llvm::GlobalValue::DLLExportStorageClass
3804 : llvm::GlobalValue::DefaultStorageClass;
3805 llvm::GlobalValue::VisibilityTypes Visibility =
3806 CodeGenModule::GetLLVMVisibility(RD->getVisibility());
3807 for (const QualType &FundamentalType : FundamentalTypes) {
3808 QualType PointerType = getContext().getPointerType(FundamentalType);
3809 QualType PointerTypeConst = getContext().getPointerType(
3810 FundamentalType.withConst());
3811 for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
3812 ItaniumRTTIBuilder(*this).BuildTypeInfo(
3813 Type, llvm::GlobalValue::ExternalLinkage,
3814 Visibility, DLLStorageClass);
3815 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003816}
3817
3818/// What sort of uniqueness rules should we use for the RTTI for the
3819/// given type?
3820ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3821 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3822 if (shouldRTTIBeUnique())
3823 return RUK_Unique;
3824
3825 // It's only necessary for linkonce_odr or weak_odr linkage.
3826 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3827 Linkage != llvm::GlobalValue::WeakODRLinkage)
3828 return RUK_Unique;
3829
3830 // It's only necessary with default visibility.
3831 if (CanTy->getVisibility() != DefaultVisibility)
3832 return RUK_Unique;
3833
3834 // If we're not required to publish this symbol, hide it.
3835 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3836 return RUK_NonUniqueHidden;
3837
3838 // If we're required to publish this symbol, as we might be under an
3839 // explicit instantiation, leave it with default visibility but
3840 // enable string-comparisons.
3841 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3842 return RUK_NonUniqueVisible;
3843}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003844
Rafael Espindola1e4df922014-09-16 15:18:21 +00003845// Find out how to codegen the complete destructor and constructor
3846namespace {
3847enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3848}
3849static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3850 const CXXMethodDecl *MD) {
3851 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3852 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003853
Rafael Espindola1e4df922014-09-16 15:18:21 +00003854 // The complete and base structors are not equivalent if there are any virtual
3855 // bases, so emit separate functions.
3856 if (MD->getParent()->getNumVBases())
3857 return StructorCodegen::Emit;
3858
3859 GlobalDecl AliasDecl;
3860 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3861 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3862 } else {
3863 const auto *CD = cast<CXXConstructorDecl>(MD);
3864 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3865 }
3866 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3867
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003868 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3869 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003870
Pavel Labathc370f262018-05-14 11:35:44 +00003871 // FIXME: Should we allow available_externally aliases?
Chandler Carruth1f82d9b2018-07-29 03:05:07 +00003872 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3873 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003874
Rafael Espindola0806f982014-09-16 20:19:43 +00003875 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003876 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3877 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3878 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003879 return StructorCodegen::COMDAT;
3880 return StructorCodegen::Emit;
3881 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003882
3883 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003884}
3885
Rafael Espindola1e4df922014-09-16 15:18:21 +00003886static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3887 GlobalDecl AliasDecl,
3888 GlobalDecl TargetDecl) {
3889 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3890
3891 StringRef MangledName = CGM.getMangledName(AliasDecl);
3892 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3893 if (Entry && !Entry->isDeclaration())
3894 return;
3895
3896 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003897
3898 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003899 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003900
Peter Collingbourned914fd22018-06-18 20:58:54 +00003901 // Constructors and destructors are always unnamed_addr.
3902 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3903
Rafael Espindola1e4df922014-09-16 15:18:21 +00003904 // Switch any previous uses to the alias.
3905 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003906 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003907 "declaration exists with different type");
3908 Alias->takeName(Entry);
3909 Entry->replaceAllUsesWith(Alias);
3910 Entry->eraseFromParent();
3911 } else {
3912 Alias->setName(MangledName);
3913 }
3914
3915 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003916 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003917}
3918
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003919void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
3920 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
Rafael Espindola1e4df922014-09-16 15:18:21 +00003921 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3922 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3923
3924 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3925
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003926 if (CD ? GD.getCtorType() == Ctor_Complete
3927 : GD.getDtorType() == Dtor_Complete) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00003928 GlobalDecl BaseDecl;
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003929 if (CD)
3930 BaseDecl = GD.getWithCtorType(Ctor_Base);
3931 else
3932 BaseDecl = GD.getWithDtorType(Dtor_Base);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003933
3934 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003935 emitConstructorDestructorAlias(CGM, GD, BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003936 return;
3937 }
3938
3939 if (CGType == StructorCodegen::RAUW) {
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003940 StringRef MangledName = CGM.getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003941 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003942 CGM.addReplacement(MangledName, Aliasee);
3943 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003944 }
3945 }
3946
3947 // The base destructor is equivalent to the base destructor of its
3948 // base class if there is exactly one non-virtual base class with a
3949 // non-trivial destructor, there are no fields with a non-trivial
3950 // destructor, and the body of the destructor is trivial.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003951 if (DD && GD.getDtorType() == Dtor_Base &&
3952 CGType != StructorCodegen::COMDAT &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003953 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003954 return;
3955
Richard Smith5b349582017-10-13 01:55:36 +00003956 // FIXME: The deleting destructor is equivalent to the selected operator
3957 // delete if:
3958 // * either the delete is a destroying operator delete or the destructor
3959 // would be trivial if it weren't virtual,
3960 // * the conversion from the 'this' parameter to the first parameter of the
3961 // destructor is equivalent to a bitcast,
3962 // * the destructor does not have an implicit "this" return, and
3963 // * the operator delete has the same calling convention and IR function type
3964 // as the destructor.
3965 // In such cases we should try to emit the deleting dtor as an alias to the
3966 // selected 'operator delete'.
3967
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003968 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003969
Rafael Espindola1e4df922014-09-16 15:18:21 +00003970 if (CGType == StructorCodegen::COMDAT) {
3971 SmallString<256> Buffer;
3972 llvm::raw_svector_ostream Out(Buffer);
3973 if (DD)
3974 getMangleContext().mangleCXXDtorComdat(DD, Out);
3975 else
3976 getMangleContext().mangleCXXCtorComdat(CD, Out);
3977 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3978 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003979 } else {
3980 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003981 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003982}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003983
James Y Knight9871db02019-02-05 16:42:33 +00003984static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003985 // void *__cxa_begin_catch(void*);
3986 llvm::FunctionType *FTy = llvm::FunctionType::get(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003987 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003988
3989 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3990}
3991
James Y Knight9871db02019-02-05 16:42:33 +00003992static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003993 // void __cxa_end_catch();
3994 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003995 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003996
3997 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3998}
3999
James Y Knight9871db02019-02-05 16:42:33 +00004000static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004001 // void *__cxa_get_exception_ptr(void*);
4002 llvm::FunctionType *FTy = llvm::FunctionType::get(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004003 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004004
4005 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
4006}
4007
4008namespace {
4009 /// A cleanup to call __cxa_end_catch. In many cases, the caught
4010 /// exception type lets us state definitively that the thrown exception
4011 /// type does not have a destructor. In particular:
4012 /// - Catch-alls tell us nothing, so we have to conservatively
4013 /// assume that the thrown exception might have a destructor.
4014 /// - Catches by reference behave according to their base types.
4015 /// - Catches of non-record types will only trigger for exceptions
4016 /// of non-record types, which never have destructors.
4017 /// - Catches of record types can trigger for arbitrary subclasses
4018 /// of the caught type, so we have to assume the actual thrown
4019 /// exception type might have a throwing destructor, even if the
4020 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00004021 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004022 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
4023 bool MightThrow;
4024
4025 void Emit(CodeGenFunction &CGF, Flags flags) override {
4026 if (!MightThrow) {
4027 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
4028 return;
4029 }
4030
4031 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
4032 }
4033 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004034}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004035
4036/// Emits a call to __cxa_begin_catch and enters a cleanup to call
4037/// __cxa_end_catch.
4038///
4039/// \param EndMightThrow - true if __cxa_end_catch might throw
4040static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
4041 llvm::Value *Exn,
4042 bool EndMightThrow) {
4043 llvm::CallInst *call =
4044 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
4045
4046 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
4047
4048 return call;
4049}
4050
4051/// A "special initializer" callback for initializing a catch
4052/// parameter during catch initialization.
4053static void InitCatchParam(CodeGenFunction &CGF,
4054 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00004055 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004056 SourceLocation Loc) {
4057 // Load the exception from where the landing pad saved it.
4058 llvm::Value *Exn = CGF.getExceptionFromSlot();
4059
4060 CanQualType CatchType =
4061 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
4062 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
4063
4064 // If we're catching by reference, we can just cast the object
4065 // pointer to the appropriate pointer.
4066 if (isa<ReferenceType>(CatchType)) {
4067 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
4068 bool EndCatchMightThrow = CaughtType->isRecordType();
4069
4070 // __cxa_begin_catch returns the adjusted object pointer.
4071 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
4072
4073 // We have no way to tell the personality function that we're
4074 // catching by reference, so if we're catching a pointer,
4075 // __cxa_begin_catch will actually return that pointer by value.
4076 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
4077 QualType PointeeType = PT->getPointeeType();
4078
4079 // When catching by reference, generally we should just ignore
4080 // this by-value pointer and use the exception object instead.
4081 if (!PointeeType->isRecordType()) {
4082
4083 // Exn points to the struct _Unwind_Exception header, which
4084 // we have to skip past in order to reach the exception data.
4085 unsigned HeaderSize =
4086 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
4087 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
4088
4089 // However, if we're catching a pointer-to-record type that won't
4090 // work, because the personality function might have adjusted
4091 // the pointer. There's actually no way for us to fully satisfy
4092 // the language/ABI contract here: we can't use Exn because it
4093 // might have the wrong adjustment, but we can't use the by-value
4094 // pointer because it's off by a level of abstraction.
4095 //
4096 // The current solution is to dump the adjusted pointer into an
4097 // alloca, which breaks language semantics (because changing the
4098 // pointer doesn't change the exception) but at least works.
4099 // The better solution would be to filter out non-exact matches
4100 // and rethrow them, but this is tricky because the rethrow
4101 // really needs to be catchable by other sites at this landing
4102 // pad. The best solution is to fix the personality function.
4103 } else {
4104 // Pull the pointer for the reference type off.
4105 llvm::Type *PtrTy =
4106 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
4107
4108 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00004109 Address ExnPtrTmp =
4110 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004111 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4112 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
4113
4114 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00004115 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004116 }
4117 }
4118
4119 llvm::Value *ExnCast =
4120 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
4121 CGF.Builder.CreateStore(ExnCast, ParamAddr);
4122 return;
4123 }
4124
4125 // Scalars and complexes.
4126 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
4127 if (TEK != TEK_Aggregate) {
4128 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
4129
4130 // If the catch type is a pointer type, __cxa_begin_catch returns
4131 // the pointer by value.
4132 if (CatchType->hasPointerRepresentation()) {
4133 llvm::Value *CastExn =
4134 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
4135
4136 switch (CatchType.getQualifiers().getObjCLifetime()) {
4137 case Qualifiers::OCL_Strong:
4138 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004139 LLVM_FALLTHROUGH;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004140
4141 case Qualifiers::OCL_None:
4142 case Qualifiers::OCL_ExplicitNone:
4143 case Qualifiers::OCL_Autoreleasing:
4144 CGF.Builder.CreateStore(CastExn, ParamAddr);
4145 return;
4146
4147 case Qualifiers::OCL_Weak:
4148 CGF.EmitARCInitWeak(ParamAddr, CastExn);
4149 return;
4150 }
4151 llvm_unreachable("bad ownership qualifier!");
4152 }
4153
4154 // Otherwise, it returns a pointer into the exception object.
4155
4156 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4157 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4158
4159 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00004160 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004161 switch (TEK) {
4162 case TEK_Complex:
4163 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
4164 /*init*/ true);
4165 return;
4166 case TEK_Scalar: {
4167 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
4168 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
4169 return;
4170 }
4171 case TEK_Aggregate:
4172 llvm_unreachable("evaluation kind filtered out!");
4173 }
4174 llvm_unreachable("bad evaluation kind");
4175 }
4176
4177 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00004178 auto catchRD = CatchType->getAsCXXRecordDecl();
4179 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004180
4181 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
4182
4183 // Check for a copy expression. If we don't have a copy expression,
4184 // that means a trivial copy is okay.
4185 const Expr *copyExpr = CatchParam.getInit();
4186 if (!copyExpr) {
4187 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00004188 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4189 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004190 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
4191 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
Richard Smithe78fac52018-04-05 20:52:58 +00004192 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004193 return;
4194 }
4195
4196 // We have to call __cxa_get_exception_ptr to get the adjusted
4197 // pointer before copying.
4198 llvm::CallInst *rawAdjustedExn =
4199 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
4200
4201 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00004202 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
4203 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004204
4205 // The copy expression is defined in terms of an OpaqueValueExpr.
4206 // Find it and map it to the adjusted expression.
4207 CodeGenFunction::OpaqueValueMapping
4208 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
4209 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
4210
4211 // Call the copy ctor in a terminate scope.
4212 CGF.EHStack.pushTerminate();
4213
4214 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004215 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00004216 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004217 AggValueSlot::IsNotDestructed,
4218 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00004219 AggValueSlot::IsNotAliased,
4220 AggValueSlot::DoesNotOverlap));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004221
4222 // Leave the terminate scope.
4223 CGF.EHStack.popTerminate();
4224
4225 // Undo the opaque value mapping.
4226 opaque.pop();
4227
4228 // Finally we can call __cxa_begin_catch.
4229 CallBeginCatch(CGF, Exn, true);
4230}
4231
4232/// Begins a catch statement by initializing the catch variable and
4233/// calling __cxa_begin_catch.
4234void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4235 const CXXCatchStmt *S) {
4236 // We have to be very careful with the ordering of cleanups here:
4237 // C++ [except.throw]p4:
4238 // The destruction [of the exception temporary] occurs
4239 // immediately after the destruction of the object declared in
4240 // the exception-declaration in the handler.
4241 //
4242 // So the precise ordering is:
4243 // 1. Construct catch variable.
4244 // 2. __cxa_begin_catch
4245 // 3. Enter __cxa_end_catch cleanup
4246 // 4. Enter dtor cleanup
4247 //
4248 // We do this by using a slightly abnormal initialization process.
4249 // Delegation sequence:
4250 // - ExitCXXTryStmt opens a RunCleanupsScope
4251 // - EmitAutoVarAlloca creates the variable and debug info
4252 // - InitCatchParam initializes the variable from the exception
4253 // - CallBeginCatch calls __cxa_begin_catch
4254 // - CallBeginCatch enters the __cxa_end_catch cleanup
4255 // - EmitAutoVarCleanups enters the variable destructor cleanup
4256 // - EmitCXXTryStmt emits the code for the catch body
4257 // - EmitCXXTryStmt close the RunCleanupsScope
4258
4259 VarDecl *CatchParam = S->getExceptionDecl();
4260 if (!CatchParam) {
4261 llvm::Value *Exn = CGF.getExceptionFromSlot();
4262 CallBeginCatch(CGF, Exn, true);
4263 return;
4264 }
4265
4266 // Emit the local.
4267 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004268 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004269 CGF.EmitAutoVarCleanups(var);
4270}
4271
4272/// Get or define the following function:
4273/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
4274/// This code is used only in C++.
James Y Knight9871db02019-02-05 16:42:33 +00004275static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004276 llvm::FunctionType *fnTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004277 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
James Y Knight9871db02019-02-05 16:42:33 +00004278 llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00004279 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00004280 llvm::Function *fn =
4281 cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
4282 if (fn->empty()) {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004283 fn->setDoesNotThrow();
4284 fn->setDoesNotReturn();
4285
4286 // What we really want is to massively penalize inlining without
4287 // forbidding it completely. The difference between that and
4288 // 'noinline' is negligible.
4289 fn->addFnAttr(llvm::Attribute::NoInline);
4290
4291 // Allow this function to be shared across translation units, but
4292 // we don't want it to turn into an exported symbol.
4293 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4294 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004295 if (CGM.supportsCOMDAT())
4296 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004297
4298 // Set up the function.
4299 llvm::BasicBlock *entry =
James Y Knight9871db02019-02-05 16:42:33 +00004300 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004301 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004302
4303 // Pull the exception pointer out of the parameter list.
4304 llvm::Value *exn = &*fn->arg_begin();
4305
4306 // Call __cxa_begin_catch(exn).
4307 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4308 catchCall->setDoesNotThrow();
4309 catchCall->setCallingConv(CGM.getRuntimeCC());
4310
4311 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004312 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004313 termCall->setDoesNotThrow();
4314 termCall->setDoesNotReturn();
4315 termCall->setCallingConv(CGM.getRuntimeCC());
4316
4317 // std::terminate cannot return.
4318 builder.CreateUnreachable();
4319 }
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004320 return fnRef;
4321}
4322
4323llvm::CallInst *
4324ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4325 llvm::Value *Exn) {
4326 // In C++, we want to call __cxa_begin_catch() before terminating.
4327 if (Exn) {
4328 assert(CGF.CGM.getLangOpts().CPlusPlus);
4329 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4330 }
4331 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4332}
Peter Collingbourne60108802017-12-13 21:53:04 +00004333
4334std::pair<llvm::Value *, const CXXRecordDecl *>
4335ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4336 const CXXRecordDecl *RD) {
4337 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4338}
Heejin Ahnc6479192018-05-31 22:18:13 +00004339
4340void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4341 const CXXCatchStmt *C) {
Heejin Ahn1eb074d2018-06-01 01:01:37 +00004342 if (CGF.getTarget().hasFeature("exception-handling"))
4343 CGF.EHStack.pushCleanup<CatchRetScope>(
4344 NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
Heejin Ahnc6479192018-05-31 22:18:13 +00004345 ItaniumCXXABI::emitBeginCatch(CGF, C);
4346}