blob: 3e2c461d6a7946eff3f1be10bca16740abb3814c [file] [log] [blame]
Charles Davis4e786dd2010-05-25 19:52:27 +00001//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Itanium C++ ABI. The class
Charles Davis4e786dd2010-05-25 19:52:27 +000011// in this file generates structures that follow the Itanium C++ ABI, which is
12// documented at:
13// http://www.codesourcery.com/public/cxx-abi/abi.html
14// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
John McCall86353412010-08-21 22:46:04 +000015//
16// It also supports the closely-related ARM ABI, documented at:
17// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18//
Charles Davis4e786dd2010-05-25 19:52:27 +000019//===----------------------------------------------------------------------===//
20
21#include "CGCXXABI.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000022#include "CGCleanup.h"
John McCall7a9aac22010-08-23 01:21:21 +000023#include "CGRecordLayout.h"
Charles Davisa325a6e2012-06-23 23:44:00 +000024#include "CGVTables.h"
John McCall475999d2010-08-22 00:05:51 +000025#include "CodeGenFunction.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000026#include "CodeGenModule.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000027#include "TargetInfo.h"
John McCall5ad74072017-03-02 20:04:19 +000028#include "clang/CodeGen/ConstantInitBuilder.h"
Craig Topperc9ee1d02012-09-15 18:47:51 +000029#include "clang/AST/Mangle.h"
30#include "clang/AST/Type.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000031#include "clang/AST/StmtCXX.h"
David Majnemer1162d252014-06-22 19:05:33 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000034#include "llvm/IR/Instructions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000035#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Value.h"
Akira Hatanaka617e2612018-04-17 18:41:52 +000037#include "llvm/Support/ScopedPrinter.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000038
39using namespace clang;
John McCall475999d2010-08-22 00:05:51 +000040using namespace CodeGen;
Charles Davis4e786dd2010-05-25 19:52:27 +000041
42namespace {
Charles Davis53c59df2010-08-16 03:33:14 +000043class ItaniumCXXABI : public CodeGen::CGCXXABI {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000044 /// VTables - All the vtables which have been defined.
45 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
46
John McCall475999d2010-08-22 00:05:51 +000047protected:
Mark Seabornedf0d382013-07-24 16:25:13 +000048 bool UseARMMethodPtrABI;
49 bool UseARMGuardVarABI;
John McCalld23b27e2016-09-16 02:40:45 +000050 bool Use32BitVTableOffsetABI;
John McCall7a9aac22010-08-23 01:21:21 +000051
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000052 ItaniumMangleContext &getMangleContext() {
53 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
54 }
55
Charles Davis4e786dd2010-05-25 19:52:27 +000056public:
Mark Seabornedf0d382013-07-24 16:25:13 +000057 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
58 bool UseARMMethodPtrABI = false,
59 bool UseARMGuardVarABI = false) :
60 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
John McCalld23b27e2016-09-16 02:40:45 +000061 UseARMGuardVarABI(UseARMGuardVarABI),
Richard Smithb17d6fa2016-12-01 03:04:07 +000062 Use32BitVTableOffsetABI(false) { }
John McCall475999d2010-08-22 00:05:51 +000063
Reid Kleckner40ca9132014-05-13 22:05:45 +000064 bool classifyReturnType(CGFunctionInfo &FI) const override;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000065
Richard Smithf667ad52017-08-26 01:04:35 +000066 bool passClassIndirect(const CXXRecordDecl *RD) const {
Richard Smithf667ad52017-08-26 01:04:35 +000067 return !canCopyArgument(RD);
68 }
69
Craig Topper4f12f102014-03-12 06:41:41 +000070 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
Richard Smith96cd6712017-08-16 01:49:53 +000071 // If C++ prohibits us from making a copy, pass by address.
Richard Smithf667ad52017-08-26 01:04:35 +000072 if (passClassIndirect(RD))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000073 return RAA_Indirect;
74 return RAA_Default;
75 }
76
John McCall7f416cc2015-09-08 08:05:57 +000077 bool isThisCompleteObject(GlobalDecl GD) const override {
78 // The Itanium ABI has separate complete-object vs. base-object
79 // variants of both constructors and destructors.
80 if (isa<CXXDestructorDecl>(GD.getDecl())) {
81 switch (GD.getDtorType()) {
82 case Dtor_Complete:
83 case Dtor_Deleting:
84 return true;
85
86 case Dtor_Base:
87 return false;
88
89 case Dtor_Comdat:
90 llvm_unreachable("emitting dtor comdat as function?");
91 }
92 llvm_unreachable("bad dtor kind");
93 }
94 if (isa<CXXConstructorDecl>(GD.getDecl())) {
95 switch (GD.getCtorType()) {
96 case Ctor_Complete:
97 return true;
98
99 case Ctor_Base:
100 return false;
101
102 case Ctor_CopyingClosure:
103 case Ctor_DefaultClosure:
104 llvm_unreachable("closure ctors in Itanium ABI?");
105
106 case Ctor_Comdat:
107 llvm_unreachable("emitting ctor comdat as function?");
108 }
109 llvm_unreachable("bad dtor kind");
110 }
111
112 // No other kinds.
113 return false;
114 }
115
Craig Topper4f12f102014-03-12 06:41:41 +0000116 bool isZeroInitializable(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000117
Craig Topper4f12f102014-03-12 06:41:41 +0000118 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
John McCall7a9aac22010-08-23 01:21:21 +0000119
John McCallb92ab1a2016-10-26 23:46:34 +0000120 CGCallee
Craig Topper4f12f102014-03-12 06:41:41 +0000121 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
122 const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000123 Address This,
124 llvm::Value *&ThisPtrForCall,
Craig Topper4f12f102014-03-12 06:41:41 +0000125 llvm::Value *MemFnPtr,
126 const MemberPointerType *MPT) override;
John McCalla8bbb822010-08-22 03:04:22 +0000127
Craig Topper4f12f102014-03-12 06:41:41 +0000128 llvm::Value *
129 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000130 Address Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000131 llvm::Value *MemPtr,
132 const MemberPointerType *MPT) override;
John McCallc134eb52010-08-31 21:07:20 +0000133
John McCall7a9aac22010-08-23 01:21:21 +0000134 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
135 const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000136 llvm::Value *Src) override;
John McCallc62bb392012-02-15 01:22:51 +0000137 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
Craig Topper4f12f102014-03-12 06:41:41 +0000138 llvm::Constant *Src) override;
John McCall84fa5102010-08-22 04:16:24 +0000139
Craig Topper4f12f102014-03-12 06:41:41 +0000140 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
John McCall84fa5102010-08-22 04:16:24 +0000141
David Majnemere2be95b2015-06-23 07:31:01 +0000142 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
John McCallf3a88602011-02-03 08:15:49 +0000143 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000144 CharUnits offset) override;
145 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
Richard Smithdafff942012-01-14 04:30:29 +0000146 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
147 CharUnits ThisAdjustment);
John McCall1c456c82010-08-22 06:43:33 +0000148
John McCall7a9aac22010-08-23 01:21:21 +0000149 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000150 llvm::Value *L, llvm::Value *R,
John McCall7a9aac22010-08-23 01:21:21 +0000151 const MemberPointerType *MPT,
Craig Topper4f12f102014-03-12 06:41:41 +0000152 bool Inequality) override;
John McCall131d97d2010-08-22 08:30:07 +0000153
John McCall7a9aac22010-08-23 01:21:21 +0000154 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000155 llvm::Value *Addr,
156 const MemberPointerType *MPT) override;
John McCall5d865c322010-08-31 07:33:07 +0000157
David Majnemer08681372014-11-01 07:37:17 +0000158 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +0000159 Address Ptr, QualType ElementType,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000160 const CXXDestructorDecl *Dtor) override;
John McCall82fb8922012-09-25 10:10:39 +0000161
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000162 /// Itanium says that an _Unwind_Exception has to be "double-word"
163 /// aligned (and thus the end of it is also so-aligned), meaning 16
164 /// bytes. Of course, that was written for the actual Itanium,
165 /// which is a 64-bit platform. Classically, the ABI doesn't really
166 /// specify the alignment on other platforms, but in practice
167 /// libUnwind declares the struct with __attribute__((aligned)), so
168 /// we assume that alignment here. (It's generally 16 bytes, but
169 /// some targets overwrite it.)
John McCall7f416cc2015-09-08 08:05:57 +0000170 CharUnits getAlignmentOfExnObject() {
Akira Hatanakac47fcf02017-07-27 18:52:44 +0000171 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned();
172 return CGM.getContext().toCharUnitsFromBits(align);
John McCall7f416cc2015-09-08 08:05:57 +0000173 }
174
David Majnemer442d0a22014-11-25 07:20:20 +0000175 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
David Majnemer7c237072015-03-05 00:46:22 +0000176 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
David Majnemer442d0a22014-11-25 07:20:20 +0000177
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000178 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
179
180 llvm::CallInst *
181 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
182 llvm::Value *Exn) override;
183
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +0000184 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
185 void EmitFundamentalRTTIDescriptors(bool DLLExport);
David Majnemer443250f2015-03-17 20:35:00 +0000186 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
Reid Kleckner10aa7702015-09-16 20:15:55 +0000187 CatchTypeInfo
David Majnemer37b417f2015-03-29 21:55:10 +0000188 getAddrOfCXXCatchHandlerType(QualType Ty,
189 QualType CatchHandlerType) override {
Reid Kleckner10aa7702015-09-16 20:15:55 +0000190 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
David Majnemer443250f2015-03-17 20:35:00 +0000191 }
David Majnemere2cb8d12014-07-07 06:20:47 +0000192
David Majnemer1162d252014-06-22 19:05:33 +0000193 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
194 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
195 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +0000196 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +0000197 llvm::Type *StdTypeInfoPtrTy) override;
198
199 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
200 QualType SrcRecordTy) override;
201
John McCall7f416cc2015-09-08 08:05:57 +0000202 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000203 QualType SrcRecordTy, QualType DestTy,
204 QualType DestRecordTy,
205 llvm::BasicBlock *CastEnd) override;
206
John McCall7f416cc2015-09-08 08:05:57 +0000207 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
David Majnemer1162d252014-06-22 19:05:33 +0000208 QualType SrcRecordTy,
209 QualType DestTy) override;
210
211 bool EmitBadCastCall(CodeGenFunction &CGF) override;
212
Craig Topper4f12f102014-03-12 06:41:41 +0000213 llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +0000214 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000215 const CXXRecordDecl *ClassDecl,
216 const CXXRecordDecl *BaseClassDecl) override;
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000217
Craig Topper4f12f102014-03-12 06:41:41 +0000218 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000219
George Burgess IVf203dbf2017-02-22 20:28:02 +0000220 AddedStructorArgs
221 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
222 SmallVectorImpl<CanQualType> &ArgTys) override;
John McCall5d865c322010-08-31 07:33:07 +0000223
Reid Klecknere7de47e2013-07-22 13:51:44 +0000224 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
Craig Topper4f12f102014-03-12 06:41:41 +0000225 CXXDtorType DT) const override {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000226 // Itanium does not emit any destructor variant as an inline thunk.
227 // Delegating may occur as an optimization, but all variants are either
228 // emitted with external linkage or as linkonce if they are inline and used.
229 return false;
230 }
231
Craig Topper4f12f102014-03-12 06:41:41 +0000232 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
Reid Klecknere7de47e2013-07-22 13:51:44 +0000233
Reid Kleckner89077a12013-12-17 19:46:40 +0000234 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
Craig Topper4f12f102014-03-12 06:41:41 +0000235 FunctionArgList &Params) override;
John McCall5d865c322010-08-31 07:33:07 +0000236
Craig Topper4f12f102014-03-12 06:41:41 +0000237 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
John McCall8ed55a52010-09-02 09:58:18 +0000238
George Burgess IVf203dbf2017-02-22 20:28:02 +0000239 AddedStructorArgs
240 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
241 CXXCtorType Type, bool ForVirtualBase,
242 bool Delegating, CallArgList &Args) override;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000243
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000244 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
245 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +0000246 bool Delegating, Address This) override;
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000247
Craig Topper4f12f102014-03-12 06:41:41 +0000248 void emitVTableDefinitions(CodeGenVTables &CGVT,
249 const CXXRecordDecl *RD) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000250
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000251 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
252 CodeGenFunction::VPtr Vptr) override;
253
254 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
255 return true;
256 }
257
258 llvm::Constant *
259 getVTableAddressPoint(BaseSubobject Base,
260 const CXXRecordDecl *VTableClass) override;
261
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000262 llvm::Value *getVTableAddressPointInStructor(
263 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000264 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
265
266 llvm::Value *getVTableAddressPointInStructorWithVTT(
267 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
268 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000269
270 llvm::Constant *
271 getVTableAddressPointForConstExpr(BaseSubobject Base,
Craig Topper4f12f102014-03-12 06:41:41 +0000272 const CXXRecordDecl *VTableClass) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000273
274 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
Craig Topper4f12f102014-03-12 06:41:41 +0000275 CharUnits VPtrOffset) override;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000276
John McCall9831b842018-02-06 18:52:44 +0000277 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
278 Address This, llvm::Type *Ty,
279 SourceLocation Loc) override;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000280
David Majnemer0c0b6d92014-10-31 20:09:12 +0000281 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
282 const CXXDestructorDecl *Dtor,
283 CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +0000284 Address This,
David Majnemer0c0b6d92014-10-31 20:09:12 +0000285 const CXXMemberCallExpr *CE) override;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000286
Craig Topper4f12f102014-03-12 06:41:41 +0000287 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
Reid Kleckner7810af02013-06-19 15:20:38 +0000288
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000289 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000290
Hans Wennborgc94391d2014-06-06 20:04:01 +0000291 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
292 bool ReturnAdjustment) override {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000293 // Allow inlining of thunks by emitting them with available_externally
294 // linkage together with vtables when needed.
Peter Collingbourne8fabc1b2015-07-01 02:10:26 +0000295 if (ForVTable && !Thunk->hasLocalLinkage())
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000296 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
Rafael Espindolab7350042018-03-01 00:35:47 +0000297 CGM.setGVProperties(Thunk, GD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000298 }
299
Rafael Espindolab7350042018-03-01 00:35:47 +0000300 bool exportThunk() override { return true; }
301
John McCall7f416cc2015-09-08 08:05:57 +0000302 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
Craig Topper4f12f102014-03-12 06:41:41 +0000303 const ThisAdjustment &TA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000304
John McCall7f416cc2015-09-08 08:05:57 +0000305 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Craig Topper4f12f102014-03-12 06:41:41 +0000306 const ReturnAdjustment &RA) override;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000307
David Majnemer196ac332014-09-11 23:05:02 +0000308 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
309 FunctionArgList &Args) const override {
310 assert(!Args.empty() && "expected the arglist to not be empty!");
311 return Args.size() - 1;
312 }
313
Craig Topper4f12f102014-03-12 06:41:41 +0000314 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
315 StringRef GetDeletedVirtualCallName() override
316 { return "__cxa_deleted_virtual"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +0000317
Craig Topper4f12f102014-03-12 06:41:41 +0000318 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000319 Address InitializeArrayCookie(CodeGenFunction &CGF,
320 Address NewPtr,
321 llvm::Value *NumElements,
322 const CXXNewExpr *expr,
323 QualType ElementType) override;
John McCallb91cd662012-05-01 05:23:51 +0000324 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000325 Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000326 CharUnits cookieSize) override;
John McCall68ff0372010-09-08 01:44:27 +0000327
John McCallcdf7ef52010-11-06 09:44:32 +0000328 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000329 llvm::GlobalVariable *DeclPtr,
330 bool PerformInit) override;
Richard Smithdbf74ba2013-04-14 23:01:42 +0000331 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
Craig Topper4f12f102014-03-12 06:41:41 +0000332 llvm::Constant *dtor, llvm::Constant *addr) override;
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000333
334 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +0000335 llvm::Value *Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000336 void EmitThreadLocalInitFuncs(
David Majnemerb3341ea2014-10-05 05:05:40 +0000337 CodeGenModule &CGM,
Richard Smith5a99c492015-12-01 01:10:48 +0000338 ArrayRef<const VarDecl *> CXXThreadLocals,
David Majnemerb3341ea2014-10-05 05:05:40 +0000339 ArrayRef<llvm::Function *> CXXThreadLocalInits,
Richard Smith5a99c492015-12-01 01:10:48 +0000340 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
David Majnemerb3341ea2014-10-05 05:05:40 +0000341
342 bool usesThreadWrapperFunction() const override { return true; }
Richard Smith0f383742014-03-26 22:48:22 +0000343 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
344 QualType LValType) override;
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000345
Craig Topper4f12f102014-03-12 06:41:41 +0000346 bool NeedsVTTParameter(GlobalDecl GD) override;
David Majnemere2cb8d12014-07-07 06:20:47 +0000347
348 /**************************** RTTI Uniqueness ******************************/
349
350protected:
351 /// Returns true if the ABI requires RTTI type_info objects to be unique
352 /// across a program.
353 virtual bool shouldRTTIBeUnique() const { return true; }
354
355public:
356 /// What sort of unique-RTTI behavior should we use?
357 enum RTTIUniquenessKind {
358 /// We are guaranteeing, or need to guarantee, that the RTTI string
359 /// is unique.
360 RUK_Unique,
361
362 /// We are not guaranteeing uniqueness for the RTTI string, so we
363 /// can demote to hidden visibility but must use string comparisons.
364 RUK_NonUniqueHidden,
365
366 /// We are not guaranteeing uniqueness for the RTTI string, so we
367 /// have to use string comparisons, but we also have to emit it with
368 /// non-hidden visibility.
369 RUK_NonUniqueVisible
370 };
371
372 /// Return the required visibility status for the given type and linkage in
373 /// the current ABI.
374 RTTIUniquenessKind
375 classifyRTTIUniqueness(QualType CanTy,
376 llvm::GlobalValue::LinkageTypes Linkage) const;
377 friend class ItaniumRTTIBuilder;
Rafael Espindola91f68b42014-09-15 19:20:10 +0000378
379 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000380
Peter Collingbourne60108802017-12-13 21:53:04 +0000381 std::pair<llvm::Value *, const CXXRecordDecl *>
382 LoadVTablePtr(CodeGenFunction &CGF, Address This,
383 const CXXRecordDecl *RD) override;
384
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000385 private:
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000386 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
387 const auto &VtableLayout =
388 CGM.getItaniumVTableContext().getVTableLayout(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000389
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000390 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
391 // Skip empty slot.
392 if (!VtableComponent.isUsedFunctionPointerKind())
393 continue;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000394
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000395 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
396 if (!Method->getCanonicalDecl()->isInlined())
397 continue;
398
399 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
400 auto *Entry = CGM.GetGlobalValue(Name);
401 // This checks if virtual inline function has already been emitted.
402 // Note that it is possible that this inline function would be emitted
403 // after trying to emit vtable speculatively. Because of this we do
404 // an extra pass after emitting all deferred vtables to find and emit
405 // these vtables opportunistically.
406 if (!Entry || Entry->isDeclaration())
407 return true;
408 }
409 return false;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000410 }
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000411
412 bool isVTableHidden(const CXXRecordDecl *RD) const {
413 const auto &VtableLayout =
414 CGM.getItaniumVTableContext().getVTableLayout(RD);
415
416 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
417 if (VtableComponent.isRTTIKind()) {
418 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
419 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
420 return true;
421 } else if (VtableComponent.isUsedFunctionPointerKind()) {
422 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
423 if (Method->getVisibility() == Visibility::HiddenVisibility &&
424 !Method->isDefined())
425 return true;
426 }
427 }
428 return false;
429 }
Charles Davis4e786dd2010-05-25 19:52:27 +0000430};
John McCall86353412010-08-21 22:46:04 +0000431
432class ARMCXXABI : public ItaniumCXXABI {
433public:
Mark Seabornedf0d382013-07-24 16:25:13 +0000434 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
435 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
436 /* UseARMGuardVarABI = */ true) {}
John McCall5d865c322010-08-31 07:33:07 +0000437
Craig Topper4f12f102014-03-12 06:41:41 +0000438 bool HasThisReturn(GlobalDecl GD) const override {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000439 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
440 isa<CXXDestructorDecl>(GD.getDecl()) &&
441 GD.getDtorType() != Dtor_Deleting));
442 }
John McCall5d865c322010-08-31 07:33:07 +0000443
Craig Topper4f12f102014-03-12 06:41:41 +0000444 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
445 QualType ResTy) override;
John McCall5d865c322010-08-31 07:33:07 +0000446
Craig Topper4f12f102014-03-12 06:41:41 +0000447 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
John McCall7f416cc2015-09-08 08:05:57 +0000448 Address InitializeArrayCookie(CodeGenFunction &CGF,
449 Address NewPtr,
450 llvm::Value *NumElements,
451 const CXXNewExpr *expr,
452 QualType ElementType) override;
453 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000454 CharUnits cookieSize) override;
John McCall86353412010-08-21 22:46:04 +0000455};
Tim Northovera2ee4332014-03-29 15:09:45 +0000456
457class iOS64CXXABI : public ARMCXXABI {
458public:
John McCalld23b27e2016-09-16 02:40:45 +0000459 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
460 Use32BitVTableOffsetABI = true;
461 }
Tim Northover65f582f2014-03-30 17:32:48 +0000462
463 // ARM64 libraries are prepared for non-unique RTTI.
David Majnemere2cb8d12014-07-07 06:20:47 +0000464 bool shouldRTTIBeUnique() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +0000465};
Dan Gohmanc2853072015-09-03 22:51:53 +0000466
467class WebAssemblyCXXABI final : public ItaniumCXXABI {
468public:
469 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
470 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
471 /*UseARMGuardVarABI=*/true) {}
Heejin Ahnc6479192018-05-31 22:18:13 +0000472 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000473
474private:
475 bool HasThisReturn(GlobalDecl GD) const override {
476 return isa<CXXConstructorDecl>(GD.getDecl()) ||
477 (isa<CXXDestructorDecl>(GD.getDecl()) &&
478 GD.getDtorType() != Dtor_Deleting);
479 }
Derek Schuff8179be42016-05-10 17:44:55 +0000480 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000481};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000482}
Charles Davis4e786dd2010-05-25 19:52:27 +0000483
Charles Davis53c59df2010-08-16 03:33:14 +0000484CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000485 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000486 // For IR-generation purposes, there's no significant difference
487 // between the ARM and iOS ABIs.
488 case TargetCXXABI::GenericARM:
489 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000490 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000491 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000492
Tim Northovera2ee4332014-03-29 15:09:45 +0000493 case TargetCXXABI::iOS64:
494 return new iOS64CXXABI(CGM);
495
Tim Northover9bb857a2013-01-31 12:13:10 +0000496 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
497 // include the other 32-bit ARM oddities: constructor/destructor return values
498 // and array cookies.
499 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000500 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
501 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000502
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000503 case TargetCXXABI::GenericMIPS:
504 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
505
Dan Gohmanc2853072015-09-03 22:51:53 +0000506 case TargetCXXABI::WebAssembly:
507 return new WebAssemblyCXXABI(CGM);
508
John McCall57625922013-01-25 23:36:14 +0000509 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000510 if (CGM.getContext().getTargetInfo().getTriple().getArch()
511 == llvm::Triple::le32) {
512 // For PNaCl, use ARM-style method pointers so that PNaCl code
513 // does not assume anything about the alignment of function
514 // pointers.
515 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
516 /* UseARMGuardVarABI = */ false);
517 }
John McCall57625922013-01-25 23:36:14 +0000518 return new ItaniumCXXABI(CGM);
519
520 case TargetCXXABI::Microsoft:
521 llvm_unreachable("Microsoft ABI is not Itanium-based");
522 }
523 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000524}
525
Chris Lattnera5f58b02011-07-09 17:41:47 +0000526llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000527ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
528 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000529 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000530 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000531}
532
John McCalld9c6c0b2010-08-22 00:59:17 +0000533/// In the Itanium and ARM ABIs, method pointers have the form:
534/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
535///
536/// In the Itanium ABI:
537/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
538/// - the this-adjustment is (memptr.adj)
539/// - the virtual offset is (memptr.ptr - 1)
540///
541/// In the ARM ABI:
542/// - method pointers are virtual if (memptr.adj & 1) is nonzero
543/// - the this-adjustment is (memptr.adj >> 1)
544/// - the virtual offset is (memptr.ptr)
545/// ARM uses 'adj' for the virtual flag because Thumb functions
546/// may be only single-byte aligned.
547///
548/// If the member is virtual, the adjusted 'this' pointer points
549/// to a vtable pointer from which the virtual offset is applied.
550///
551/// If the member is non-virtual, memptr.ptr is the address of
552/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000553CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000554 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
555 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000556 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000557 CGBuilderTy &Builder = CGF.Builder;
558
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000559 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000560 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000561 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000562 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
563
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000564 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
565 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000566
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000567 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000568
John McCalld9c6c0b2010-08-22 00:59:17 +0000569 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
570 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
571 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
572
John McCalla1dee5302010-08-22 10:59:02 +0000573 // Extract memptr.adj, which is in the second field.
574 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000575
576 // Compute the true adjustment.
577 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000578 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000579 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000580
581 // Apply the adjustment and cast back to the original struct type
582 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000583 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000584 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
585 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
586 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000587 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000588
John McCall475999d2010-08-22 00:05:51 +0000589 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000590 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000591
John McCall475999d2010-08-22 00:05:51 +0000592 // If the LSB in the function pointer is 1, the function pointer points to
593 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000594 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000595 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000596 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
597 else
598 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
599 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000600 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
601
602 // In the virtual path, the adjustment left 'This' pointing to the
603 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000604 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000605 CGF.EmitBlock(FnVirtual);
606
607 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000608 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000609 CharUnits VTablePtrAlign =
610 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
611 CGF.getPointerAlign());
612 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000613 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000614
615 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000616 // On ARM64, to reserve extra space in virtual member function pointers,
617 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000618 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000619 if (!UseARMMethodPtrABI)
620 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000621 if (Use32BitVTableOffsetABI) {
622 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
623 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
624 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000625 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000626
627 // Load the virtual function to call.
628 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000629 llvm::Value *VirtualFn =
630 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
631 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000632 CGF.EmitBranch(FnEnd);
633
634 // In the non-virtual path, the function pointer is actually a
635 // function pointer.
636 CGF.EmitBlock(FnNonVirtual);
637 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000638 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000639
John McCall475999d2010-08-22 00:05:51 +0000640 // We're done.
641 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000642 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
643 CalleePtr->addIncoming(VirtualFn, FnVirtual);
644 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
645
646 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000647 return Callee;
648}
John McCalla8bbb822010-08-22 03:04:22 +0000649
John McCallc134eb52010-08-31 21:07:20 +0000650/// Compute an l-value by applying the given pointer-to-member to a
651/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000652llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000653 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000654 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000655 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000656
657 CGBuilderTy &Builder = CGF.Builder;
658
John McCallc134eb52010-08-31 21:07:20 +0000659 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000660 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000661
662 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000663 llvm::Value *Addr =
664 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000665
666 // Cast the address to the appropriate pointer type, adopting the
667 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000668 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
669 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000670 return Builder.CreateBitCast(Addr, PType);
671}
672
John McCallc62bb392012-02-15 01:22:51 +0000673/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
674/// conversion.
675///
676/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000677///
678/// Obligatory offset/adjustment diagram:
679/// <-- offset --> <-- adjustment -->
680/// |--------------------------|----------------------|--------------------|
681/// ^Derived address point ^Base address point ^Member address point
682///
683/// So when converting a base member pointer to a derived member pointer,
684/// we add the offset to the adjustment because the address point has
685/// decreased; and conversely, when converting a derived MP to a base MP
686/// we subtract the offset from the adjustment because the address point
687/// has increased.
688///
689/// The standard forbids (at compile time) conversion to and from
690/// virtual bases, which is why we don't have to consider them here.
691///
692/// The standard forbids (at run time) casting a derived MP to a base
693/// MP when the derived MP does not point to a member of the base.
694/// This is why -1 is a reasonable choice for null data member
695/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000696llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000697ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
698 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000699 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000700 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000701 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
702 E->getCastKind() == CK_ReinterpretMemberPointer);
703
704 // Under Itanium, reinterprets don't require any additional processing.
705 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
706
707 // Use constant emission if we can.
708 if (isa<llvm::Constant>(src))
709 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
710
711 llvm::Constant *adj = getMemberPointerAdjustment(E);
712 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000713
714 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000715 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000716
John McCallc62bb392012-02-15 01:22:51 +0000717 const MemberPointerType *destTy =
718 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000719
John McCall7a9aac22010-08-23 01:21:21 +0000720 // For member data pointers, this is just a matter of adding the
721 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000722 if (destTy->isMemberDataPointer()) {
723 llvm::Value *dst;
724 if (isDerivedToBase)
725 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000726 else
John McCallc62bb392012-02-15 01:22:51 +0000727 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000728
729 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000730 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
731 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
732 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000733 }
734
John McCalla1dee5302010-08-22 10:59:02 +0000735 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000736 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000737 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
738 offset <<= 1;
739 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000740 }
741
John McCallc62bb392012-02-15 01:22:51 +0000742 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
743 llvm::Value *dstAdj;
744 if (isDerivedToBase)
745 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000746 else
John McCallc62bb392012-02-15 01:22:51 +0000747 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000748
John McCallc62bb392012-02-15 01:22:51 +0000749 return Builder.CreateInsertValue(src, dstAdj, 1);
750}
751
752llvm::Constant *
753ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
754 llvm::Constant *src) {
755 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
756 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
757 E->getCastKind() == CK_ReinterpretMemberPointer);
758
759 // Under Itanium, reinterprets don't require any additional processing.
760 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
761
762 // If the adjustment is trivial, we don't need to do anything.
763 llvm::Constant *adj = getMemberPointerAdjustment(E);
764 if (!adj) return src;
765
766 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
767
768 const MemberPointerType *destTy =
769 E->getType()->castAs<MemberPointerType>();
770
771 // For member data pointers, this is just a matter of adding the
772 // offset if the source is non-null.
773 if (destTy->isMemberDataPointer()) {
774 // null maps to null.
775 if (src->isAllOnesValue()) return src;
776
777 if (isDerivedToBase)
778 return llvm::ConstantExpr::getNSWSub(src, adj);
779 else
780 return llvm::ConstantExpr::getNSWAdd(src, adj);
781 }
782
783 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000784 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000785 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
786 offset <<= 1;
787 adj = llvm::ConstantInt::get(adj->getType(), offset);
788 }
789
790 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
791 llvm::Constant *dstAdj;
792 if (isDerivedToBase)
793 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
794 else
795 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
796
797 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000798}
John McCall84fa5102010-08-22 04:16:24 +0000799
800llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000801ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000802 // Itanium C++ ABI 2.3:
803 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000804 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000805 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000806
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000807 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000808 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000809 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000810}
811
John McCallf3a88602011-02-03 08:15:49 +0000812llvm::Constant *
813ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
814 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000815 // Itanium C++ ABI 2.3:
816 // A pointer to data member is an offset from the base address of
817 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000818 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000819}
820
David Majnemere2be95b2015-06-23 07:31:01 +0000821llvm::Constant *
822ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000823 return BuildMemberPointer(MD, CharUnits::Zero());
824}
825
826llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
827 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000828 assert(MD->isInstance() && "Member function must not be static!");
John McCalla1dee5302010-08-22 10:59:02 +0000829
830 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000831
832 // Get the function pointer (or index if this is a virtual function).
833 llvm::Constant *MemPtr[2];
834 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000835 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000836
Ken Dyckdf016282011-04-09 01:30:02 +0000837 const ASTContext &Context = getContext();
838 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000839 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000840 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000841
Mark Seabornedf0d382013-07-24 16:25:13 +0000842 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000843 // ARM C++ ABI 3.2.1:
844 // This ABI specifies that adj contains twice the this
845 // adjustment, plus 1 if the member function is virtual. The
846 // least significant bit of adj then makes exactly the same
847 // discrimination as the least significant bit of ptr does for
848 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000849 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
850 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000851 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000852 } else {
853 // Itanium C++ ABI 2.3:
854 // For a virtual function, [the pointer field] is 1 plus the
855 // virtual table offset (in bytes) of the function,
856 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000857 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
858 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000859 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000860 }
861 } else {
John McCall2979fe02011-04-12 00:42:48 +0000862 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000863 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000864 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000865 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000866 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000867 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000868 } else {
John McCall2979fe02011-04-12 00:42:48 +0000869 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
870 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000871 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000872 }
John McCall2979fe02011-04-12 00:42:48 +0000873 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000874
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000875 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000876 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
877 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000878 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000879 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000880
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000881 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000882}
883
Richard Smithdafff942012-01-14 04:30:29 +0000884llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
885 QualType MPType) {
886 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
887 const ValueDecl *MPD = MP.getMemberPointerDecl();
888 if (!MPD)
889 return EmitNullMemberPointer(MPT);
890
Reid Kleckner452abac2013-05-09 21:01:17 +0000891 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000892
893 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
894 return BuildMemberPointer(MD, ThisAdjustment);
895
896 CharUnits FieldOffset =
897 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
898 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
899}
900
John McCall131d97d2010-08-22 08:30:07 +0000901/// The comparison algorithm is pretty easy: the member pointers are
902/// the same if they're either bitwise identical *or* both null.
903///
904/// ARM is different here only because null-ness is more complicated.
905llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000906ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
907 llvm::Value *L,
908 llvm::Value *R,
909 const MemberPointerType *MPT,
910 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000911 CGBuilderTy &Builder = CGF.Builder;
912
John McCall131d97d2010-08-22 08:30:07 +0000913 llvm::ICmpInst::Predicate Eq;
914 llvm::Instruction::BinaryOps And, Or;
915 if (Inequality) {
916 Eq = llvm::ICmpInst::ICMP_NE;
917 And = llvm::Instruction::Or;
918 Or = llvm::Instruction::And;
919 } else {
920 Eq = llvm::ICmpInst::ICMP_EQ;
921 And = llvm::Instruction::And;
922 Or = llvm::Instruction::Or;
923 }
924
John McCall7a9aac22010-08-23 01:21:21 +0000925 // Member data pointers are easy because there's a unique null
926 // value, so it just comes down to bitwise equality.
927 if (MPT->isMemberDataPointer())
928 return Builder.CreateICmp(Eq, L, R);
929
930 // For member function pointers, the tautologies are more complex.
931 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000932 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000933 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000934 // (L == R) <==> (L.ptr == R.ptr &&
935 // (L.adj == R.adj ||
936 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000937 // The inequality tautologies have exactly the same structure, except
938 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000939
John McCall7a9aac22010-08-23 01:21:21 +0000940 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
941 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
942
John McCall131d97d2010-08-22 08:30:07 +0000943 // This condition tests whether L.ptr == R.ptr. This must always be
944 // true for equality to hold.
945 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
946
947 // This condition, together with the assumption that L.ptr == R.ptr,
948 // tests whether the pointers are both null. ARM imposes an extra
949 // condition.
950 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
951 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
952
953 // This condition tests whether L.adj == R.adj. If this isn't
954 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000955 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
956 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000957 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
958
959 // Null member function pointers on ARM clear the low bit of Adj,
960 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000961 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000962 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
963
964 // Compute (l.adj | r.adj) & 1 and test it against zero.
965 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
966 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
967 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
968 "cmp.or.adj");
969 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
970 }
971
972 // Tie together all our conditions.
973 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
974 Result = Builder.CreateBinOp(And, PtrEq, Result,
975 Inequality ? "memptr.ne" : "memptr.eq");
976 return Result;
977}
978
979llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000980ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
981 llvm::Value *MemPtr,
982 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000983 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000984
985 /// For member data pointers, this is just a check against -1.
986 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000987 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000988 llvm::Value *NegativeOne =
989 llvm::Constant::getAllOnesValue(MemPtr->getType());
990 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
991 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000992
Daniel Dunbar914bc412011-04-19 23:10:47 +0000993 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000994 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000995
996 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
997 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
998
Daniel Dunbar914bc412011-04-19 23:10:47 +0000999 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1000 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001001 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001002 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001003 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001004 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001005 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1006 "memptr.isvirtual");
1007 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001008 }
1009
1010 return Result;
1011}
John McCall1c456c82010-08-22 06:43:33 +00001012
Reid Kleckner40ca9132014-05-13 22:05:45 +00001013bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1014 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1015 if (!RD)
1016 return false;
1017
Richard Smith96cd6712017-08-16 01:49:53 +00001018 // If C++ prohibits us from making a copy, return by address.
Richard Smithf667ad52017-08-26 01:04:35 +00001019 if (passClassIndirect(RD)) {
John McCall7f416cc2015-09-08 08:05:57 +00001020 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1021 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001022 return true;
1023 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001024 return false;
1025}
1026
John McCall614dbdc2010-08-22 21:01:12 +00001027/// The Itanium ABI requires non-zero initialization only for data
1028/// member pointers, for which '0' is a valid offset.
1029bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001030 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001031}
John McCall5d865c322010-08-31 07:33:07 +00001032
John McCall82fb8922012-09-25 10:10:39 +00001033/// The Itanium ABI always places an offset to the complete object
1034/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001035void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1036 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001037 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001038 QualType ElementType,
1039 const CXXDestructorDecl *Dtor) {
1040 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001041 if (UseGlobalDelete) {
1042 // Derive the complete-object pointer, which is what we need
1043 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001044
David Majnemer0c0b6d92014-10-31 20:09:12 +00001045 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001046 auto *ClassDecl =
1047 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1048 llvm::Value *VTable =
1049 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001050
David Majnemer0c0b6d92014-10-31 20:09:12 +00001051 // Track back to entry -2 and pull out the offset there.
1052 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1053 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001054 llvm::Value *Offset =
1055 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001056
1057 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001058 llvm::Value *CompletePtr =
1059 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001060 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1061
1062 // If we're supposed to call the global delete, make sure we do so
1063 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001064 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1065 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001066 }
1067
1068 // FIXME: Provide a source location here even though there's no
1069 // CXXMemberCallExpr for dtor call.
1070 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1071 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1072
1073 if (UseGlobalDelete)
1074 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001075}
1076
David Majnemer442d0a22014-11-25 07:20:20 +00001077void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1078 // void __cxa_rethrow();
1079
1080 llvm::FunctionType *FTy =
1081 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1082
1083 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1084
1085 if (isNoReturn)
1086 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1087 else
1088 CGF.EmitRuntimeCallOrInvoke(Fn);
1089}
1090
David Majnemer7c237072015-03-05 00:46:22 +00001091static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1092 // void *__cxa_allocate_exception(size_t thrown_size);
1093
1094 llvm::FunctionType *FTy =
1095 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1096
1097 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1098}
1099
1100static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1101 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1102 // void (*dest) (void *));
1103
1104 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1105 llvm::FunctionType *FTy =
1106 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1107
1108 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1109}
1110
1111void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1112 QualType ThrowType = E->getSubExpr()->getType();
1113 // Now allocate the exception object.
1114 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1115 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1116
1117 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1118 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1119 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1120
John McCall7f416cc2015-09-08 08:05:57 +00001121 CharUnits ExnAlign = getAlignmentOfExnObject();
1122 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001123
1124 // Now throw the exception.
1125 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1126 /*ForEH=*/true);
1127
1128 // The address of the destructor. If the exception type has a
1129 // trivial destructor (or isn't a record), we just pass null.
1130 llvm::Constant *Dtor = nullptr;
1131 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1132 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1133 if (!Record->hasTrivialDestructor()) {
1134 CXXDestructorDecl *DtorD = Record->getDestructor();
1135 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1136 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1137 }
1138 }
1139 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1140
1141 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1142 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1143}
1144
David Majnemer1162d252014-06-22 19:05:33 +00001145static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1146 // void *__dynamic_cast(const void *sub,
1147 // const abi::__class_type_info *src,
1148 // const abi::__class_type_info *dst,
1149 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001150
David Majnemer1162d252014-06-22 19:05:33 +00001151 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001152 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001153 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1154
1155 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1156
1157 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1158
1159 // Mark the function as nounwind readonly.
1160 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1161 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001162 llvm::AttributeList Attrs = llvm::AttributeList::get(
1163 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001164
1165 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1166}
1167
1168static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1169 // void __cxa_bad_cast();
1170 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1171 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1172}
1173
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001174/// Compute the src2dst_offset hint as described in the
David Majnemer1162d252014-06-22 19:05:33 +00001175/// Itanium C++ ABI [2.9.7]
1176static CharUnits computeOffsetHint(ASTContext &Context,
1177 const CXXRecordDecl *Src,
1178 const CXXRecordDecl *Dst) {
1179 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1180 /*DetectVirtual=*/false);
1181
1182 // If Dst is not derived from Src we can skip the whole computation below and
1183 // return that Src is not a public base of Dst. Record all inheritance paths.
1184 if (!Dst->isDerivedFrom(Src, Paths))
1185 return CharUnits::fromQuantity(-2ULL);
1186
1187 unsigned NumPublicPaths = 0;
1188 CharUnits Offset;
1189
1190 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001191 for (const CXXBasePath &Path : Paths) {
1192 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001193 continue;
1194
1195 ++NumPublicPaths;
1196
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001197 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001198 // If the path contains a virtual base class we can't give any hint.
1199 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001200 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001201 return CharUnits::fromQuantity(-1ULL);
1202
1203 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1204 continue;
1205
1206 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001207 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1208 Offset += L.getBaseClassOffset(
1209 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001210 }
1211 }
1212
1213 // -2: Src is not a public base of Dst.
1214 if (NumPublicPaths == 0)
1215 return CharUnits::fromQuantity(-2ULL);
1216
1217 // -3: Src is a multiple public base type but never a virtual base type.
1218 if (NumPublicPaths > 1)
1219 return CharUnits::fromQuantity(-3ULL);
1220
1221 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1222 // Return the offset of Src from the origin of Dst.
1223 return Offset;
1224}
1225
1226static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1227 // void __cxa_bad_typeid();
1228 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1229
1230 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1231}
1232
1233bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1234 QualType SrcRecordTy) {
1235 return IsDeref;
1236}
1237
1238void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1239 llvm::Value *Fn = getBadTypeidFn(CGF);
1240 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1241 CGF.Builder.CreateUnreachable();
1242}
1243
1244llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1245 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001246 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001247 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001248 auto *ClassDecl =
1249 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001250 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001251 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001252
1253 // Load the type info.
1254 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001255 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001256}
1257
1258bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1259 QualType SrcRecordTy) {
1260 return SrcIsPtr;
1261}
1262
1263llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001264 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001265 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1266 llvm::Type *PtrDiffLTy =
1267 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1268 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1269
1270 llvm::Value *SrcRTTI =
1271 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1272 llvm::Value *DestRTTI =
1273 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1274
1275 // Compute the offset hint.
1276 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1277 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1278 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1279 PtrDiffLTy,
1280 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1281
1282 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001283 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001284 Value = CGF.EmitCastToVoidPtr(Value);
1285
1286 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1287 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1288 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1289
1290 /// C++ [expr.dynamic.cast]p9:
1291 /// A failed cast to reference type throws std::bad_cast
1292 if (DestTy->isReferenceType()) {
1293 llvm::BasicBlock *BadCastBlock =
1294 CGF.createBasicBlock("dynamic_cast.bad_cast");
1295
1296 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1297 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1298
1299 CGF.EmitBlock(BadCastBlock);
1300 EmitBadCastCall(CGF);
1301 }
1302
1303 return Value;
1304}
1305
1306llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001307 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001308 QualType SrcRecordTy,
1309 QualType DestTy) {
1310 llvm::Type *PtrDiffLTy =
1311 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1312 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1313
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001314 auto *ClassDecl =
1315 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001316 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001317 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1318 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001319
1320 // Get the offset-to-top from the vtable.
1321 llvm::Value *OffsetToTop =
1322 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001323 OffsetToTop =
1324 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1325 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001326
1327 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001328 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001329 Value = CGF.EmitCastToVoidPtr(Value);
1330 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1331
1332 return CGF.Builder.CreateBitCast(Value, DestLTy);
1333}
1334
1335bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1336 llvm::Value *Fn = getBadCastFn(CGF);
1337 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1338 CGF.Builder.CreateUnreachable();
1339 return true;
1340}
1341
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001342llvm::Value *
1343ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001344 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001345 const CXXRecordDecl *ClassDecl,
1346 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001347 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001348 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001349 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1350 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001351
1352 llvm::Value *VBaseOffsetPtr =
1353 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1354 "vbase.offset.ptr");
1355 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1356 CGM.PtrDiffTy->getPointerTo());
1357
1358 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001359 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1360 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001361
1362 return VBaseOffset;
1363}
1364
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001365void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1366 // Just make sure we're in sync with TargetCXXABI.
1367 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1368
Rafael Espindolac3cde362013-12-09 14:51:17 +00001369 // The constructor used for constructing this as a base class;
1370 // ignores virtual bases.
1371 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1372
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001373 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001374 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001375 if (!D->getParent()->isAbstract()) {
1376 // We don't need to emit the complete ctor if the class is abstract.
1377 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1378 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001379}
1380
George Burgess IVf203dbf2017-02-22 20:28:02 +00001381CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001382ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1383 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001384 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001385
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001386 // All parameters are already in place except VTT, which goes after 'this'.
1387 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001388
1389 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001390 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001391 ArgTys.insert(ArgTys.begin() + 1,
1392 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001393 return AddedStructorArgs::prefix(1);
1394 }
1395 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001396}
1397
Reid Klecknere7de47e2013-07-22 13:51:44 +00001398void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001399 // The destructor used for destructing this as a base class; ignores
1400 // virtual bases.
1401 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001402
1403 // The destructor used for destructing this as a most-derived class;
1404 // call the base destructor and then destructs any virtual bases.
1405 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1406
Rafael Espindolac3cde362013-12-09 14:51:17 +00001407 // The destructor in a virtual table is always a 'deleting'
1408 // destructor, which calls the complete destructor and then uses the
1409 // appropriate operator delete.
1410 if (D->isVirtual())
1411 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001412}
1413
Reid Kleckner89077a12013-12-17 19:46:40 +00001414void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1415 QualType &ResTy,
1416 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001417 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001418 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001419
1420 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001421 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001422 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001423
1424 // FIXME: avoid the fake decl
1425 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001426 auto *VTTDecl = ImplicitParamDecl::Create(
1427 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1428 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001429 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001430 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001431 }
1432}
1433
John McCall5d865c322010-08-31 07:33:07 +00001434void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001435 // Naked functions have no prolog.
1436 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1437 return;
1438
Reid Kleckner06239e42017-11-16 19:09:36 +00001439 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001440 /// adjustments are required, because they are all handled by thunks.
Reid Kleckner06239e42017-11-16 19:09:36 +00001441 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001442
1443 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001444 if (getStructorImplicitParamDecl(CGF)) {
1445 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1446 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001447 }
John McCall5d865c322010-08-31 07:33:07 +00001448
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001449 /// If this is a function that the ABI specifies returns 'this', initialize
1450 /// the return slot to 'this' at the start of the function.
1451 ///
1452 /// Unlike the setting of return types, this is done within the ABI
1453 /// implementation instead of by clients of CGCXXABI because:
1454 /// 1) getThisValue is currently protected
1455 /// 2) in theory, an ABI could implement 'this' returns some other way;
1456 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001457 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001458 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001459}
1460
George Burgess IVf203dbf2017-02-22 20:28:02 +00001461CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001462 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1463 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1464 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001465 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001466
Reid Kleckner89077a12013-12-17 19:46:40 +00001467 // Insert the implicit 'vtt' argument as the second argument.
1468 llvm::Value *VTT =
1469 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1470 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
Yaxun Liu5b330e82018-03-15 15:25:19 +00001471 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001472 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001473}
1474
1475void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1476 const CXXDestructorDecl *DD,
1477 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001478 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001479 GlobalDecl GD(DD, Type);
1480 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1481 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1482
John McCallb92ab1a2016-10-26 23:46:34 +00001483 CGCallee Callee;
1484 if (getContext().getLangOpts().AppleKext &&
1485 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001486 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001487 else
1488 Callee =
1489 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1490 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001491
John McCall7f416cc2015-09-08 08:05:57 +00001492 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001493 This.getPointer(), VTT, VTTTy,
1494 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001495}
1496
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001497void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1498 const CXXRecordDecl *RD) {
1499 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1500 if (VTable->hasInitializer())
1501 return;
1502
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001503 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001504 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1505 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001506 llvm::Constant *RTTI =
1507 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001508
1509 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001510 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001511 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001512 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1513 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001514
1515 // Set the correct linkage.
1516 VTable->setLinkage(Linkage);
1517
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001518 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1519 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001520
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001521 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001522 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001523
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001524 // Use pointer alignment for the vtable. Otherwise we would align them based
1525 // on the size of the initializer which doesn't make sense as only single
1526 // values are read.
1527 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1528 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1529
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001530 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1531 // we will emit the typeinfo for the fundamental types. This is the
1532 // same behaviour as GCC.
1533 const DeclContext *DC = RD->getDeclContext();
1534 if (RD->getIdentifier() &&
1535 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1536 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1537 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1538 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001539 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001540
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001541 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001542 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001543}
1544
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001545bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1546 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1547 if (Vptr.NearestVBase == nullptr)
1548 return false;
1549 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001550}
1551
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001552llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1553 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1554 const CXXRecordDecl *NearestVBase) {
1555
1556 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1557 NeedsVTTParameter(CGF.CurGD)) {
1558 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1559 NearestVBase);
1560 }
1561 return getVTableAddressPoint(Base, VTableClass);
1562}
1563
1564llvm::Constant *
1565ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1566 const CXXRecordDecl *VTableClass) {
1567 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001568
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001569 // Find the appropriate vtable within the vtable group, and the address point
1570 // within that vtable.
1571 VTableLayout::AddressPointLocation AddressPoint =
1572 CGM.getItaniumVTableContext()
1573 .getVTableLayout(VTableClass)
1574 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001575 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001576 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001577 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1578 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001579 };
1580
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001581 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1582 Indices, /*InBounds=*/true,
1583 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001584}
1585
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001586llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1587 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1588 const CXXRecordDecl *NearestVBase) {
1589 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1590 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1591
1592 // Get the secondary vpointer index.
1593 uint64_t VirtualPointerIndex =
1594 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1595
1596 /// Load the VTT.
1597 llvm::Value *VTT = CGF.LoadCXXVTT();
1598 if (VirtualPointerIndex)
1599 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1600
1601 // And load the address point from the VTT.
1602 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1603}
1604
1605llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1606 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1607 return getVTableAddressPoint(Base, VTableClass);
1608}
1609
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001610llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1611 CharUnits VPtrOffset) {
1612 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1613
1614 llvm::GlobalVariable *&VTable = VTables[RD];
1615 if (VTable)
1616 return VTable;
1617
Eric Christopherd160c502016-01-29 01:35:53 +00001618 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001619 CGM.addDeferredVTable(RD);
1620
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001621 SmallString<256> Name;
1622 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001623 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001624
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001625 const VTableLayout &VTLayout =
1626 CGM.getItaniumVTableContext().getVTableLayout(RD);
1627 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001628
1629 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001630 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001631 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001632
Rafael Espindola922f2aa2018-02-23 19:30:48 +00001633 CGM.setGVProperties(VTable, RD);
1634
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001635 return VTable;
1636}
1637
John McCall9831b842018-02-06 18:52:44 +00001638CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1639 GlobalDecl GD,
1640 Address This,
1641 llvm::Type *Ty,
1642 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001643 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001644 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1645 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001646
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001647 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001648 llvm::Value *VFunc;
1649 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1650 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001651 MethodDecl->getParent(), VTable,
1652 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001653 } else {
1654 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001655
John McCall9831b842018-02-06 18:52:44 +00001656 llvm::Value *VFuncPtr =
1657 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1658 auto *VFuncLoad =
1659 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001660
John McCall9831b842018-02-06 18:52:44 +00001661 // Add !invariant.load md to virtual function load to indicate that
1662 // function didn't change inside vtable.
1663 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1664 // help in devirtualization because it will only matter if we will have 2
1665 // the same virtual function loads from the same vtable load, which won't
1666 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1667 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1668 CGM.getCodeGenOpts().StrictVTablePointers)
1669 VFuncLoad->setMetadata(
1670 llvm::LLVMContext::MD_invariant_load,
1671 llvm::MDNode::get(CGM.getLLVMContext(),
1672 llvm::ArrayRef<llvm::Metadata *>()));
1673 VFunc = VFuncLoad;
1674 }
John McCallb92ab1a2016-10-26 23:46:34 +00001675
Reid Kleckner138ab492018-05-17 18:12:18 +00001676 CGCallee Callee(MethodDecl->getCanonicalDecl(), VFunc);
John McCall9831b842018-02-06 18:52:44 +00001677 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001678}
1679
David Majnemer0c0b6d92014-10-31 20:09:12 +00001680llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1681 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001682 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001683 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001684 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1685
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001686 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1687 Dtor, getFromDtorType(DtorType));
George Burgess IV00f70bd2018-03-01 05:43:23 +00001688 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001689 CGCallee Callee =
Peter Collingbourneea211002018-02-05 23:09:13 +00001690 CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001691
John McCall7f416cc2015-09-08 08:05:57 +00001692 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1693 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001694 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001695 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001696}
1697
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001698void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001699 CodeGenVTables &VTables = CGM.getVTables();
1700 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001701 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001702}
1703
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001704bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001705 // We don't emit available_externally vtables if we are in -fapple-kext mode
1706 // because kext mode does not permit devirtualization.
1707 if (CGM.getLangOpts().AppleKext)
1708 return false;
1709
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001710 // If we don't have any not emitted inline virtual function, and if vtable is
1711 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001712 // FIXME we can still emit a copy of the vtable if we
1713 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001714 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001715}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001716static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001717 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001718 int64_t NonVirtualAdjustment,
1719 int64_t VirtualAdjustment,
1720 bool IsReturnAdjustment) {
1721 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001722 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001723
John McCall7f416cc2015-09-08 08:05:57 +00001724 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001725
John McCall7f416cc2015-09-08 08:05:57 +00001726 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001727 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001728 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1729 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001730 }
1731
John McCall7f416cc2015-09-08 08:05:57 +00001732 // Perform the virtual adjustment if we have one.
1733 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001734 if (VirtualAdjustment) {
1735 llvm::Type *PtrDiffTy =
1736 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1737
John McCall7f416cc2015-09-08 08:05:57 +00001738 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001739 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1740
1741 llvm::Value *OffsetPtr =
1742 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1743
1744 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1745
1746 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001747 llvm::Value *Offset =
1748 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001749
1750 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001751 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1752 } else {
1753 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001754 }
1755
John McCall7f416cc2015-09-08 08:05:57 +00001756 // In a derived-to-base conversion, the non-virtual adjustment is
1757 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001758 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001759 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1760 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001761 }
1762
1763 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001764 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001765}
1766
1767llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001768 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001769 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001770 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1771 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001772 /*IsReturnAdjustment=*/false);
1773}
1774
1775llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001776ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001777 const ReturnAdjustment &RA) {
1778 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1779 RA.Virtual.Itanium.VBaseOffsetOffset,
1780 /*IsReturnAdjustment=*/true);
1781}
1782
John McCall5d865c322010-08-31 07:33:07 +00001783void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1784 RValue RV, QualType ResultType) {
1785 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1786 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1787
1788 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001789 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001790 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1791 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1792}
John McCall8ed55a52010-09-02 09:58:18 +00001793
1794/************************** Array allocation cookies **************************/
1795
John McCallb91cd662012-05-01 05:23:51 +00001796CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1797 // The array cookie is a size_t; pad that up to the element alignment.
1798 // The cookie is actually right-justified in that space.
1799 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1800 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001801}
1802
John McCall7f416cc2015-09-08 08:05:57 +00001803Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1804 Address NewPtr,
1805 llvm::Value *NumElements,
1806 const CXXNewExpr *expr,
1807 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001808 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001809
John McCall7f416cc2015-09-08 08:05:57 +00001810 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001811
John McCall9bca9232010-09-02 10:25:57 +00001812 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001813 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001814
1815 // The size of the cookie.
1816 CharUnits CookieSize =
1817 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001818 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001819
1820 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001821 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001822 CharUnits CookieOffset = CookieSize - SizeSize;
1823 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001824 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001825
1826 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001827 Address NumElementsPtr =
1828 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001829 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001830
1831 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001832 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001833 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
1834 CGM.getCodeGenOpts().SanitizeAddressPoisonClassMemberArrayNewCookie)) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001835 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001836 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1837 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001838 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001839 llvm::Constant *F =
1840 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001841 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001842 }
John McCall8ed55a52010-09-02 09:58:18 +00001843
1844 // Finally, compute a pointer to the actual data buffer by skipping
1845 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001846 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001847}
1848
John McCallb91cd662012-05-01 05:23:51 +00001849llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001850 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001851 CharUnits cookieSize) {
1852 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001853 Address numElementsPtr = allocPtr;
1854 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001855 if (!numElementsOffset.isZero())
1856 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001857 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001858
John McCall7f416cc2015-09-08 08:05:57 +00001859 unsigned AS = allocPtr.getAddressSpace();
1860 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001861 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001862 return CGF.Builder.CreateLoad(numElementsPtr);
1863 // In asan mode emit a function call instead of a regular load and let the
1864 // run-time deal with it: if the shadow is properly poisoned return the
1865 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1866 // We can't simply ignore this load using nosanitize metadata because
1867 // the metadata may be lost.
1868 llvm::FunctionType *FTy =
1869 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1870 llvm::Constant *F =
1871 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001872 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001873}
1874
John McCallb91cd662012-05-01 05:23:51 +00001875CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001876 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001877 // struct array_cookie {
1878 // std::size_t element_size; // element_size != 0
1879 // std::size_t element_count;
1880 // };
John McCallc19c7062013-01-25 23:36:19 +00001881 // But the base ABI doesn't give anything an alignment greater than
1882 // 8, so we can dismiss this as typical ABI-author blindness to
1883 // actual language complexity and round up to the element alignment.
1884 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1885 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001886}
1887
John McCall7f416cc2015-09-08 08:05:57 +00001888Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1889 Address newPtr,
1890 llvm::Value *numElements,
1891 const CXXNewExpr *expr,
1892 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001893 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001894
John McCall8ed55a52010-09-02 09:58:18 +00001895 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001896 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001897
1898 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001899 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001900 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1901 getContext().getTypeSizeInChars(elementType).getQuantity());
1902 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001903
1904 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001905 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001906 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001907
1908 // Finally, compute a pointer to the actual data buffer by skipping
1909 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001910 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001911 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001912}
1913
John McCallb91cd662012-05-01 05:23:51 +00001914llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001915 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001916 CharUnits cookieSize) {
1917 // The number of elements is at offset sizeof(size_t) relative to
1918 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001919 Address numElementsPtr
1920 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001921
John McCall7f416cc2015-09-08 08:05:57 +00001922 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001923 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001924}
1925
John McCall68ff0372010-09-08 01:44:27 +00001926/*********************** Static local initialization **************************/
1927
1928static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001929 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001930 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001931 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001932 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001933 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001934 return CGM.CreateRuntimeFunction(
1935 FTy, "__cxa_guard_acquire",
1936 llvm::AttributeList::get(CGM.getLLVMContext(),
1937 llvm::AttributeList::FunctionIndex,
1938 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001939}
1940
1941static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001942 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001943 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001944 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001945 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001946 return CGM.CreateRuntimeFunction(
1947 FTy, "__cxa_guard_release",
1948 llvm::AttributeList::get(CGM.getLLVMContext(),
1949 llvm::AttributeList::FunctionIndex,
1950 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001951}
1952
1953static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001954 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001955 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001956 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001957 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001958 return CGM.CreateRuntimeFunction(
1959 FTy, "__cxa_guard_abort",
1960 llvm::AttributeList::get(CGM.getLLVMContext(),
1961 llvm::AttributeList::FunctionIndex,
1962 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001963}
1964
1965namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001966 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001967 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001968 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001969
Craig Topper4f12f102014-03-12 06:41:41 +00001970 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001971 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1972 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001973 }
1974 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001975}
John McCall68ff0372010-09-08 01:44:27 +00001976
1977/// The ARM code here follows the Itanium code closely enough that we
1978/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001979void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1980 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001981 llvm::GlobalVariable *var,
1982 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001983 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001984
Richard Smith62f19e72016-06-25 00:15:56 +00001985 // Inline variables that weren't instantiated from variable templates have
1986 // partially-ordered initialization within their translation unit.
1987 bool NonTemplateInline =
1988 D.isInline() &&
1989 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1990
1991 // We only need to use thread-safe statics for local non-TLS variables and
1992 // inline variables; other global initialization is always single-threaded
1993 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001994 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001995 (D.isLocalVarDecl() || NonTemplateInline) &&
1996 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001997
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001998 // If we have a global variable with internal linkage and thread-safe statics
1999 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00002000 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2001
2002 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002003 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002004 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002005 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002006 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002007 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002008 // Guard variables are 64 bits in the generic ABI and size width on ARM
2009 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002010 if (UseARMGuardVarABI) {
2011 guardTy = CGF.SizeTy;
2012 guardAlignment = CGF.getSizeAlign();
2013 } else {
2014 guardTy = CGF.Int64Ty;
2015 guardAlignment = CharUnits::fromQuantity(
2016 CGM.getDataLayout().getABITypeAlignment(guardTy));
2017 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002018 }
John McCallb88a5662012-03-30 21:00:39 +00002019 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002020
John McCallb88a5662012-03-30 21:00:39 +00002021 // Create the guard variable if we don't already have it (as we
2022 // might if we're double-emitting this function body).
2023 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2024 if (!guard) {
2025 // Mangle the name for the guard.
2026 SmallString<256> guardName;
2027 {
2028 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002029 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002030 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002031
John McCallb88a5662012-03-30 21:00:39 +00002032 // Create the guard variable with a zero-initializer.
2033 // Just absorb linkage and visibility from the guarded variable.
2034 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2035 false, var->getLinkage(),
2036 llvm::ConstantInt::get(guardTy, 0),
2037 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002038 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002039 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002040 // If the variable is thread-local, so is its guard variable.
2041 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002042 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002043
Yaron Keren5bfa1082015-09-03 20:33:29 +00002044 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2045 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002046 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002047 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002048 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002049 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2050 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002051 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002052 // An inline variable's guard function is run from the per-TU
2053 // initialization function, not via a dedicated global ctor function, so
2054 // we can't put it in a comdat.
2055 if (!NonTemplateInline)
2056 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002057 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2058 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002059 }
2060
John McCallb88a5662012-03-30 21:00:39 +00002061 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2062 }
John McCall87590e62012-03-30 07:09:50 +00002063
John McCall7f416cc2015-09-08 08:05:57 +00002064 Address guardAddr = Address(guard, guardAlignment);
2065
John McCall68ff0372010-09-08 01:44:27 +00002066 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002067 //
John McCall68ff0372010-09-08 01:44:27 +00002068 // Itanium C++ ABI 3.3.2:
2069 // The following is pseudo-code showing how these functions can be used:
2070 // if (obj_guard.first_byte == 0) {
2071 // if ( __cxa_guard_acquire (&obj_guard) ) {
2072 // try {
2073 // ... initialize the object ...;
2074 // } catch (...) {
2075 // __cxa_guard_abort (&obj_guard);
2076 // throw;
2077 // }
2078 // ... queue object destructor with __cxa_atexit() ...;
2079 // __cxa_guard_release (&obj_guard);
2080 // }
2081 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002082
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002083 // Load the first byte of the guard variable.
2084 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002085 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002086
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002087 // Itanium ABI:
2088 // An implementation supporting thread-safety on multiprocessor
2089 // systems must also guarantee that references to the initialized
2090 // object do not occur before the load of the initialization flag.
2091 //
2092 // In LLVM, we do this by marking the load Acquire.
2093 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002094 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002095
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002096 // For ARM, we should only check the first bit, rather than the entire byte:
2097 //
2098 // ARM C++ ABI 3.2.3.1:
2099 // To support the potential use of initialization guard variables
2100 // as semaphores that are the target of ARM SWP and LDREX/STREX
2101 // synchronizing instructions we define a static initialization
2102 // guard variable to be a 4-byte aligned, 4-byte word with the
2103 // following inline access protocol.
2104 // #define INITIALIZED 1
2105 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2106 // if (__cxa_guard_acquire(&obj_guard))
2107 // ...
2108 // }
2109 //
2110 // and similarly for ARM64:
2111 //
2112 // ARM64 C++ ABI 3.2.2:
2113 // This ABI instead only specifies the value bit 0 of the static guard
2114 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2115 // variable is not initialized and 1 when it is.
2116 llvm::Value *V =
2117 (UseARMGuardVarABI && !useInt8GuardVariable)
2118 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2119 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002120 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002121
2122 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2123 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2124
2125 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002126 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2127 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002128
2129 CGF.EmitBlock(InitCheckBlock);
2130
2131 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002132 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002133 // Call __cxa_guard_acquire.
2134 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002135 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002136
John McCall68ff0372010-09-08 01:44:27 +00002137 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002138
John McCall68ff0372010-09-08 01:44:27 +00002139 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2140 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002141
John McCall68ff0372010-09-08 01:44:27 +00002142 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002143 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002144
John McCall68ff0372010-09-08 01:44:27 +00002145 CGF.EmitBlock(InitBlock);
2146 }
2147
2148 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002149 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002150
John McCall5aa52592011-06-17 07:33:57 +00002151 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002152 // Pop the guard-abort cleanup if we pushed one.
2153 CGF.PopCleanupBlock();
2154
2155 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002156 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2157 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002158 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002159 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002160 }
2161
2162 CGF.EmitBlock(EndBlock);
2163}
John McCallc84ed6a2012-05-01 06:13:13 +00002164
2165/// Register a global destructor using __cxa_atexit.
2166static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2167 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002168 llvm::Constant *addr,
2169 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002170 const char *Name = "__cxa_atexit";
2171 if (TLS) {
2172 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002173 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002174 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002175
John McCallc84ed6a2012-05-01 06:13:13 +00002176 // We're assuming that the destructor function is something we can
2177 // reasonably call with the default CC. Go ahead and cast it to the
2178 // right prototype.
2179 llvm::Type *dtorTy =
2180 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2181
2182 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2183 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2184 llvm::FunctionType *atexitTy =
2185 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2186
2187 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002188 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002189 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2190 fn->setDoesNotThrow();
2191
2192 // Create a variable that binds the atexit to this shared object.
2193 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002194 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2195 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2196 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002197
Akira Hatanaka617e2612018-04-17 18:41:52 +00002198 if (!addr)
2199 // addr is null when we are trying to register a dtor annotated with
2200 // __attribute__((destructor)) in a constructor function. Using null here is
2201 // okay because this argument is just passed back to the destructor
2202 // function.
2203 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2204
John McCallc84ed6a2012-05-01 06:13:13 +00002205 llvm::Value *args[] = {
2206 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2207 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2208 handle
2209 };
John McCall882987f2013-02-28 19:01:20 +00002210 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002211}
2212
Akira Hatanaka617e2612018-04-17 18:41:52 +00002213void CodeGenModule::registerGlobalDtorsWithAtExit() {
2214 for (const auto I : DtorsUsingAtExit) {
2215 int Priority = I.first;
2216 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2217
2218 // Create a function that registers destructors that have the same priority.
2219 //
2220 // Since constructor functions are run in non-descending order of their
2221 // priorities, destructors are registered in non-descending order of their
2222 // priorities, and since destructor functions are run in the reverse order
2223 // of their registration, destructor functions are run in non-ascending
2224 // order of their priorities.
2225 CodeGenFunction CGF(*this);
2226 std::string GlobalInitFnName =
2227 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2228 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2229 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2230 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2231 SourceLocation());
2232 ASTContext &Ctx = getContext();
2233 FunctionDecl *FD = FunctionDecl::Create(
2234 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
2235 &Ctx.Idents.get(GlobalInitFnName), Ctx.VoidTy, nullptr, SC_Static,
2236 false, false);
2237 CGF.StartFunction(GlobalDecl(FD), getContext().VoidTy, GlobalInitFn,
2238 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2239 SourceLocation(), SourceLocation());
2240
2241 for (auto *Dtor : Dtors) {
2242 // Register the destructor function calling __cxa_atexit if it is
2243 // available. Otherwise fall back on calling atexit.
2244 if (getCodeGenOpts().CXAAtExit)
2245 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2246 else
2247 CGF.registerGlobalDtorWithAtExit(Dtor);
2248 }
2249
2250 CGF.FinishFunction();
2251 AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2252 }
2253}
2254
John McCallc84ed6a2012-05-01 06:13:13 +00002255/// Register a global destructor as best as we know how.
2256void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002257 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002258 llvm::Constant *dtor,
2259 llvm::Constant *addr) {
2260 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002261 if (CGM.getCodeGenOpts().CXAAtExit)
2262 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2263
2264 if (D.getTLSKind())
2265 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002266
2267 // In Apple kexts, we want to add a global destructor entry.
2268 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002269 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002270 // Generate a global destructor entry.
2271 return CGM.AddCXXDtorEntry(dtor, addr);
2272 }
2273
David Blaikieebe87e12013-08-27 23:57:18 +00002274 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002275}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002276
David Majnemer9b21c332014-07-11 20:28:10 +00002277static bool isThreadWrapperReplaceable(const VarDecl *VD,
2278 CodeGen::CodeGenModule &CGM) {
2279 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002280 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002281 // the thread wrapper instead of directly referencing the backing variable.
2282 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002283 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002284}
2285
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002286/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002287/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002288/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002289static llvm::GlobalValue::LinkageTypes
2290getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2291 llvm::GlobalValue::LinkageTypes VarLinkage =
2292 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2293
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002294 // For internal linkage variables, we don't need an external or weak wrapper.
2295 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2296 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002297
David Majnemer9b21c332014-07-11 20:28:10 +00002298 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002299 if (isThreadWrapperReplaceable(VD, CGM))
2300 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2301 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2302 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002303 return llvm::GlobalValue::WeakODRLinkage;
2304}
2305
2306llvm::Function *
2307ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002308 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002309 // Mangle the name for the thread_local wrapper function.
2310 SmallString<256> WrapperName;
2311 {
2312 llvm::raw_svector_ostream Out(WrapperName);
2313 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002314 }
2315
Akira Hatanaka26907f92016-01-15 03:34:06 +00002316 // FIXME: If VD is a definition, we should regenerate the function attributes
2317 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002318 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002319 return cast<llvm::Function>(V);
2320
Akira Hatanaka26907f92016-01-15 03:34:06 +00002321 QualType RetQT = VD->getType();
2322 if (RetQT->isReferenceType())
2323 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002324
John McCallc56a8b32016-03-11 04:30:31 +00002325 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2326 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002327
2328 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002329 llvm::Function *Wrapper =
2330 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2331 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002332
2333 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2334
2335 if (VD->hasDefinition())
2336 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2337
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002338 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002339 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2340 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2341 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002342 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002343
2344 if (isThreadWrapperReplaceable(VD, CGM)) {
2345 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2346 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2347 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002348 return Wrapper;
2349}
2350
2351void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002352 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2353 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2354 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002355 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002356
2357 // Separate initializers into those with ordered (or partially-ordered)
2358 // initialization and those with unordered initialization.
2359 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2360 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2361 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2362 if (isTemplateInstantiation(
2363 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2364 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2365 CXXThreadLocalInits[I];
2366 else
2367 OrderedInits.push_back(CXXThreadLocalInits[I]);
2368 }
2369
2370 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002371 // Generate a guarded initialization function.
2372 llvm::FunctionType *FTy =
2373 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002374 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2375 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002376 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002377 /*TLS=*/true);
2378 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2379 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2380 llvm::GlobalVariable::InternalLinkage,
2381 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2382 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002383
2384 CharUnits GuardAlign = CharUnits::One();
2385 Guard->setAlignment(GuardAlign.getQuantity());
2386
Richard Smithfbe23692017-01-13 00:43:31 +00002387 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2388 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002389 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2390 if (CGM.getTarget().getTriple().isOSDarwin()) {
2391 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2392 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2393 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002394 }
Richard Smithfbe23692017-01-13 00:43:31 +00002395
2396 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002397 for (const VarDecl *VD : CXXThreadLocals) {
2398 llvm::GlobalVariable *Var =
2399 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002400 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002401
David Majnemer9b21c332014-07-11 20:28:10 +00002402 // Some targets require that all access to thread local variables go through
2403 // the thread wrapper. This means that we cannot attempt to create a thread
2404 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002405 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2406 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002407 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002408 }
David Majnemer9b21c332014-07-11 20:28:10 +00002409
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002410 // Mangle the name for the thread_local initialization function.
2411 SmallString<256> InitFnName;
2412 {
2413 llvm::raw_svector_ostream Out(InitFnName);
2414 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002415 }
2416
2417 // If we have a definition for the variable, emit the initialization
2418 // function as an alias to the global Init function (if any). Otherwise,
2419 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002420 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002421 bool InitIsInitFunc = false;
2422 if (VD->hasDefinition()) {
2423 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002424 llvm::Function *InitFuncToUse = InitFunc;
2425 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2426 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2427 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002428 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002429 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002430 } else {
2431 // Emit a weak global function referring to the initialization function.
2432 // This function will not exist if the TU defining the thread_local
2433 // variable in question does not need any dynamic initialization for
2434 // its thread_local variables.
2435 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002436 Init = llvm::Function::Create(FnTy,
2437 llvm::GlobalVariable::ExternalWeakLinkage,
2438 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002439 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002440 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002441 }
2442
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002443 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002444 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002445 Init->setDSOLocal(Var->isDSOLocal());
2446 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002447
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002448 llvm::LLVMContext &Context = CGM.getModule().getContext();
2449 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002450 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002451 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002452 if (Init) {
2453 llvm::CallInst *CallVal = Builder.CreateCall(Init);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002454 if (isThreadWrapperReplaceable(VD, CGM)) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002455 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002456 llvm::Function *Fn =
2457 cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
2458 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2459 }
Manman Ren5e5d0462016-03-18 23:35:21 +00002460 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002461 } else {
2462 // Don't know whether we have an init function. Call it if it exists.
2463 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2464 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2465 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2466 Builder.CreateCondBr(Have, InitBB, ExitBB);
2467
2468 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002469 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002470 Builder.CreateBr(ExitBB);
2471
2472 Builder.SetInsertPoint(ExitBB);
2473 }
2474
2475 // For a reference, the result of the wrapper function is a pointer to
2476 // the referenced object.
2477 llvm::Value *Val = Var;
2478 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002479 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2480 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002481 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002482 if (Val->getType() != Wrapper->getReturnType())
2483 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2484 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002485 Builder.CreateRet(Val);
2486 }
2487}
2488
Richard Smith0f383742014-03-26 22:48:22 +00002489LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2490 const VarDecl *VD,
2491 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002492 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002493 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002494
Manman Renb0b3af72015-12-17 00:42:36 +00002495 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002496 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002497
2498 LValue LV;
2499 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002500 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002501 else
Manman Renb0b3af72015-12-17 00:42:36 +00002502 LV = CGF.MakeAddrLValue(CallVal, LValType,
2503 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002504 // FIXME: need setObjCGCLValueClass?
2505 return LV;
2506}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002507
2508/// Return whether the given global decl needs a VTT parameter, which it does
2509/// if it's a base constructor or destructor with virtual bases.
2510bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2511 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002512
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002513 // We don't have any virtual bases, just return early.
2514 if (!MD->getParent()->getNumVBases())
2515 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002516
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002517 // Check if we have a base constructor.
2518 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2519 return true;
2520
2521 // Check if we have a base destructor.
2522 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2523 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002524
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002525 return false;
2526}
David Majnemere2cb8d12014-07-07 06:20:47 +00002527
2528namespace {
2529class ItaniumRTTIBuilder {
2530 CodeGenModule &CGM; // Per-module state.
2531 llvm::LLVMContext &VMContext;
2532 const ItaniumCXXABI &CXXABI; // Per-module state.
2533
2534 /// Fields - The fields of the RTTI descriptor currently being built.
2535 SmallVector<llvm::Constant *, 16> Fields;
2536
2537 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2538 llvm::GlobalVariable *
2539 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2540
2541 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2542 /// descriptor of the given type.
2543 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2544
2545 /// BuildVTablePointer - Build the vtable pointer for the given type.
2546 void BuildVTablePointer(const Type *Ty);
2547
2548 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2549 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2550 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2551
2552 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2553 /// classes with bases that do not satisfy the abi::__si_class_type_info
2554 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2555 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2556
2557 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2558 /// for pointer types.
2559 void BuildPointerTypeInfo(QualType PointeeTy);
2560
2561 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2562 /// type_info for an object type.
2563 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2564
2565 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2566 /// struct, used for member pointer types.
2567 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2568
2569public:
2570 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2571 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2572
2573 // Pointer type info flags.
2574 enum {
2575 /// PTI_Const - Type has const qualifier.
2576 PTI_Const = 0x1,
2577
2578 /// PTI_Volatile - Type has volatile qualifier.
2579 PTI_Volatile = 0x2,
2580
2581 /// PTI_Restrict - Type has restrict qualifier.
2582 PTI_Restrict = 0x4,
2583
2584 /// PTI_Incomplete - Type is incomplete.
2585 PTI_Incomplete = 0x8,
2586
2587 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2588 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002589 PTI_ContainingClassIncomplete = 0x10,
2590
2591 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2592 //PTI_TransactionSafe = 0x20,
2593
2594 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2595 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002596 };
2597
2598 // VMI type info flags.
2599 enum {
2600 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2601 VMI_NonDiamondRepeat = 0x1,
2602
2603 /// VMI_DiamondShaped - Class is diamond shaped.
2604 VMI_DiamondShaped = 0x2
2605 };
2606
2607 // Base class type info flags.
2608 enum {
2609 /// BCTI_Virtual - Base class is virtual.
2610 BCTI_Virtual = 0x1,
2611
2612 /// BCTI_Public - Base class is public.
2613 BCTI_Public = 0x2
2614 };
2615
2616 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2617 ///
2618 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002619 /// \param DLLExport - true to mark the RTTI value as DLLExport
2620 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2621 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002622};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002623}
David Majnemere2cb8d12014-07-07 06:20:47 +00002624
2625llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2626 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002627 SmallString<256> Name;
2628 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002629 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002630
2631 // We know that the mangled name of the type starts at index 4 of the
2632 // mangled name of the typename, so we can just index into it in order to
2633 // get the mangled name of the type.
2634 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2635 Name.substr(4));
2636
2637 llvm::GlobalVariable *GV =
2638 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2639
2640 GV->setInitializer(Init);
2641
2642 return GV;
2643}
2644
2645llvm::Constant *
2646ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2647 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002648 SmallString<256> Name;
2649 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002650 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002651
2652 // Look for an existing global.
2653 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2654
2655 if (!GV) {
2656 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002657 // Note for the future: If we would ever like to do deferred emission of
2658 // RTTI, check if emitting vtables opportunistically need any adjustment.
2659
David Majnemere2cb8d12014-07-07 06:20:47 +00002660 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2661 /*Constant=*/true,
2662 llvm::GlobalValue::ExternalLinkage, nullptr,
2663 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002664 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2665 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002666 }
2667
2668 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2669}
2670
2671/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2672/// info for that type is defined in the standard library.
2673static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2674 // Itanium C++ ABI 2.9.2:
2675 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2676 // the run-time support library. Specifically, the run-time support
2677 // library should contain type_info objects for the types X, X* and
2678 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2679 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2680 // long, unsigned long, long long, unsigned long long, float, double,
2681 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2682 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002683 //
2684 // GCC also emits RTTI for __int128.
2685 // FIXME: We do not emit RTTI information for decimal types here.
2686
2687 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002688 switch (Ty->getKind()) {
2689 case BuiltinType::Void:
2690 case BuiltinType::NullPtr:
2691 case BuiltinType::Bool:
2692 case BuiltinType::WChar_S:
2693 case BuiltinType::WChar_U:
2694 case BuiltinType::Char_U:
2695 case BuiltinType::Char_S:
2696 case BuiltinType::UChar:
2697 case BuiltinType::SChar:
2698 case BuiltinType::Short:
2699 case BuiltinType::UShort:
2700 case BuiltinType::Int:
2701 case BuiltinType::UInt:
2702 case BuiltinType::Long:
2703 case BuiltinType::ULong:
2704 case BuiltinType::LongLong:
2705 case BuiltinType::ULongLong:
2706 case BuiltinType::Half:
2707 case BuiltinType::Float:
2708 case BuiltinType::Double:
2709 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002710 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002711 case BuiltinType::Float128:
Richard Smith3a8244d2018-05-01 05:02:45 +00002712 case BuiltinType::Char8:
David Majnemere2cb8d12014-07-07 06:20:47 +00002713 case BuiltinType::Char16:
2714 case BuiltinType::Char32:
2715 case BuiltinType::Int128:
2716 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002717 return true;
2718
Alexey Bader954ba212016-04-08 13:40:33 +00002719#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2720 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002721#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002722 case BuiltinType::OCLSampler:
2723 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002724 case BuiltinType::OCLClkEvent:
2725 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002726 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002727 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002728
2729 case BuiltinType::Dependent:
2730#define BUILTIN_TYPE(Id, SingletonId)
2731#define PLACEHOLDER_TYPE(Id, SingletonId) \
2732 case BuiltinType::Id:
2733#include "clang/AST/BuiltinTypes.def"
2734 llvm_unreachable("asking for RRTI for a placeholder type!");
2735
2736 case BuiltinType::ObjCId:
2737 case BuiltinType::ObjCClass:
2738 case BuiltinType::ObjCSel:
2739 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2740 }
2741
2742 llvm_unreachable("Invalid BuiltinType Kind!");
2743}
2744
2745static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2746 QualType PointeeTy = PointerTy->getPointeeType();
2747 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2748 if (!BuiltinTy)
2749 return false;
2750
2751 // Check the qualifiers.
2752 Qualifiers Quals = PointeeTy.getQualifiers();
2753 Quals.removeConst();
2754
2755 if (!Quals.empty())
2756 return false;
2757
2758 return TypeInfoIsInStandardLibrary(BuiltinTy);
2759}
2760
2761/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2762/// information for the given type exists in the standard library.
2763static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2764 // Type info for builtin types is defined in the standard library.
2765 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2766 return TypeInfoIsInStandardLibrary(BuiltinTy);
2767
2768 // Type info for some pointer types to builtin types is defined in the
2769 // standard library.
2770 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2771 return TypeInfoIsInStandardLibrary(PointerTy);
2772
2773 return false;
2774}
2775
2776/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2777/// the given type exists somewhere else, and that we should not emit the type
2778/// information in this translation unit. Assumes that it is not a
2779/// standard-library type.
2780static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2781 QualType Ty) {
2782 ASTContext &Context = CGM.getContext();
2783
2784 // If RTTI is disabled, assume it might be disabled in the
2785 // translation unit that defines any potential key function, too.
2786 if (!Context.getLangOpts().RTTI) return false;
2787
2788 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2789 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2790 if (!RD->hasDefinition())
2791 return false;
2792
2793 if (!RD->isDynamicClass())
2794 return false;
2795
2796 // FIXME: this may need to be reconsidered if the key function
2797 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002798 // N.B. We must always emit the RTTI data ourselves if there exists a key
2799 // function.
2800 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002801
2802 // Don't import the RTTI but emit it locally.
2803 if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
2804 return false;
2805
David Majnemer1fb1a042014-11-07 07:26:38 +00002806 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002807 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2808 ? false
2809 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002810
David Majnemerbe9022c2015-08-06 20:56:55 +00002811 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002812 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002813 }
2814
2815 return false;
2816}
2817
2818/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2819static bool IsIncompleteClassType(const RecordType *RecordTy) {
2820 return !RecordTy->getDecl()->isCompleteDefinition();
2821}
2822
2823/// ContainsIncompleteClassType - Returns whether the given type contains an
2824/// incomplete class type. This is true if
2825///
2826/// * The given type is an incomplete class type.
2827/// * The given type is a pointer type whose pointee type contains an
2828/// incomplete class type.
2829/// * The given type is a member pointer type whose class is an incomplete
2830/// class type.
2831/// * The given type is a member pointer type whoise pointee type contains an
2832/// incomplete class type.
2833/// is an indirect or direct pointer to an incomplete class type.
2834static bool ContainsIncompleteClassType(QualType Ty) {
2835 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2836 if (IsIncompleteClassType(RecordTy))
2837 return true;
2838 }
2839
2840 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2841 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2842
2843 if (const MemberPointerType *MemberPointerTy =
2844 dyn_cast<MemberPointerType>(Ty)) {
2845 // Check if the class type is incomplete.
2846 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2847 if (IsIncompleteClassType(ClassType))
2848 return true;
2849
2850 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2851 }
2852
2853 return false;
2854}
2855
2856// CanUseSingleInheritance - Return whether the given record decl has a "single,
2857// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2858// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2859static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2860 // Check the number of bases.
2861 if (RD->getNumBases() != 1)
2862 return false;
2863
2864 // Get the base.
2865 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2866
2867 // Check that the base is not virtual.
2868 if (Base->isVirtual())
2869 return false;
2870
2871 // Check that the base is public.
2872 if (Base->getAccessSpecifier() != AS_public)
2873 return false;
2874
2875 // Check that the class is dynamic iff the base is.
2876 const CXXRecordDecl *BaseDecl =
2877 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2878 if (!BaseDecl->isEmpty() &&
2879 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2880 return false;
2881
2882 return true;
2883}
2884
2885void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2886 // abi::__class_type_info.
2887 static const char * const ClassTypeInfo =
2888 "_ZTVN10__cxxabiv117__class_type_infoE";
2889 // abi::__si_class_type_info.
2890 static const char * const SIClassTypeInfo =
2891 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2892 // abi::__vmi_class_type_info.
2893 static const char * const VMIClassTypeInfo =
2894 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2895
2896 const char *VTableName = nullptr;
2897
2898 switch (Ty->getTypeClass()) {
2899#define TYPE(Class, Base)
2900#define ABSTRACT_TYPE(Class, Base)
2901#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2902#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2903#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2904#include "clang/AST/TypeNodes.def"
2905 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2906
2907 case Type::LValueReference:
2908 case Type::RValueReference:
2909 llvm_unreachable("References shouldn't get here");
2910
2911 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002912 case Type::DeducedTemplateSpecialization:
2913 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002914
Xiuli Pan9c14e282016-01-09 12:53:17 +00002915 case Type::Pipe:
2916 llvm_unreachable("Pipe types shouldn't get here");
2917
David Majnemere2cb8d12014-07-07 06:20:47 +00002918 case Type::Builtin:
2919 // GCC treats vector and complex types as fundamental types.
2920 case Type::Vector:
2921 case Type::ExtVector:
2922 case Type::Complex:
2923 case Type::Atomic:
2924 // FIXME: GCC treats block pointers as fundamental types?!
2925 case Type::BlockPointer:
2926 // abi::__fundamental_type_info.
2927 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2928 break;
2929
2930 case Type::ConstantArray:
2931 case Type::IncompleteArray:
2932 case Type::VariableArray:
2933 // abi::__array_type_info.
2934 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2935 break;
2936
2937 case Type::FunctionNoProto:
2938 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002939 // abi::__function_type_info.
2940 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002941 break;
2942
2943 case Type::Enum:
2944 // abi::__enum_type_info.
2945 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2946 break;
2947
2948 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00002949 const CXXRecordDecl *RD =
2950 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00002951
2952 if (!RD->hasDefinition() || !RD->getNumBases()) {
2953 VTableName = ClassTypeInfo;
2954 } else if (CanUseSingleInheritance(RD)) {
2955 VTableName = SIClassTypeInfo;
2956 } else {
2957 VTableName = VMIClassTypeInfo;
2958 }
2959
2960 break;
2961 }
2962
2963 case Type::ObjCObject:
2964 // Ignore protocol qualifiers.
2965 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2966
2967 // Handle id and Class.
2968 if (isa<BuiltinType>(Ty)) {
2969 VTableName = ClassTypeInfo;
2970 break;
2971 }
2972
2973 assert(isa<ObjCInterfaceType>(Ty));
2974 // Fall through.
2975
2976 case Type::ObjCInterface:
2977 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2978 VTableName = SIClassTypeInfo;
2979 } else {
2980 VTableName = ClassTypeInfo;
2981 }
2982 break;
2983
2984 case Type::ObjCObjectPointer:
2985 case Type::Pointer:
2986 // abi::__pointer_type_info.
2987 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2988 break;
2989
2990 case Type::MemberPointer:
2991 // abi::__pointer_to_member_type_info.
2992 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2993 break;
2994 }
2995
2996 llvm::Constant *VTable =
2997 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00002998 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00002999
3000 llvm::Type *PtrDiffTy =
3001 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
3002
3003 // The vtable address point is 2.
3004 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00003005 VTable =
3006 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00003007 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3008
3009 Fields.push_back(VTable);
3010}
3011
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003012/// Return the linkage that the type info and type info name constants
David Majnemere2cb8d12014-07-07 06:20:47 +00003013/// should have for the given type.
Richard Smithbbb26552018-05-21 20:10:54 +00003014static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
3015 QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003016 // Itanium C++ ABI 2.9.5p7:
3017 // In addition, it and all of the intermediate abi::__pointer_type_info
3018 // structs in the chain down to the abi::__class_type_info for the
3019 // incomplete class type must be prevented from resolving to the
3020 // corresponding type_info structs for the complete class type, possibly
3021 // by making them local static objects. Finally, a dummy class RTTI is
3022 // generated for the incomplete type that will not resolve to the final
3023 // complete class RTTI (because the latter need not exist), possibly by
3024 // making it a local static object.
3025 if (ContainsIncompleteClassType(Ty))
Richard Smithbbb26552018-05-21 20:10:54 +00003026 return llvm::GlobalValue::InternalLinkage;
3027
3028 switch (Ty->getLinkage()) {
3029 case NoLinkage:
3030 case InternalLinkage:
3031 case UniqueExternalLinkage:
3032 return llvm::GlobalValue::InternalLinkage;
3033
3034 case VisibleNoLinkage:
3035 case ModuleInternalLinkage:
3036 case ModuleLinkage:
3037 case ExternalLinkage:
3038 // RTTI is not enabled, which means that this type info struct is going
3039 // to be used for exception handling. Give it linkonce_odr linkage.
3040 if (!CGM.getLangOpts().RTTI)
3041 return llvm::GlobalValue::LinkOnceODRLinkage;
3042
3043 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3044 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3045 if (RD->hasAttr<WeakAttr>())
3046 return llvm::GlobalValue::WeakODRLinkage;
3047 if (CGM.getTriple().isWindowsItaniumEnvironment())
3048 if (RD->hasAttr<DLLImportAttr>() &&
3049 ShouldUseExternalRTTIDescriptor(CGM, Ty))
3050 return llvm::GlobalValue::ExternalLinkage;
3051 // MinGW always uses LinkOnceODRLinkage for type info.
3052 if (RD->isDynamicClass() &&
3053 !CGM.getContext()
3054 .getTargetInfo()
3055 .getTriple()
3056 .isWindowsGNUEnvironment())
3057 return CGM.getVTableLinkage(RD);
3058 }
3059
3060 return llvm::GlobalValue::LinkOnceODRLinkage;
3061 }
3062
3063 llvm_unreachable("Invalid linkage!");
David Majnemere2cb8d12014-07-07 06:20:47 +00003064}
3065
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003066llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3067 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003068 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003069 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003070
3071 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003072 SmallString<256> Name;
3073 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003074 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003075
3076 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3077 if (OldGV && !OldGV->isDeclaration()) {
3078 assert(!OldGV->hasAvailableExternallyLinkage() &&
3079 "available_externally typeinfos not yet implemented");
3080
3081 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3082 }
3083
3084 // Check if there is already an external RTTI descriptor for this type.
3085 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3086 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3087 return GetAddrOfExternalRTTIDescriptor(Ty);
3088
3089 // Emit the standard library with external linkage.
Richard Smithbbb26552018-05-21 20:10:54 +00003090 llvm::GlobalVariable::LinkageTypes Linkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00003091 if (IsStdLib)
Richard Smithbbb26552018-05-21 20:10:54 +00003092 Linkage = llvm::GlobalValue::ExternalLinkage;
3093 else
3094 Linkage = getTypeInfoLinkage(CGM, Ty);
3095
David Majnemere2cb8d12014-07-07 06:20:47 +00003096 // Add the vtable pointer.
3097 BuildVTablePointer(cast<Type>(Ty));
3098
3099 // And the name.
Richard Smithbbb26552018-05-21 20:10:54 +00003100 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003101 llvm::Constant *TypeNameField;
3102
3103 // If we're supposed to demote the visibility, be sure to set a flag
3104 // to use a string comparison for type_info comparisons.
3105 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
Richard Smithbbb26552018-05-21 20:10:54 +00003106 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003107 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3108 // The flag is the sign bit, which on ARM64 is defined to be clear
3109 // for global pointers. This is very ARM64-specific.
3110 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3111 llvm::Constant *flag =
3112 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3113 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3114 TypeNameField =
3115 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3116 } else {
3117 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3118 }
3119 Fields.push_back(TypeNameField);
3120
3121 switch (Ty->getTypeClass()) {
3122#define TYPE(Class, Base)
3123#define ABSTRACT_TYPE(Class, Base)
3124#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3125#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3126#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3127#include "clang/AST/TypeNodes.def"
3128 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3129
3130 // GCC treats vector types as fundamental types.
3131 case Type::Builtin:
3132 case Type::Vector:
3133 case Type::ExtVector:
3134 case Type::Complex:
3135 case Type::BlockPointer:
3136 // Itanium C++ ABI 2.9.5p4:
3137 // abi::__fundamental_type_info adds no data members to std::type_info.
3138 break;
3139
3140 case Type::LValueReference:
3141 case Type::RValueReference:
3142 llvm_unreachable("References shouldn't get here");
3143
3144 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003145 case Type::DeducedTemplateSpecialization:
3146 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003147
Xiuli Pan9c14e282016-01-09 12:53:17 +00003148 case Type::Pipe:
3149 llvm_unreachable("Pipe type shouldn't get here");
3150
David Majnemere2cb8d12014-07-07 06:20:47 +00003151 case Type::ConstantArray:
3152 case Type::IncompleteArray:
3153 case Type::VariableArray:
3154 // Itanium C++ ABI 2.9.5p5:
3155 // abi::__array_type_info adds no data members to std::type_info.
3156 break;
3157
3158 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003159 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003160 // Itanium C++ ABI 2.9.5p5:
3161 // abi::__function_type_info adds no data members to std::type_info.
3162 break;
3163
3164 case Type::Enum:
3165 // Itanium C++ ABI 2.9.5p5:
3166 // abi::__enum_type_info adds no data members to std::type_info.
3167 break;
3168
3169 case Type::Record: {
3170 const CXXRecordDecl *RD =
3171 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3172 if (!RD->hasDefinition() || !RD->getNumBases()) {
3173 // We don't need to emit any fields.
3174 break;
3175 }
3176
3177 if (CanUseSingleInheritance(RD))
3178 BuildSIClassTypeInfo(RD);
3179 else
3180 BuildVMIClassTypeInfo(RD);
3181
3182 break;
3183 }
3184
3185 case Type::ObjCObject:
3186 case Type::ObjCInterface:
3187 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3188 break;
3189
3190 case Type::ObjCObjectPointer:
3191 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3192 break;
3193
3194 case Type::Pointer:
3195 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3196 break;
3197
3198 case Type::MemberPointer:
3199 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3200 break;
3201
3202 case Type::Atomic:
3203 // No fields, at least for the moment.
3204 break;
3205 }
3206
3207 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3208
Rafael Espindolacb92c192015-01-15 23:18:01 +00003209 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003210 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003211 new llvm::GlobalVariable(M, Init->getType(),
Richard Smithbbb26552018-05-21 20:10:54 +00003212 /*Constant=*/true, Linkage, Init, Name);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003213
David Majnemere2cb8d12014-07-07 06:20:47 +00003214 // If there's already an old global variable, replace it with the new one.
3215 if (OldGV) {
3216 GV->takeName(OldGV);
3217 llvm::Constant *NewPtr =
3218 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3219 OldGV->replaceAllUsesWith(NewPtr);
3220 OldGV->eraseFromParent();
3221 }
3222
Yaron Keren04da2382015-07-29 15:42:28 +00003223 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3224 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3225
David Majnemere2cb8d12014-07-07 06:20:47 +00003226 // The Itanium ABI specifies that type_info objects must be globally
3227 // unique, with one exception: if the type is an incomplete class
3228 // type or a (possibly indirect) pointer to one. That exception
3229 // affects the general case of comparing type_info objects produced
3230 // by the typeid operator, which is why the comparison operators on
3231 // std::type_info generally use the type_info name pointers instead
3232 // of the object addresses. However, the language's built-in uses
3233 // of RTTI generally require class types to be complete, even when
3234 // manipulating pointers to those class types. This allows the
3235 // implementation of dynamic_cast to rely on address equality tests,
3236 // which is much faster.
3237
3238 // All of this is to say that it's important that both the type_info
3239 // object and the type_info name be uniqued when weakly emitted.
3240
3241 // Give the type_info object and name the formal visibility of the
3242 // type itself.
Richard Smithbbb26552018-05-21 20:10:54 +00003243 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3244 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3245 // If the linkage is local, only default visibility makes sense.
3246 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3247 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3248 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3249 else
3250 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003251
Richard Smithbbb26552018-05-21 20:10:54 +00003252 TypeName->setVisibility(llvmVisibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003253 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003254
Richard Smithbbb26552018-05-21 20:10:54 +00003255 GV->setVisibility(llvmVisibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003256 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003257
3258 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3259 auto RD = Ty->getAsCXXRecordDecl();
3260 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3261 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3262 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003263 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3264 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003265 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3266 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3267
3268 // Because the typename and the typeinfo are DLL import, convert them to
3269 // declarations rather than definitions. The initializers still need to
3270 // be constructed to calculate the type for the declarations.
3271 TypeName->setInitializer(nullptr);
3272 GV->setInitializer(nullptr);
3273 }
3274 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003275
3276 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3277}
3278
David Majnemere2cb8d12014-07-07 06:20:47 +00003279/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3280/// for the given Objective-C object type.
3281void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3282 // Drop qualifiers.
3283 const Type *T = OT->getBaseType().getTypePtr();
3284 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3285
3286 // The builtin types are abi::__class_type_infos and don't require
3287 // extra fields.
3288 if (isa<BuiltinType>(T)) return;
3289
3290 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3291 ObjCInterfaceDecl *Super = Class->getSuperClass();
3292
3293 // Root classes are also __class_type_info.
3294 if (!Super) return;
3295
3296 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3297
3298 // Everything else is single inheritance.
3299 llvm::Constant *BaseTypeInfo =
3300 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3301 Fields.push_back(BaseTypeInfo);
3302}
3303
3304/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3305/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3306void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3307 // Itanium C++ ABI 2.9.5p6b:
3308 // It adds to abi::__class_type_info a single member pointing to the
3309 // type_info structure for the base type,
3310 llvm::Constant *BaseTypeInfo =
3311 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3312 Fields.push_back(BaseTypeInfo);
3313}
3314
3315namespace {
3316 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3317 /// a class hierarchy.
3318 struct SeenBases {
3319 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3320 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3321 };
3322}
3323
3324/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3325/// abi::__vmi_class_type_info.
3326///
3327static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3328 SeenBases &Bases) {
3329
3330 unsigned Flags = 0;
3331
3332 const CXXRecordDecl *BaseDecl =
3333 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3334
3335 if (Base->isVirtual()) {
3336 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003337 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003338 // If this virtual base has been seen before, then the class is diamond
3339 // shaped.
3340 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3341 } else {
3342 if (Bases.NonVirtualBases.count(BaseDecl))
3343 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3344 }
3345 } else {
3346 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003347 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003348 // If this non-virtual base has been seen before, then the class has non-
3349 // diamond shaped repeated inheritance.
3350 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3351 } else {
3352 if (Bases.VirtualBases.count(BaseDecl))
3353 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3354 }
3355 }
3356
3357 // Walk all bases.
3358 for (const auto &I : BaseDecl->bases())
3359 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3360
3361 return Flags;
3362}
3363
3364static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3365 unsigned Flags = 0;
3366 SeenBases Bases;
3367
3368 // Walk all bases.
3369 for (const auto &I : RD->bases())
3370 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3371
3372 return Flags;
3373}
3374
3375/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3376/// classes with bases that do not satisfy the abi::__si_class_type_info
3377/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3378void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3379 llvm::Type *UnsignedIntLTy =
3380 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3381
3382 // Itanium C++ ABI 2.9.5p6c:
3383 // __flags is a word with flags describing details about the class
3384 // structure, which may be referenced by using the __flags_masks
3385 // enumeration. These flags refer to both direct and indirect bases.
3386 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3387 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3388
3389 // Itanium C++ ABI 2.9.5p6c:
3390 // __base_count is a word with the number of direct proper base class
3391 // descriptions that follow.
3392 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3393
3394 if (!RD->getNumBases())
3395 return;
3396
David Majnemere2cb8d12014-07-07 06:20:47 +00003397 // Now add the base class descriptions.
3398
3399 // Itanium C++ ABI 2.9.5p6c:
3400 // __base_info[] is an array of base class descriptions -- one for every
3401 // direct proper base. Each description is of the type:
3402 //
3403 // struct abi::__base_class_type_info {
3404 // public:
3405 // const __class_type_info *__base_type;
3406 // long __offset_flags;
3407 //
3408 // enum __offset_flags_masks {
3409 // __virtual_mask = 0x1,
3410 // __public_mask = 0x2,
3411 // __offset_shift = 8
3412 // };
3413 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003414
3415 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3416 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3417 // LLP64 platforms.
3418 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3419 // LLP64 platforms.
3420 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3421 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3422 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3423 OffsetFlagsTy = CGM.getContext().LongLongTy;
3424 llvm::Type *OffsetFlagsLTy =
3425 CGM.getTypes().ConvertType(OffsetFlagsTy);
3426
David Majnemere2cb8d12014-07-07 06:20:47 +00003427 for (const auto &Base : RD->bases()) {
3428 // The __base_type member points to the RTTI for the base type.
3429 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3430
3431 const CXXRecordDecl *BaseDecl =
3432 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3433
3434 int64_t OffsetFlags = 0;
3435
3436 // All but the lower 8 bits of __offset_flags are a signed offset.
3437 // For a non-virtual base, this is the offset in the object of the base
3438 // subobject. For a virtual base, this is the offset in the virtual table of
3439 // the virtual base offset for the virtual base referenced (negative).
3440 CharUnits Offset;
3441 if (Base.isVirtual())
3442 Offset =
3443 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3444 else {
3445 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3446 Offset = Layout.getBaseClassOffset(BaseDecl);
3447 };
3448
3449 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3450
3451 // The low-order byte of __offset_flags contains flags, as given by the
3452 // masks from the enumeration __offset_flags_masks.
3453 if (Base.isVirtual())
3454 OffsetFlags |= BCTI_Virtual;
3455 if (Base.getAccessSpecifier() == AS_public)
3456 OffsetFlags |= BCTI_Public;
3457
Reid Klecknerd8b04662016-08-25 22:16:30 +00003458 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003459 }
3460}
3461
Richard Smitha7d93782016-12-01 03:32:42 +00003462/// Compute the flags for a __pbase_type_info, and remove the corresponding
3463/// pieces from \p Type.
3464static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3465 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003466
Richard Smitha7d93782016-12-01 03:32:42 +00003467 if (Type.isConstQualified())
3468 Flags |= ItaniumRTTIBuilder::PTI_Const;
3469 if (Type.isVolatileQualified())
3470 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3471 if (Type.isRestrictQualified())
3472 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3473 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003474
3475 // Itanium C++ ABI 2.9.5p7:
3476 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3477 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003478 if (ContainsIncompleteClassType(Type))
3479 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3480
3481 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003482 if (Proto->isNothrow()) {
Richard Smitha7d93782016-12-01 03:32:42 +00003483 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003484 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003485 }
3486 }
3487
3488 return Flags;
3489}
3490
3491/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3492/// used for pointer types.
3493void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3494 // Itanium C++ ABI 2.9.5p7:
3495 // __flags is a flag word describing the cv-qualification and other
3496 // attributes of the type pointed to
3497 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003498
3499 llvm::Type *UnsignedIntLTy =
3500 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3501 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3502
3503 // Itanium C++ ABI 2.9.5p7:
3504 // __pointee is a pointer to the std::type_info derivation for the
3505 // unqualified type being pointed to.
3506 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003507 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003508 Fields.push_back(PointeeTypeInfo);
3509}
3510
3511/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3512/// struct, used for member pointer types.
3513void
3514ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3515 QualType PointeeTy = Ty->getPointeeType();
3516
David Majnemere2cb8d12014-07-07 06:20:47 +00003517 // Itanium C++ ABI 2.9.5p7:
3518 // __flags is a flag word describing the cv-qualification and other
3519 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003520 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003521
3522 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003523 if (IsIncompleteClassType(ClassType))
3524 Flags |= PTI_ContainingClassIncomplete;
3525
3526 llvm::Type *UnsignedIntLTy =
3527 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3528 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3529
3530 // Itanium C++ ABI 2.9.5p7:
3531 // __pointee is a pointer to the std::type_info derivation for the
3532 // unqualified type being pointed to.
3533 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003534 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003535 Fields.push_back(PointeeTypeInfo);
3536
3537 // Itanium C++ ABI 2.9.5p9:
3538 // __context is a pointer to an abi::__class_type_info corresponding to the
3539 // class type containing the member pointed to
3540 // (e.g., the "A" in "int A::*").
3541 Fields.push_back(
3542 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3543}
3544
David Majnemer443250f2015-03-17 20:35:00 +00003545llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003546 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3547}
3548
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003549void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3550 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003551 QualType PointerType = getContext().getPointerType(Type);
3552 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003553 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3554 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3555 DLLExport);
3556 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3557 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003558}
3559
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003560void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003561 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003562 QualType FundamentalTypes[] = {
3563 getContext().VoidTy, getContext().NullPtrTy,
3564 getContext().BoolTy, getContext().WCharTy,
3565 getContext().CharTy, getContext().UnsignedCharTy,
3566 getContext().SignedCharTy, getContext().ShortTy,
3567 getContext().UnsignedShortTy, getContext().IntTy,
3568 getContext().UnsignedIntTy, getContext().LongTy,
3569 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003570 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3571 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003572 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003573 getContext().LongDoubleTy, getContext().Float128Ty,
Richard Smith3a8244d2018-05-01 05:02:45 +00003574 getContext().Char8Ty, getContext().Char16Ty,
3575 getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003576 };
3577 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003578 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003579}
3580
3581/// What sort of uniqueness rules should we use for the RTTI for the
3582/// given type?
3583ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3584 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3585 if (shouldRTTIBeUnique())
3586 return RUK_Unique;
3587
3588 // It's only necessary for linkonce_odr or weak_odr linkage.
3589 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3590 Linkage != llvm::GlobalValue::WeakODRLinkage)
3591 return RUK_Unique;
3592
3593 // It's only necessary with default visibility.
3594 if (CanTy->getVisibility() != DefaultVisibility)
3595 return RUK_Unique;
3596
3597 // If we're not required to publish this symbol, hide it.
3598 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3599 return RUK_NonUniqueHidden;
3600
3601 // If we're required to publish this symbol, as we might be under an
3602 // explicit instantiation, leave it with default visibility but
3603 // enable string-comparisons.
3604 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3605 return RUK_NonUniqueVisible;
3606}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003607
Rafael Espindola1e4df922014-09-16 15:18:21 +00003608// Find out how to codegen the complete destructor and constructor
3609namespace {
3610enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3611}
3612static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3613 const CXXMethodDecl *MD) {
3614 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3615 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003616
Rafael Espindola1e4df922014-09-16 15:18:21 +00003617 // The complete and base structors are not equivalent if there are any virtual
3618 // bases, so emit separate functions.
3619 if (MD->getParent()->getNumVBases())
3620 return StructorCodegen::Emit;
3621
3622 GlobalDecl AliasDecl;
3623 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3624 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3625 } else {
3626 const auto *CD = cast<CXXConstructorDecl>(MD);
3627 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3628 }
3629 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3630
Richard Smith6ca999b2018-05-30 00:45:10 +00003631 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3632 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003633
Pavel Labathc370f262018-05-14 11:35:44 +00003634 // FIXME: Should we allow available_externally aliases?
Richard Smith6ca999b2018-05-30 00:45:10 +00003635 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3636 return StructorCodegen::RAUW;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003637
Rafael Espindola0806f982014-09-16 20:19:43 +00003638 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003639 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3640 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3641 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003642 return StructorCodegen::COMDAT;
3643 return StructorCodegen::Emit;
3644 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003645
3646 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003647}
3648
Rafael Espindola1e4df922014-09-16 15:18:21 +00003649static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3650 GlobalDecl AliasDecl,
3651 GlobalDecl TargetDecl) {
3652 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3653
3654 StringRef MangledName = CGM.getMangledName(AliasDecl);
3655 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3656 if (Entry && !Entry->isDeclaration())
3657 return;
3658
3659 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003660
3661 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003662 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003663
3664 // Switch any previous uses to the alias.
3665 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003666 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003667 "declaration exists with different type");
3668 Alias->takeName(Entry);
3669 Entry->replaceAllUsesWith(Alias);
3670 Entry->eraseFromParent();
3671 } else {
3672 Alias->setName(MangledName);
3673 }
3674
3675 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003676 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003677}
3678
3679void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3680 StructorType Type) {
3681 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3682 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3683
3684 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3685
3686 if (Type == StructorType::Complete) {
3687 GlobalDecl CompleteDecl;
3688 GlobalDecl BaseDecl;
3689 if (CD) {
3690 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3691 BaseDecl = GlobalDecl(CD, Ctor_Base);
3692 } else {
3693 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3694 BaseDecl = GlobalDecl(DD, Dtor_Base);
3695 }
3696
3697 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3698 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3699 return;
3700 }
3701
3702 if (CGType == StructorCodegen::RAUW) {
3703 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003704 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003705 CGM.addReplacement(MangledName, Aliasee);
3706 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003707 }
3708 }
3709
3710 // The base destructor is equivalent to the base destructor of its
3711 // base class if there is exactly one non-virtual base class with a
3712 // non-trivial destructor, there are no fields with a non-trivial
3713 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003714 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3715 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003716 return;
3717
Richard Smith5b349582017-10-13 01:55:36 +00003718 // FIXME: The deleting destructor is equivalent to the selected operator
3719 // delete if:
3720 // * either the delete is a destroying operator delete or the destructor
3721 // would be trivial if it weren't virtual,
3722 // * the conversion from the 'this' parameter to the first parameter of the
3723 // destructor is equivalent to a bitcast,
3724 // * the destructor does not have an implicit "this" return, and
3725 // * the operator delete has the same calling convention and IR function type
3726 // as the destructor.
3727 // In such cases we should try to emit the deleting dtor as an alias to the
3728 // selected 'operator delete'.
3729
Rafael Espindola1e4df922014-09-16 15:18:21 +00003730 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003731
Rafael Espindola1e4df922014-09-16 15:18:21 +00003732 if (CGType == StructorCodegen::COMDAT) {
3733 SmallString<256> Buffer;
3734 llvm::raw_svector_ostream Out(Buffer);
3735 if (DD)
3736 getMangleContext().mangleCXXDtorComdat(DD, Out);
3737 else
3738 getMangleContext().mangleCXXCtorComdat(CD, Out);
3739 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3740 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003741 } else {
3742 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003743 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003744}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003745
3746static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3747 // void *__cxa_begin_catch(void*);
3748 llvm::FunctionType *FTy = llvm::FunctionType::get(
3749 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3750
3751 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3752}
3753
3754static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3755 // void __cxa_end_catch();
3756 llvm::FunctionType *FTy =
3757 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3758
3759 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3760}
3761
3762static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3763 // void *__cxa_get_exception_ptr(void*);
3764 llvm::FunctionType *FTy = llvm::FunctionType::get(
3765 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3766
3767 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3768}
3769
3770namespace {
3771 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3772 /// exception type lets us state definitively that the thrown exception
3773 /// type does not have a destructor. In particular:
3774 /// - Catch-alls tell us nothing, so we have to conservatively
3775 /// assume that the thrown exception might have a destructor.
3776 /// - Catches by reference behave according to their base types.
3777 /// - Catches of non-record types will only trigger for exceptions
3778 /// of non-record types, which never have destructors.
3779 /// - Catches of record types can trigger for arbitrary subclasses
3780 /// of the caught type, so we have to assume the actual thrown
3781 /// exception type might have a throwing destructor, even if the
3782 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003783 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003784 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3785 bool MightThrow;
3786
3787 void Emit(CodeGenFunction &CGF, Flags flags) override {
3788 if (!MightThrow) {
3789 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3790 return;
3791 }
3792
3793 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3794 }
3795 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003796}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003797
3798/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3799/// __cxa_end_catch.
3800///
3801/// \param EndMightThrow - true if __cxa_end_catch might throw
3802static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3803 llvm::Value *Exn,
3804 bool EndMightThrow) {
3805 llvm::CallInst *call =
3806 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3807
3808 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3809
3810 return call;
3811}
3812
3813/// A "special initializer" callback for initializing a catch
3814/// parameter during catch initialization.
3815static void InitCatchParam(CodeGenFunction &CGF,
3816 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003817 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003818 SourceLocation Loc) {
3819 // Load the exception from where the landing pad saved it.
3820 llvm::Value *Exn = CGF.getExceptionFromSlot();
3821
3822 CanQualType CatchType =
3823 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3824 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3825
3826 // If we're catching by reference, we can just cast the object
3827 // pointer to the appropriate pointer.
3828 if (isa<ReferenceType>(CatchType)) {
3829 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3830 bool EndCatchMightThrow = CaughtType->isRecordType();
3831
3832 // __cxa_begin_catch returns the adjusted object pointer.
3833 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3834
3835 // We have no way to tell the personality function that we're
3836 // catching by reference, so if we're catching a pointer,
3837 // __cxa_begin_catch will actually return that pointer by value.
3838 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3839 QualType PointeeType = PT->getPointeeType();
3840
3841 // When catching by reference, generally we should just ignore
3842 // this by-value pointer and use the exception object instead.
3843 if (!PointeeType->isRecordType()) {
3844
3845 // Exn points to the struct _Unwind_Exception header, which
3846 // we have to skip past in order to reach the exception data.
3847 unsigned HeaderSize =
3848 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3849 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3850
3851 // However, if we're catching a pointer-to-record type that won't
3852 // work, because the personality function might have adjusted
3853 // the pointer. There's actually no way for us to fully satisfy
3854 // the language/ABI contract here: we can't use Exn because it
3855 // might have the wrong adjustment, but we can't use the by-value
3856 // pointer because it's off by a level of abstraction.
3857 //
3858 // The current solution is to dump the adjusted pointer into an
3859 // alloca, which breaks language semantics (because changing the
3860 // pointer doesn't change the exception) but at least works.
3861 // The better solution would be to filter out non-exact matches
3862 // and rethrow them, but this is tricky because the rethrow
3863 // really needs to be catchable by other sites at this landing
3864 // pad. The best solution is to fix the personality function.
3865 } else {
3866 // Pull the pointer for the reference type off.
3867 llvm::Type *PtrTy =
3868 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3869
3870 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003871 Address ExnPtrTmp =
3872 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003873 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3874 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3875
3876 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003877 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003878 }
3879 }
3880
3881 llvm::Value *ExnCast =
3882 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3883 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3884 return;
3885 }
3886
3887 // Scalars and complexes.
3888 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3889 if (TEK != TEK_Aggregate) {
3890 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3891
3892 // If the catch type is a pointer type, __cxa_begin_catch returns
3893 // the pointer by value.
3894 if (CatchType->hasPointerRepresentation()) {
3895 llvm::Value *CastExn =
3896 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3897
3898 switch (CatchType.getQualifiers().getObjCLifetime()) {
3899 case Qualifiers::OCL_Strong:
3900 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3901 // fallthrough
3902
3903 case Qualifiers::OCL_None:
3904 case Qualifiers::OCL_ExplicitNone:
3905 case Qualifiers::OCL_Autoreleasing:
3906 CGF.Builder.CreateStore(CastExn, ParamAddr);
3907 return;
3908
3909 case Qualifiers::OCL_Weak:
3910 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3911 return;
3912 }
3913 llvm_unreachable("bad ownership qualifier!");
3914 }
3915
3916 // Otherwise, it returns a pointer into the exception object.
3917
3918 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3919 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3920
3921 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003922 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003923 switch (TEK) {
3924 case TEK_Complex:
3925 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3926 /*init*/ true);
3927 return;
3928 case TEK_Scalar: {
3929 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3930 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3931 return;
3932 }
3933 case TEK_Aggregate:
3934 llvm_unreachable("evaluation kind filtered out!");
3935 }
3936 llvm_unreachable("bad evaluation kind");
3937 }
3938
3939 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003940 auto catchRD = CatchType->getAsCXXRecordDecl();
3941 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003942
3943 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3944
3945 // Check for a copy expression. If we don't have a copy expression,
3946 // that means a trivial copy is okay.
3947 const Expr *copyExpr = CatchParam.getInit();
3948 if (!copyExpr) {
3949 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003950 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3951 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00003952 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
3953 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
Richard Smithe78fac52018-04-05 20:52:58 +00003954 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003955 return;
3956 }
3957
3958 // We have to call __cxa_get_exception_ptr to get the adjusted
3959 // pointer before copying.
3960 llvm::CallInst *rawAdjustedExn =
3961 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3962
3963 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003964 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3965 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003966
3967 // The copy expression is defined in terms of an OpaqueValueExpr.
3968 // Find it and map it to the adjusted expression.
3969 CodeGenFunction::OpaqueValueMapping
3970 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3971 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3972
3973 // Call the copy ctor in a terminate scope.
3974 CGF.EHStack.pushTerminate();
3975
3976 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003977 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003978 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003979 AggValueSlot::IsNotDestructed,
3980 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003981 AggValueSlot::IsNotAliased,
3982 AggValueSlot::DoesNotOverlap));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003983
3984 // Leave the terminate scope.
3985 CGF.EHStack.popTerminate();
3986
3987 // Undo the opaque value mapping.
3988 opaque.pop();
3989
3990 // Finally we can call __cxa_begin_catch.
3991 CallBeginCatch(CGF, Exn, true);
3992}
3993
3994/// Begins a catch statement by initializing the catch variable and
3995/// calling __cxa_begin_catch.
3996void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3997 const CXXCatchStmt *S) {
3998 // We have to be very careful with the ordering of cleanups here:
3999 // C++ [except.throw]p4:
4000 // The destruction [of the exception temporary] occurs
4001 // immediately after the destruction of the object declared in
4002 // the exception-declaration in the handler.
4003 //
4004 // So the precise ordering is:
4005 // 1. Construct catch variable.
4006 // 2. __cxa_begin_catch
4007 // 3. Enter __cxa_end_catch cleanup
4008 // 4. Enter dtor cleanup
4009 //
4010 // We do this by using a slightly abnormal initialization process.
4011 // Delegation sequence:
4012 // - ExitCXXTryStmt opens a RunCleanupsScope
4013 // - EmitAutoVarAlloca creates the variable and debug info
4014 // - InitCatchParam initializes the variable from the exception
4015 // - CallBeginCatch calls __cxa_begin_catch
4016 // - CallBeginCatch enters the __cxa_end_catch cleanup
4017 // - EmitAutoVarCleanups enters the variable destructor cleanup
4018 // - EmitCXXTryStmt emits the code for the catch body
4019 // - EmitCXXTryStmt close the RunCleanupsScope
4020
4021 VarDecl *CatchParam = S->getExceptionDecl();
4022 if (!CatchParam) {
4023 llvm::Value *Exn = CGF.getExceptionFromSlot();
4024 CallBeginCatch(CGF, Exn, true);
4025 return;
4026 }
4027
4028 // Emit the local.
4029 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
4030 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
4031 CGF.EmitAutoVarCleanups(var);
4032}
4033
4034/// Get or define the following function:
4035/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
4036/// This code is used only in C++.
4037static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
4038 llvm::FunctionType *fnTy =
4039 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00004040 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
4041 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004042
4043 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
4044 if (fn && fn->empty()) {
4045 fn->setDoesNotThrow();
4046 fn->setDoesNotReturn();
4047
4048 // What we really want is to massively penalize inlining without
4049 // forbidding it completely. The difference between that and
4050 // 'noinline' is negligible.
4051 fn->addFnAttr(llvm::Attribute::NoInline);
4052
4053 // Allow this function to be shared across translation units, but
4054 // we don't want it to turn into an exported symbol.
4055 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4056 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004057 if (CGM.supportsCOMDAT())
4058 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004059
4060 // Set up the function.
4061 llvm::BasicBlock *entry =
4062 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004063 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004064
4065 // Pull the exception pointer out of the parameter list.
4066 llvm::Value *exn = &*fn->arg_begin();
4067
4068 // Call __cxa_begin_catch(exn).
4069 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4070 catchCall->setDoesNotThrow();
4071 catchCall->setCallingConv(CGM.getRuntimeCC());
4072
4073 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004074 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004075 termCall->setDoesNotThrow();
4076 termCall->setDoesNotReturn();
4077 termCall->setCallingConv(CGM.getRuntimeCC());
4078
4079 // std::terminate cannot return.
4080 builder.CreateUnreachable();
4081 }
4082
4083 return fnRef;
4084}
4085
4086llvm::CallInst *
4087ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4088 llvm::Value *Exn) {
4089 // In C++, we want to call __cxa_begin_catch() before terminating.
4090 if (Exn) {
4091 assert(CGF.CGM.getLangOpts().CPlusPlus);
4092 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4093 }
4094 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4095}
Peter Collingbourne60108802017-12-13 21:53:04 +00004096
4097std::pair<llvm::Value *, const CXXRecordDecl *>
4098ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4099 const CXXRecordDecl *RD) {
4100 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4101}
Heejin Ahnc6479192018-05-31 22:18:13 +00004102
4103void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4104 const CXXCatchStmt *C) {
Heejin Ahn1eb074d2018-06-01 01:01:37 +00004105 if (CGF.getTarget().hasFeature("exception-handling"))
4106 CGF.EHStack.pushCleanup<CatchRetScope>(
4107 NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
Heejin Ahnc6479192018-05-31 22:18:13 +00004108 ItaniumCXXABI::emitBeginCatch(CGF, C);
4109}