blob: 9768e71178b785d2bf82c50882e23705ee9af2a5 [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) {}
472
473private:
474 bool HasThisReturn(GlobalDecl GD) const override {
475 return isa<CXXConstructorDecl>(GD.getDecl()) ||
476 (isa<CXXDestructorDecl>(GD.getDecl()) &&
477 GD.getDtorType() != Dtor_Deleting);
478 }
Derek Schuff8179be42016-05-10 17:44:55 +0000479 bool canCallMismatchedFunctionType() const override { return false; }
Dan Gohmanc2853072015-09-03 22:51:53 +0000480};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000481}
Charles Davis4e786dd2010-05-25 19:52:27 +0000482
Charles Davis53c59df2010-08-16 03:33:14 +0000483CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +0000484 switch (CGM.getTarget().getCXXABI().getKind()) {
John McCall57625922013-01-25 23:36:14 +0000485 // For IR-generation purposes, there's no significant difference
486 // between the ARM and iOS ABIs.
487 case TargetCXXABI::GenericARM:
488 case TargetCXXABI::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000489 case TargetCXXABI::WatchOS:
John McCall57625922013-01-25 23:36:14 +0000490 return new ARMCXXABI(CGM);
Charles Davis4e786dd2010-05-25 19:52:27 +0000491
Tim Northovera2ee4332014-03-29 15:09:45 +0000492 case TargetCXXABI::iOS64:
493 return new iOS64CXXABI(CGM);
494
Tim Northover9bb857a2013-01-31 12:13:10 +0000495 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
496 // include the other 32-bit ARM oddities: constructor/destructor return values
497 // and array cookies.
498 case TargetCXXABI::GenericAArch64:
Mark Seabornedf0d382013-07-24 16:25:13 +0000499 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
500 /* UseARMGuardVarABI = */ true);
Tim Northover9bb857a2013-01-31 12:13:10 +0000501
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000502 case TargetCXXABI::GenericMIPS:
503 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
504
Dan Gohmanc2853072015-09-03 22:51:53 +0000505 case TargetCXXABI::WebAssembly:
506 return new WebAssemblyCXXABI(CGM);
507
John McCall57625922013-01-25 23:36:14 +0000508 case TargetCXXABI::GenericItanium:
Mark Seabornedf0d382013-07-24 16:25:13 +0000509 if (CGM.getContext().getTargetInfo().getTriple().getArch()
510 == llvm::Triple::le32) {
511 // For PNaCl, use ARM-style method pointers so that PNaCl code
512 // does not assume anything about the alignment of function
513 // pointers.
514 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
515 /* UseARMGuardVarABI = */ false);
516 }
John McCall57625922013-01-25 23:36:14 +0000517 return new ItaniumCXXABI(CGM);
518
519 case TargetCXXABI::Microsoft:
520 llvm_unreachable("Microsoft ABI is not Itanium-based");
521 }
522 llvm_unreachable("bad ABI kind");
John McCall86353412010-08-21 22:46:04 +0000523}
524
Chris Lattnera5f58b02011-07-09 17:41:47 +0000525llvm::Type *
John McCall7a9aac22010-08-23 01:21:21 +0000526ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
527 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000528 return CGM.PtrDiffTy;
Serge Guelton1d993272017-05-09 19:31:30 +0000529 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
John McCall1c456c82010-08-22 06:43:33 +0000530}
531
John McCalld9c6c0b2010-08-22 00:59:17 +0000532/// In the Itanium and ARM ABIs, method pointers have the form:
533/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
534///
535/// In the Itanium ABI:
536/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
537/// - the this-adjustment is (memptr.adj)
538/// - the virtual offset is (memptr.ptr - 1)
539///
540/// In the ARM ABI:
541/// - method pointers are virtual if (memptr.adj & 1) is nonzero
542/// - the this-adjustment is (memptr.adj >> 1)
543/// - the virtual offset is (memptr.ptr)
544/// ARM uses 'adj' for the virtual flag because Thumb functions
545/// may be only single-byte aligned.
546///
547/// If the member is virtual, the adjusted 'this' pointer points
548/// to a vtable pointer from which the virtual offset is applied.
549///
550/// If the member is non-virtual, memptr.ptr is the address of
551/// the function to call.
John McCallb92ab1a2016-10-26 23:46:34 +0000552CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
John McCall7f416cc2015-09-08 08:05:57 +0000553 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
554 llvm::Value *&ThisPtrForCall,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000555 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
John McCall475999d2010-08-22 00:05:51 +0000556 CGBuilderTy &Builder = CGF.Builder;
557
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000558 const FunctionProtoType *FPT =
John McCall475999d2010-08-22 00:05:51 +0000559 MPT->getPointeeType()->getAs<FunctionProtoType>();
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000560 const CXXRecordDecl *RD =
John McCall475999d2010-08-22 00:05:51 +0000561 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
562
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000563 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
564 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
John McCall475999d2010-08-22 00:05:51 +0000565
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000566 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
John McCall475999d2010-08-22 00:05:51 +0000567
John McCalld9c6c0b2010-08-22 00:59:17 +0000568 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
569 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
570 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
571
John McCalla1dee5302010-08-22 10:59:02 +0000572 // Extract memptr.adj, which is in the second field.
573 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
John McCalld9c6c0b2010-08-22 00:59:17 +0000574
575 // Compute the true adjustment.
576 llvm::Value *Adj = RawAdj;
Mark Seabornedf0d382013-07-24 16:25:13 +0000577 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000578 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
John McCall475999d2010-08-22 00:05:51 +0000579
580 // Apply the adjustment and cast back to the original struct type
581 // for consistency.
John McCall7f416cc2015-09-08 08:05:57 +0000582 llvm::Value *This = ThisAddr.getPointer();
John McCalld9c6c0b2010-08-22 00:59:17 +0000583 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
584 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
585 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
John McCall7f416cc2015-09-08 08:05:57 +0000586 ThisPtrForCall = This;
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000587
John McCall475999d2010-08-22 00:05:51 +0000588 // Load the function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000589 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000590
John McCall475999d2010-08-22 00:05:51 +0000591 // If the LSB in the function pointer is 1, the function pointer points to
592 // a virtual function.
John McCalld9c6c0b2010-08-22 00:59:17 +0000593 llvm::Value *IsVirtual;
Mark Seabornedf0d382013-07-24 16:25:13 +0000594 if (UseARMMethodPtrABI)
John McCalld9c6c0b2010-08-22 00:59:17 +0000595 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
596 else
597 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
598 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
John McCall475999d2010-08-22 00:05:51 +0000599 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
600
601 // In the virtual path, the adjustment left 'This' pointing to the
602 // vtable of the correct base subobject. The "function pointer" is an
John McCalld9c6c0b2010-08-22 00:59:17 +0000603 // offset within the vtable (+1 for the virtual flag on non-ARM).
John McCall475999d2010-08-22 00:05:51 +0000604 CGF.EmitBlock(FnVirtual);
605
606 // Cast the adjusted this to a pointer to vtable pointer and load.
Chris Lattner2192fe52011-07-18 04:24:23 +0000607 llvm::Type *VTableTy = Builder.getInt8PtrTy();
John McCall7f416cc2015-09-08 08:05:57 +0000608 CharUnits VTablePtrAlign =
609 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
610 CGF.getPointerAlign());
611 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000612 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
John McCall475999d2010-08-22 00:05:51 +0000613
614 // Apply the offset.
John McCalld23b27e2016-09-16 02:40:45 +0000615 // On ARM64, to reserve extra space in virtual member function pointers,
616 // we only pay attention to the low 32 bits of the offset.
John McCalld9c6c0b2010-08-22 00:59:17 +0000617 llvm::Value *VTableOffset = FnAsInt;
Mark Seabornedf0d382013-07-24 16:25:13 +0000618 if (!UseARMMethodPtrABI)
619 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
John McCalld23b27e2016-09-16 02:40:45 +0000620 if (Use32BitVTableOffsetABI) {
621 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
622 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
623 }
John McCalld9c6c0b2010-08-22 00:59:17 +0000624 VTable = Builder.CreateGEP(VTable, VTableOffset);
John McCall475999d2010-08-22 00:05:51 +0000625
626 // Load the virtual function to call.
627 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +0000628 llvm::Value *VirtualFn =
629 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
630 "memptr.virtualfn");
John McCall475999d2010-08-22 00:05:51 +0000631 CGF.EmitBranch(FnEnd);
632
633 // In the non-virtual path, the function pointer is actually a
634 // function pointer.
635 CGF.EmitBlock(FnNonVirtual);
636 llvm::Value *NonVirtualFn =
John McCalld9c6c0b2010-08-22 00:59:17 +0000637 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000638
John McCall475999d2010-08-22 00:05:51 +0000639 // We're done.
640 CGF.EmitBlock(FnEnd);
John McCallb92ab1a2016-10-26 23:46:34 +0000641 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
642 CalleePtr->addIncoming(VirtualFn, FnVirtual);
643 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
644
645 CGCallee Callee(FPT, CalleePtr);
John McCall475999d2010-08-22 00:05:51 +0000646 return Callee;
647}
John McCalla8bbb822010-08-22 03:04:22 +0000648
John McCallc134eb52010-08-31 21:07:20 +0000649/// Compute an l-value by applying the given pointer-to-member to a
650/// base object.
David Majnemer2b0d66d2014-02-20 23:22:07 +0000651llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
John McCall7f416cc2015-09-08 08:05:57 +0000652 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
David Majnemer2b0d66d2014-02-20 23:22:07 +0000653 const MemberPointerType *MPT) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000654 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCallc134eb52010-08-31 21:07:20 +0000655
656 CGBuilderTy &Builder = CGF.Builder;
657
John McCallc134eb52010-08-31 21:07:20 +0000658 // Cast to char*.
John McCall7f416cc2015-09-08 08:05:57 +0000659 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
John McCallc134eb52010-08-31 21:07:20 +0000660
661 // Apply the offset, which we assume is non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000662 llvm::Value *Addr =
663 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
John McCallc134eb52010-08-31 21:07:20 +0000664
665 // Cast the address to the appropriate pointer type, adopting the
666 // address space of the base pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000667 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
668 ->getPointerTo(Base.getAddressSpace());
John McCallc134eb52010-08-31 21:07:20 +0000669 return Builder.CreateBitCast(Addr, PType);
670}
671
John McCallc62bb392012-02-15 01:22:51 +0000672/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
673/// conversion.
674///
675/// Bitcast conversions are always a no-op under Itanium.
John McCall7a9aac22010-08-23 01:21:21 +0000676///
677/// Obligatory offset/adjustment diagram:
678/// <-- offset --> <-- adjustment -->
679/// |--------------------------|----------------------|--------------------|
680/// ^Derived address point ^Base address point ^Member address point
681///
682/// So when converting a base member pointer to a derived member pointer,
683/// we add the offset to the adjustment because the address point has
684/// decreased; and conversely, when converting a derived MP to a base MP
685/// we subtract the offset from the adjustment because the address point
686/// has increased.
687///
688/// The standard forbids (at compile time) conversion to and from
689/// virtual bases, which is why we don't have to consider them here.
690///
691/// The standard forbids (at run time) casting a derived MP to a base
692/// MP when the derived MP does not point to a member of the base.
693/// This is why -1 is a reasonable choice for null data member
694/// pointers.
John McCalla1dee5302010-08-22 10:59:02 +0000695llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000696ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
697 const CastExpr *E,
John McCallc62bb392012-02-15 01:22:51 +0000698 llvm::Value *src) {
John McCalle3027922010-08-25 11:45:40 +0000699 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
John McCallc62bb392012-02-15 01:22:51 +0000700 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
701 E->getCastKind() == CK_ReinterpretMemberPointer);
702
703 // Under Itanium, reinterprets don't require any additional processing.
704 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
705
706 // Use constant emission if we can.
707 if (isa<llvm::Constant>(src))
708 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
709
710 llvm::Constant *adj = getMemberPointerAdjustment(E);
711 if (!adj) return src;
John McCalla8bbb822010-08-22 03:04:22 +0000712
713 CGBuilderTy &Builder = CGF.Builder;
John McCallc62bb392012-02-15 01:22:51 +0000714 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
John McCalla8bbb822010-08-22 03:04:22 +0000715
John McCallc62bb392012-02-15 01:22:51 +0000716 const MemberPointerType *destTy =
717 E->getType()->castAs<MemberPointerType>();
John McCall1c456c82010-08-22 06:43:33 +0000718
John McCall7a9aac22010-08-23 01:21:21 +0000719 // For member data pointers, this is just a matter of adding the
720 // offset if the source is non-null.
John McCallc62bb392012-02-15 01:22:51 +0000721 if (destTy->isMemberDataPointer()) {
722 llvm::Value *dst;
723 if (isDerivedToBase)
724 dst = Builder.CreateNSWSub(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000725 else
John McCallc62bb392012-02-15 01:22:51 +0000726 dst = Builder.CreateNSWAdd(src, adj, "adj");
John McCall7a9aac22010-08-23 01:21:21 +0000727
728 // Null check.
John McCallc62bb392012-02-15 01:22:51 +0000729 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
730 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
731 return Builder.CreateSelect(isNull, src, dst);
John McCall7a9aac22010-08-23 01:21:21 +0000732 }
733
John McCalla1dee5302010-08-22 10:59:02 +0000734 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000735 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000736 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
737 offset <<= 1;
738 adj = llvm::ConstantInt::get(adj->getType(), offset);
John McCalla1dee5302010-08-22 10:59:02 +0000739 }
740
John McCallc62bb392012-02-15 01:22:51 +0000741 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
742 llvm::Value *dstAdj;
743 if (isDerivedToBase)
744 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000745 else
John McCallc62bb392012-02-15 01:22:51 +0000746 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
John McCalla1dee5302010-08-22 10:59:02 +0000747
John McCallc62bb392012-02-15 01:22:51 +0000748 return Builder.CreateInsertValue(src, dstAdj, 1);
749}
750
751llvm::Constant *
752ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
753 llvm::Constant *src) {
754 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
755 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
756 E->getCastKind() == CK_ReinterpretMemberPointer);
757
758 // Under Itanium, reinterprets don't require any additional processing.
759 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
760
761 // If the adjustment is trivial, we don't need to do anything.
762 llvm::Constant *adj = getMemberPointerAdjustment(E);
763 if (!adj) return src;
764
765 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
766
767 const MemberPointerType *destTy =
768 E->getType()->castAs<MemberPointerType>();
769
770 // For member data pointers, this is just a matter of adding the
771 // offset if the source is non-null.
772 if (destTy->isMemberDataPointer()) {
773 // null maps to null.
774 if (src->isAllOnesValue()) return src;
775
776 if (isDerivedToBase)
777 return llvm::ConstantExpr::getNSWSub(src, adj);
778 else
779 return llvm::ConstantExpr::getNSWAdd(src, adj);
780 }
781
782 // The this-adjustment is left-shifted by 1 on ARM.
Mark Seabornedf0d382013-07-24 16:25:13 +0000783 if (UseARMMethodPtrABI) {
John McCallc62bb392012-02-15 01:22:51 +0000784 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
785 offset <<= 1;
786 adj = llvm::ConstantInt::get(adj->getType(), offset);
787 }
788
789 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
790 llvm::Constant *dstAdj;
791 if (isDerivedToBase)
792 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
793 else
794 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
795
796 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
John McCalla8bbb822010-08-22 03:04:22 +0000797}
John McCall84fa5102010-08-22 04:16:24 +0000798
799llvm::Constant *
John McCall7a9aac22010-08-23 01:21:21 +0000800ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
John McCall7a9aac22010-08-23 01:21:21 +0000801 // Itanium C++ ABI 2.3:
802 // A NULL pointer is represented as -1.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000803 if (MPT->isMemberDataPointer())
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000804 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
John McCalla1dee5302010-08-22 10:59:02 +0000805
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000806 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
John McCalla1dee5302010-08-22 10:59:02 +0000807 llvm::Constant *Values[2] = { Zero, Zero };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000808 return llvm::ConstantStruct::getAnon(Values);
John McCall84fa5102010-08-22 04:16:24 +0000809}
810
John McCallf3a88602011-02-03 08:15:49 +0000811llvm::Constant *
812ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
813 CharUnits offset) {
John McCall7a9aac22010-08-23 01:21:21 +0000814 // Itanium C++ ABI 2.3:
815 // A pointer to data member is an offset from the base address of
816 // the class object containing it, represented as a ptrdiff_t
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000817 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
John McCall7a9aac22010-08-23 01:21:21 +0000818}
819
David Majnemere2be95b2015-06-23 07:31:01 +0000820llvm::Constant *
821ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
Richard Smithdafff942012-01-14 04:30:29 +0000822 return BuildMemberPointer(MD, CharUnits::Zero());
823}
824
825llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
826 CharUnits ThisAdjustment) {
John McCalla1dee5302010-08-22 10:59:02 +0000827 assert(MD->isInstance() && "Member function must not be static!");
John McCalla1dee5302010-08-22 10:59:02 +0000828
829 CodeGenTypes &Types = CGM.getTypes();
John McCalla1dee5302010-08-22 10:59:02 +0000830
831 // Get the function pointer (or index if this is a virtual function).
832 llvm::Constant *MemPtr[2];
833 if (MD->isVirtual()) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000834 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
John McCalla1dee5302010-08-22 10:59:02 +0000835
Ken Dyckdf016282011-04-09 01:30:02 +0000836 const ASTContext &Context = getContext();
837 CharUnits PointerWidth =
Douglas Gregore8bbc122011-09-02 00:18:52 +0000838 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Ken Dyckdf016282011-04-09 01:30:02 +0000839 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000840
Mark Seabornedf0d382013-07-24 16:25:13 +0000841 if (UseARMMethodPtrABI) {
John McCalla1dee5302010-08-22 10:59:02 +0000842 // ARM C++ ABI 3.2.1:
843 // This ABI specifies that adj contains twice the this
844 // adjustment, plus 1 if the member function is virtual. The
845 // least significant bit of adj then makes exactly the same
846 // discrimination as the least significant bit of ptr does for
847 // Itanium.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000848 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
849 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000850 2 * ThisAdjustment.getQuantity() + 1);
John McCalla1dee5302010-08-22 10:59:02 +0000851 } else {
852 // Itanium C++ ABI 2.3:
853 // For a virtual function, [the pointer field] is 1 plus the
854 // virtual table offset (in bytes) of the function,
855 // represented as a ptrdiff_t.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000856 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
857 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
Richard Smithdafff942012-01-14 04:30:29 +0000858 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000859 }
860 } else {
John McCall2979fe02011-04-12 00:42:48 +0000861 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +0000862 llvm::Type *Ty;
John McCall2979fe02011-04-12 00:42:48 +0000863 // Check whether the function has a computable LLVM signature.
Chris Lattner8806e322011-07-10 00:18:59 +0000864 if (Types.isFuncTypeConvertible(FPT)) {
John McCall2979fe02011-04-12 00:42:48 +0000865 // The function has a computable LLVM signature; use the correct type.
John McCalla729c622012-02-17 03:33:10 +0000866 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
John McCalla1dee5302010-08-22 10:59:02 +0000867 } else {
John McCall2979fe02011-04-12 00:42:48 +0000868 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
869 // function type is incomplete.
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000870 Ty = CGM.PtrDiffTy;
John McCalla1dee5302010-08-22 10:59:02 +0000871 }
John McCall2979fe02011-04-12 00:42:48 +0000872 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
John McCalla1dee5302010-08-22 10:59:02 +0000873
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000874 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
Mark Seabornedf0d382013-07-24 16:25:13 +0000875 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
876 (UseARMMethodPtrABI ? 2 : 1) *
Richard Smithdafff942012-01-14 04:30:29 +0000877 ThisAdjustment.getQuantity());
John McCalla1dee5302010-08-22 10:59:02 +0000878 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000879
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000880 return llvm::ConstantStruct::getAnon(MemPtr);
John McCall1c456c82010-08-22 06:43:33 +0000881}
882
Richard Smithdafff942012-01-14 04:30:29 +0000883llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
884 QualType MPType) {
885 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
886 const ValueDecl *MPD = MP.getMemberPointerDecl();
887 if (!MPD)
888 return EmitNullMemberPointer(MPT);
889
Reid Kleckner452abac2013-05-09 21:01:17 +0000890 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
Richard Smithdafff942012-01-14 04:30:29 +0000891
892 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
893 return BuildMemberPointer(MD, ThisAdjustment);
894
895 CharUnits FieldOffset =
896 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
897 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
898}
899
John McCall131d97d2010-08-22 08:30:07 +0000900/// The comparison algorithm is pretty easy: the member pointers are
901/// the same if they're either bitwise identical *or* both null.
902///
903/// ARM is different here only because null-ness is more complicated.
904llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000905ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
906 llvm::Value *L,
907 llvm::Value *R,
908 const MemberPointerType *MPT,
909 bool Inequality) {
John McCall131d97d2010-08-22 08:30:07 +0000910 CGBuilderTy &Builder = CGF.Builder;
911
John McCall131d97d2010-08-22 08:30:07 +0000912 llvm::ICmpInst::Predicate Eq;
913 llvm::Instruction::BinaryOps And, Or;
914 if (Inequality) {
915 Eq = llvm::ICmpInst::ICMP_NE;
916 And = llvm::Instruction::Or;
917 Or = llvm::Instruction::And;
918 } else {
919 Eq = llvm::ICmpInst::ICMP_EQ;
920 And = llvm::Instruction::And;
921 Or = llvm::Instruction::Or;
922 }
923
John McCall7a9aac22010-08-23 01:21:21 +0000924 // Member data pointers are easy because there's a unique null
925 // value, so it just comes down to bitwise equality.
926 if (MPT->isMemberDataPointer())
927 return Builder.CreateICmp(Eq, L, R);
928
929 // For member function pointers, the tautologies are more complex.
930 // The Itanium tautology is:
John McCall61a14882010-08-23 06:56:36 +0000931 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
John McCall7a9aac22010-08-23 01:21:21 +0000932 // The ARM tautology is:
John McCall61a14882010-08-23 06:56:36 +0000933 // (L == R) <==> (L.ptr == R.ptr &&
934 // (L.adj == R.adj ||
935 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
John McCall7a9aac22010-08-23 01:21:21 +0000936 // The inequality tautologies have exactly the same structure, except
937 // applying De Morgan's laws.
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000938
John McCall7a9aac22010-08-23 01:21:21 +0000939 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
940 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
941
John McCall131d97d2010-08-22 08:30:07 +0000942 // This condition tests whether L.ptr == R.ptr. This must always be
943 // true for equality to hold.
944 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
945
946 // This condition, together with the assumption that L.ptr == R.ptr,
947 // tests whether the pointers are both null. ARM imposes an extra
948 // condition.
949 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
950 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
951
952 // This condition tests whether L.adj == R.adj. If this isn't
953 // true, the pointers are unequal unless they're both null.
John McCalla1dee5302010-08-22 10:59:02 +0000954 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
955 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +0000956 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
957
958 // Null member function pointers on ARM clear the low bit of Adj,
959 // so the zero condition has to check that neither low bit is set.
Mark Seabornedf0d382013-07-24 16:25:13 +0000960 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +0000961 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
962
963 // Compute (l.adj | r.adj) & 1 and test it against zero.
964 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
965 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
966 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
967 "cmp.or.adj");
968 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
969 }
970
971 // Tie together all our conditions.
972 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
973 Result = Builder.CreateBinOp(And, PtrEq, Result,
974 Inequality ? "memptr.ne" : "memptr.eq");
975 return Result;
976}
977
978llvm::Value *
John McCall7a9aac22010-08-23 01:21:21 +0000979ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
980 llvm::Value *MemPtr,
981 const MemberPointerType *MPT) {
John McCall131d97d2010-08-22 08:30:07 +0000982 CGBuilderTy &Builder = CGF.Builder;
John McCall7a9aac22010-08-23 01:21:21 +0000983
984 /// For member data pointers, this is just a check against -1.
985 if (MPT->isMemberDataPointer()) {
Reid Kleckner9cffbc12013-03-22 16:13:10 +0000986 assert(MemPtr->getType() == CGM.PtrDiffTy);
John McCall7a9aac22010-08-23 01:21:21 +0000987 llvm::Value *NegativeOne =
988 llvm::Constant::getAllOnesValue(MemPtr->getType());
989 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
990 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000991
Daniel Dunbar914bc412011-04-19 23:10:47 +0000992 // In Itanium, a member function pointer is not null if 'ptr' is not null.
John McCalla1dee5302010-08-22 10:59:02 +0000993 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
John McCall131d97d2010-08-22 08:30:07 +0000994
995 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
996 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
997
Daniel Dunbar914bc412011-04-19 23:10:47 +0000998 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
999 // (the virtual bit) is set.
Mark Seabornedf0d382013-07-24 16:25:13 +00001000 if (UseARMMethodPtrABI) {
John McCall131d97d2010-08-22 08:30:07 +00001001 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
John McCalla1dee5302010-08-22 10:59:02 +00001002 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
John McCall131d97d2010-08-22 08:30:07 +00001003 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
Daniel Dunbar914bc412011-04-19 23:10:47 +00001004 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1005 "memptr.isvirtual");
1006 Result = Builder.CreateOr(Result, IsVirtual);
John McCall131d97d2010-08-22 08:30:07 +00001007 }
1008
1009 return Result;
1010}
John McCall1c456c82010-08-22 06:43:33 +00001011
Reid Kleckner40ca9132014-05-13 22:05:45 +00001012bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1013 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1014 if (!RD)
1015 return false;
1016
Richard Smith96cd6712017-08-16 01:49:53 +00001017 // If C++ prohibits us from making a copy, return by address.
Richard Smithf667ad52017-08-26 01:04:35 +00001018 if (passClassIndirect(RD)) {
John McCall7f416cc2015-09-08 08:05:57 +00001019 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1020 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner40ca9132014-05-13 22:05:45 +00001021 return true;
1022 }
Reid Kleckner40ca9132014-05-13 22:05:45 +00001023 return false;
1024}
1025
John McCall614dbdc2010-08-22 21:01:12 +00001026/// The Itanium ABI requires non-zero initialization only for data
1027/// member pointers, for which '0' is a valid offset.
1028bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
David Majnemer5fd33e02015-04-24 01:25:08 +00001029 return MPT->isMemberFunctionPointer();
John McCall84fa5102010-08-22 04:16:24 +00001030}
John McCall5d865c322010-08-31 07:33:07 +00001031
John McCall82fb8922012-09-25 10:10:39 +00001032/// The Itanium ABI always places an offset to the complete object
1033/// at entry -2 in the vtable.
David Majnemer08681372014-11-01 07:37:17 +00001034void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1035 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001036 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001037 QualType ElementType,
1038 const CXXDestructorDecl *Dtor) {
1039 bool UseGlobalDelete = DE->isGlobalDelete();
David Majnemer0c0b6d92014-10-31 20:09:12 +00001040 if (UseGlobalDelete) {
1041 // Derive the complete-object pointer, which is what we need
1042 // to pass to the deallocation function.
John McCall82fb8922012-09-25 10:10:39 +00001043
David Majnemer0c0b6d92014-10-31 20:09:12 +00001044 // Grab the vtable pointer as an intptr_t*.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001045 auto *ClassDecl =
1046 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1047 llvm::Value *VTable =
1048 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
John McCall82fb8922012-09-25 10:10:39 +00001049
David Majnemer0c0b6d92014-10-31 20:09:12 +00001050 // Track back to entry -2 and pull out the offset there.
1051 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1052 VTable, -2, "complete-offset.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001053 llvm::Value *Offset =
1054 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
David Majnemer0c0b6d92014-10-31 20:09:12 +00001055
1056 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +00001057 llvm::Value *CompletePtr =
1058 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001059 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1060
1061 // If we're supposed to call the global delete, make sure we do so
1062 // even if the destructor throws.
David Majnemer08681372014-11-01 07:37:17 +00001063 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1064 ElementType);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001065 }
1066
1067 // FIXME: Provide a source location here even though there's no
1068 // CXXMemberCallExpr for dtor call.
1069 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1070 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1071
1072 if (UseGlobalDelete)
1073 CGF.PopCleanupBlock();
John McCall82fb8922012-09-25 10:10:39 +00001074}
1075
David Majnemer442d0a22014-11-25 07:20:20 +00001076void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1077 // void __cxa_rethrow();
1078
1079 llvm::FunctionType *FTy =
1080 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1081
1082 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1083
1084 if (isNoReturn)
1085 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1086 else
1087 CGF.EmitRuntimeCallOrInvoke(Fn);
1088}
1089
David Majnemer7c237072015-03-05 00:46:22 +00001090static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1091 // void *__cxa_allocate_exception(size_t thrown_size);
1092
1093 llvm::FunctionType *FTy =
1094 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1095
1096 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1097}
1098
1099static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1100 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1101 // void (*dest) (void *));
1102
1103 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1104 llvm::FunctionType *FTy =
1105 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1106
1107 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1108}
1109
1110void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1111 QualType ThrowType = E->getSubExpr()->getType();
1112 // Now allocate the exception object.
1113 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1114 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1115
1116 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1117 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1118 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1119
John McCall7f416cc2015-09-08 08:05:57 +00001120 CharUnits ExnAlign = getAlignmentOfExnObject();
1121 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
David Majnemer7c237072015-03-05 00:46:22 +00001122
1123 // Now throw the exception.
1124 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1125 /*ForEH=*/true);
1126
1127 // The address of the destructor. If the exception type has a
1128 // trivial destructor (or isn't a record), we just pass null.
1129 llvm::Constant *Dtor = nullptr;
1130 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1131 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1132 if (!Record->hasTrivialDestructor()) {
1133 CXXDestructorDecl *DtorD = Record->getDestructor();
1134 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1135 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1136 }
1137 }
1138 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1139
1140 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1141 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1142}
1143
David Majnemer1162d252014-06-22 19:05:33 +00001144static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1145 // void *__dynamic_cast(const void *sub,
1146 // const abi::__class_type_info *src,
1147 // const abi::__class_type_info *dst,
1148 // std::ptrdiff_t src2dst_offset);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001149
David Majnemer1162d252014-06-22 19:05:33 +00001150 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001151 llvm::Type *PtrDiffTy =
David Majnemer1162d252014-06-22 19:05:33 +00001152 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1153
1154 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1155
1156 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1157
1158 // Mark the function as nounwind readonly.
1159 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1160 llvm::Attribute::ReadOnly };
Reid Klecknerde864822017-03-21 16:57:30 +00001161 llvm::AttributeList Attrs = llvm::AttributeList::get(
1162 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
David Majnemer1162d252014-06-22 19:05:33 +00001163
1164 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1165}
1166
1167static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1168 // void __cxa_bad_cast();
1169 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1170 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1171}
1172
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001173/// Compute the src2dst_offset hint as described in the
David Majnemer1162d252014-06-22 19:05:33 +00001174/// Itanium C++ ABI [2.9.7]
1175static CharUnits computeOffsetHint(ASTContext &Context,
1176 const CXXRecordDecl *Src,
1177 const CXXRecordDecl *Dst) {
1178 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1179 /*DetectVirtual=*/false);
1180
1181 // If Dst is not derived from Src we can skip the whole computation below and
1182 // return that Src is not a public base of Dst. Record all inheritance paths.
1183 if (!Dst->isDerivedFrom(Src, Paths))
1184 return CharUnits::fromQuantity(-2ULL);
1185
1186 unsigned NumPublicPaths = 0;
1187 CharUnits Offset;
1188
1189 // Now walk all possible inheritance paths.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001190 for (const CXXBasePath &Path : Paths) {
1191 if (Path.Access != AS_public) // Ignore non-public inheritance.
David Majnemer1162d252014-06-22 19:05:33 +00001192 continue;
1193
1194 ++NumPublicPaths;
1195
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001196 for (const CXXBasePathElement &PathElement : Path) {
David Majnemer1162d252014-06-22 19:05:33 +00001197 // If the path contains a virtual base class we can't give any hint.
1198 // -1: no hint.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001199 if (PathElement.Base->isVirtual())
David Majnemer1162d252014-06-22 19:05:33 +00001200 return CharUnits::fromQuantity(-1ULL);
1201
1202 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1203 continue;
1204
1205 // Accumulate the base class offsets.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001206 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1207 Offset += L.getBaseClassOffset(
1208 PathElement.Base->getType()->getAsCXXRecordDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001209 }
1210 }
1211
1212 // -2: Src is not a public base of Dst.
1213 if (NumPublicPaths == 0)
1214 return CharUnits::fromQuantity(-2ULL);
1215
1216 // -3: Src is a multiple public base type but never a virtual base type.
1217 if (NumPublicPaths > 1)
1218 return CharUnits::fromQuantity(-3ULL);
1219
1220 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1221 // Return the offset of Src from the origin of Dst.
1222 return Offset;
1223}
1224
1225static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1226 // void __cxa_bad_typeid();
1227 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1228
1229 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1230}
1231
1232bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1233 QualType SrcRecordTy) {
1234 return IsDeref;
1235}
1236
1237void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1238 llvm::Value *Fn = getBadTypeidFn(CGF);
1239 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1240 CGF.Builder.CreateUnreachable();
1241}
1242
1243llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1244 QualType SrcRecordTy,
John McCall7f416cc2015-09-08 08:05:57 +00001245 Address ThisPtr,
David Majnemer1162d252014-06-22 19:05:33 +00001246 llvm::Type *StdTypeInfoPtrTy) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001247 auto *ClassDecl =
1248 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001249 llvm::Value *Value =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001250 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001251
1252 // Load the type info.
1253 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001254 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
David Majnemer1162d252014-06-22 19:05:33 +00001255}
1256
1257bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1258 QualType SrcRecordTy) {
1259 return SrcIsPtr;
1260}
1261
1262llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
John McCall7f416cc2015-09-08 08:05:57 +00001263 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00001264 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1265 llvm::Type *PtrDiffLTy =
1266 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1267 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1268
1269 llvm::Value *SrcRTTI =
1270 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1271 llvm::Value *DestRTTI =
1272 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1273
1274 // Compute the offset hint.
1275 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1276 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1277 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1278 PtrDiffLTy,
1279 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1280
1281 // Emit the call to __dynamic_cast.
John McCall7f416cc2015-09-08 08:05:57 +00001282 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001283 Value = CGF.EmitCastToVoidPtr(Value);
1284
1285 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1286 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1287 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1288
1289 /// C++ [expr.dynamic.cast]p9:
1290 /// A failed cast to reference type throws std::bad_cast
1291 if (DestTy->isReferenceType()) {
1292 llvm::BasicBlock *BadCastBlock =
1293 CGF.createBasicBlock("dynamic_cast.bad_cast");
1294
1295 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1296 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1297
1298 CGF.EmitBlock(BadCastBlock);
1299 EmitBadCastCall(CGF);
1300 }
1301
1302 return Value;
1303}
1304
1305llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001306 Address ThisAddr,
David Majnemer1162d252014-06-22 19:05:33 +00001307 QualType SrcRecordTy,
1308 QualType DestTy) {
1309 llvm::Type *PtrDiffLTy =
1310 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1311 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1312
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001313 auto *ClassDecl =
1314 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
David Majnemer1162d252014-06-22 19:05:33 +00001315 // Get the vtable pointer.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001316 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1317 ClassDecl);
David Majnemer1162d252014-06-22 19:05:33 +00001318
1319 // Get the offset-to-top from the vtable.
1320 llvm::Value *OffsetToTop =
1321 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
John McCall7f416cc2015-09-08 08:05:57 +00001322 OffsetToTop =
1323 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1324 "offset.to.top");
David Majnemer1162d252014-06-22 19:05:33 +00001325
1326 // Finally, add the offset to the pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001327 llvm::Value *Value = ThisAddr.getPointer();
David Majnemer1162d252014-06-22 19:05:33 +00001328 Value = CGF.EmitCastToVoidPtr(Value);
1329 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1330
1331 return CGF.Builder.CreateBitCast(Value, DestLTy);
1332}
1333
1334bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1335 llvm::Value *Fn = getBadCastFn(CGF);
1336 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1337 CGF.Builder.CreateUnreachable();
1338 return true;
1339}
1340
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001341llvm::Value *
1342ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001343 Address This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001344 const CXXRecordDecl *ClassDecl,
1345 const CXXRecordDecl *BaseClassDecl) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001346 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001347 CharUnits VBaseOffsetOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001348 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1349 BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001350
1351 llvm::Value *VBaseOffsetPtr =
1352 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1353 "vbase.offset.ptr");
1354 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1355 CGM.PtrDiffTy->getPointerTo());
1356
1357 llvm::Value *VBaseOffset =
John McCall7f416cc2015-09-08 08:05:57 +00001358 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1359 "vbase.offset");
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001360
1361 return VBaseOffset;
1362}
1363
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001364void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1365 // Just make sure we're in sync with TargetCXXABI.
1366 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1367
Rafael Espindolac3cde362013-12-09 14:51:17 +00001368 // The constructor used for constructing this as a base class;
1369 // ignores virtual bases.
1370 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1371
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001372 // The constructor used for constructing this as a complete class;
Nico Weber4c2ffb22015-01-07 05:25:05 +00001373 // constructs the virtual bases, then calls the base constructor.
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001374 if (!D->getParent()->isAbstract()) {
1375 // We don't need to emit the complete ctor if the class is abstract.
1376 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1377 }
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00001378}
1379
George Burgess IVf203dbf2017-02-22 20:28:02 +00001380CGCXXABI::AddedStructorArgs
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001381ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1382 SmallVectorImpl<CanQualType> &ArgTys) {
John McCall9bca9232010-09-02 10:25:57 +00001383 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001384
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001385 // All parameters are already in place except VTT, which goes after 'this'.
1386 // These are Clang types, so we don't need to worry about sret yet.
John McCall5d865c322010-08-31 07:33:07 +00001387
1388 // Check if we need to add a VTT parameter (which has type void **).
George Burgess IVf203dbf2017-02-22 20:28:02 +00001389 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001390 ArgTys.insert(ArgTys.begin() + 1,
1391 Context.getPointerType(Context.VoidPtrTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001392 return AddedStructorArgs::prefix(1);
1393 }
1394 return AddedStructorArgs{};
John McCall5d865c322010-08-31 07:33:07 +00001395}
1396
Reid Klecknere7de47e2013-07-22 13:51:44 +00001397void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
Rafael Espindolac3cde362013-12-09 14:51:17 +00001398 // The destructor used for destructing this as a base class; ignores
1399 // virtual bases.
1400 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001401
1402 // The destructor used for destructing this as a most-derived class;
1403 // call the base destructor and then destructs any virtual bases.
1404 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1405
Rafael Espindolac3cde362013-12-09 14:51:17 +00001406 // The destructor in a virtual table is always a 'deleting'
1407 // destructor, which calls the complete destructor and then uses the
1408 // appropriate operator delete.
1409 if (D->isVirtual())
1410 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
Reid Klecknere7de47e2013-07-22 13:51:44 +00001411}
1412
Reid Kleckner89077a12013-12-17 19:46:40 +00001413void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1414 QualType &ResTy,
1415 FunctionArgList &Params) {
John McCall5d865c322010-08-31 07:33:07 +00001416 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +00001417 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
John McCall5d865c322010-08-31 07:33:07 +00001418
1419 // Check if we need a VTT parameter as well.
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001420 if (NeedsVTTParameter(CGF.CurGD)) {
John McCall9bca9232010-09-02 10:25:57 +00001421 ASTContext &Context = getContext();
John McCall5d865c322010-08-31 07:33:07 +00001422
1423 // FIXME: avoid the fake decl
1424 QualType T = Context.getPointerType(Context.VoidPtrTy);
Alexey Bataev56223232017-06-09 13:40:18 +00001425 auto *VTTDecl = ImplicitParamDecl::Create(
1426 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1427 T, ImplicitParamDecl::CXXVTT);
Reid Kleckner89077a12013-12-17 19:46:40 +00001428 Params.insert(Params.begin() + 1, VTTDecl);
Reid Kleckner2af6d732013-12-13 00:09:59 +00001429 getStructorImplicitParamDecl(CGF) = VTTDecl;
John McCall5d865c322010-08-31 07:33:07 +00001430 }
1431}
1432
John McCall5d865c322010-08-31 07:33:07 +00001433void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
Justin Lebared4f1722016-07-27 22:04:24 +00001434 // Naked functions have no prolog.
1435 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1436 return;
1437
Reid Kleckner06239e42017-11-16 19:09:36 +00001438 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001439 /// adjustments are required, because they are all handled by thunks.
Reid Kleckner06239e42017-11-16 19:09:36 +00001440 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
John McCall5d865c322010-08-31 07:33:07 +00001441
1442 /// Initialize the 'vtt' slot if needed.
Reid Kleckner2af6d732013-12-13 00:09:59 +00001443 if (getStructorImplicitParamDecl(CGF)) {
1444 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1445 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
John McCall5d865c322010-08-31 07:33:07 +00001446 }
John McCall5d865c322010-08-31 07:33:07 +00001447
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001448 /// If this is a function that the ABI specifies returns 'this', initialize
1449 /// the return slot to 'this' at the start of the function.
1450 ///
1451 /// Unlike the setting of return types, this is done within the ABI
1452 /// implementation instead of by clients of CGCXXABI because:
1453 /// 1) getThisValue is currently protected
1454 /// 2) in theory, an ABI could implement 'this' returns some other way;
1455 /// HasThisReturn only specifies a contract, not the implementation
John McCall5d865c322010-08-31 07:33:07 +00001456 if (HasThisReturn(CGF.CurGD))
Eli Friedman9fbeba02012-02-11 02:57:39 +00001457 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
John McCall5d865c322010-08-31 07:33:07 +00001458}
1459
George Burgess IVf203dbf2017-02-22 20:28:02 +00001460CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
Reid Kleckner89077a12013-12-17 19:46:40 +00001461 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1462 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1463 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
George Burgess IVf203dbf2017-02-22 20:28:02 +00001464 return AddedStructorArgs{};
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001465
Reid Kleckner89077a12013-12-17 19:46:40 +00001466 // Insert the implicit 'vtt' argument as the second argument.
1467 llvm::Value *VTT =
1468 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1469 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
Yaxun Liu5b330e82018-03-15 15:25:19 +00001470 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
George Burgess IVf203dbf2017-02-22 20:28:02 +00001471 return AddedStructorArgs::prefix(1); // Added one arg.
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001472}
1473
1474void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1475 const CXXDestructorDecl *DD,
1476 CXXDtorType Type, bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001477 bool Delegating, Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001478 GlobalDecl GD(DD, Type);
1479 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1480 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1481
John McCallb92ab1a2016-10-26 23:46:34 +00001482 CGCallee Callee;
1483 if (getContext().getLangOpts().AppleKext &&
1484 Type != Dtor_Base && DD->isVirtual())
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001485 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
John McCallb92ab1a2016-10-26 23:46:34 +00001486 else
1487 Callee =
1488 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1489 DD);
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001490
John McCall7f416cc2015-09-08 08:05:57 +00001491 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
Richard Smith762672a2016-09-28 19:09:10 +00001492 This.getPointer(), VTT, VTTTy,
1493 nullptr, nullptr);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001494}
1495
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001496void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1497 const CXXRecordDecl *RD) {
1498 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1499 if (VTable->hasInitializer())
1500 return;
1501
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001502 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001503 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1504 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
David Majnemerd905da42014-07-01 20:30:31 +00001505 llvm::Constant *RTTI =
1506 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001507
1508 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +00001509 ConstantInitBuilder Builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001510 auto Components = Builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +00001511 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1512 Components.finishAndSetAsInitializer(VTable);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001513
1514 // Set the correct linkage.
1515 VTable->setLinkage(Linkage);
1516
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001517 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1518 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00001519
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001520 // Set the right visibility.
Rafael Espindola699f5d62018-02-07 22:15:33 +00001521 CGM.setGVProperties(VTable, RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001522
Benjamin Kramer5d34a2b2014-09-10 12:50:59 +00001523 // Use pointer alignment for the vtable. Otherwise we would align them based
1524 // on the size of the initializer which doesn't make sense as only single
1525 // values are read.
1526 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1527 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1528
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001529 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1530 // we will emit the typeinfo for the fundamental types. This is the
1531 // same behaviour as GCC.
1532 const DeclContext *DC = RD->getDeclContext();
1533 if (RD->getIdentifier() &&
1534 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1535 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1536 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1537 DC->getParent()->isTranslationUnit())
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00001538 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001539
Evgeniy Stepanov93987df2016-01-23 01:20:18 +00001540 if (!VTable->isDeclarationForLinker())
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001541 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001542}
1543
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001544bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1545 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1546 if (Vptr.NearestVBase == nullptr)
1547 return false;
1548 return NeedsVTTParameter(CGF.CurGD);
Piotr Padlewski255652e2015-09-09 22:20:28 +00001549}
1550
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001551llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1552 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1553 const CXXRecordDecl *NearestVBase) {
1554
1555 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1556 NeedsVTTParameter(CGF.CurGD)) {
1557 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1558 NearestVBase);
1559 }
1560 return getVTableAddressPoint(Base, VTableClass);
1561}
1562
1563llvm::Constant *
1564ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1565 const CXXRecordDecl *VTableClass) {
1566 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001567
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001568 // Find the appropriate vtable within the vtable group, and the address point
1569 // within that vtable.
1570 VTableLayout::AddressPointLocation AddressPoint =
1571 CGM.getItaniumVTableContext()
1572 .getVTableLayout(VTableClass)
1573 .getAddressPoint(Base);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001574 llvm::Value *Indices[] = {
Peter Collingbourne4e6a5402016-03-14 19:07:10 +00001575 llvm::ConstantInt::get(CGM.Int32Ty, 0),
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001576 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1577 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001578 };
1579
Peter Collingbourne25a2b702016-12-13 20:50:44 +00001580 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1581 Indices, /*InBounds=*/true,
1582 /*InRangeIndex=*/1);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001583}
1584
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001585llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1586 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1587 const CXXRecordDecl *NearestVBase) {
1588 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1589 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1590
1591 // Get the secondary vpointer index.
1592 uint64_t VirtualPointerIndex =
1593 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1594
1595 /// Load the VTT.
1596 llvm::Value *VTT = CGF.LoadCXXVTT();
1597 if (VirtualPointerIndex)
1598 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1599
1600 // And load the address point from the VTT.
1601 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1602}
1603
1604llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1605 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1606 return getVTableAddressPoint(Base, VTableClass);
1607}
1608
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001609llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1610 CharUnits VPtrOffset) {
1611 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1612
1613 llvm::GlobalVariable *&VTable = VTables[RD];
1614 if (VTable)
1615 return VTable;
1616
Eric Christopherd160c502016-01-29 01:35:53 +00001617 // Queue up this vtable for possible deferred emission.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001618 CGM.addDeferredVTable(RD);
1619
Yaron Kerene46f7ed2015-07-29 14:21:47 +00001620 SmallString<256> Name;
1621 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00001622 getMangleContext().mangleCXXVTable(RD, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001623
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001624 const VTableLayout &VTLayout =
1625 CGM.getItaniumVTableContext().getVTableLayout(RD);
1626 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001627
1628 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001629 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001630 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Hans Wennborgda24e9c2014-06-02 23:13:03 +00001631
Rafael Espindola922f2aa2018-02-23 19:30:48 +00001632 CGM.setGVProperties(VTable, RD);
1633
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001634 return VTable;
1635}
1636
John McCall9831b842018-02-06 18:52:44 +00001637CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1638 GlobalDecl GD,
1639 Address This,
1640 llvm::Type *Ty,
1641 SourceLocation Loc) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001642 Ty = Ty->getPointerTo()->getPointerTo();
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001643 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1644 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001645
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001646 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
John McCall9831b842018-02-06 18:52:44 +00001647 llvm::Value *VFunc;
1648 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1649 VFunc = CGF.EmitVTableTypeCheckedLoad(
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001650 MethodDecl->getParent(), VTable,
1651 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
John McCall9831b842018-02-06 18:52:44 +00001652 } else {
1653 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00001654
John McCall9831b842018-02-06 18:52:44 +00001655 llvm::Value *VFuncPtr =
1656 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1657 auto *VFuncLoad =
1658 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
Piotr Padlewski77cc9622016-10-29 15:28:30 +00001659
John McCall9831b842018-02-06 18:52:44 +00001660 // Add !invariant.load md to virtual function load to indicate that
1661 // function didn't change inside vtable.
1662 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1663 // help in devirtualization because it will only matter if we will have 2
1664 // the same virtual function loads from the same vtable load, which won't
1665 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1666 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1667 CGM.getCodeGenOpts().StrictVTablePointers)
1668 VFuncLoad->setMetadata(
1669 llvm::LLVMContext::MD_invariant_load,
1670 llvm::MDNode::get(CGM.getLLVMContext(),
1671 llvm::ArrayRef<llvm::Metadata *>()));
1672 VFunc = VFuncLoad;
1673 }
John McCallb92ab1a2016-10-26 23:46:34 +00001674
Reid Kleckner138ab492018-05-17 18:12:18 +00001675 CGCallee Callee(MethodDecl->getCanonicalDecl(), VFunc);
John McCall9831b842018-02-06 18:52:44 +00001676 return Callee;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001677}
1678
David Majnemer0c0b6d92014-10-31 20:09:12 +00001679llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1680 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
John McCall7f416cc2015-09-08 08:05:57 +00001681 Address This, const CXXMemberCallExpr *CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001682 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001683 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1684
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001685 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1686 Dtor, getFromDtorType(DtorType));
George Burgess IV00f70bd2018-03-01 05:43:23 +00001687 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
John McCallb92ab1a2016-10-26 23:46:34 +00001688 CGCallee Callee =
Peter Collingbourneea211002018-02-05 23:09:13 +00001689 CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001690
John McCall7f416cc2015-09-08 08:05:57 +00001691 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1692 This.getPointer(), /*ImplicitParam=*/nullptr,
Richard Smith762672a2016-09-28 19:09:10 +00001693 QualType(), CE, nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +00001694 return nullptr;
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001695}
1696
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001697void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001698 CodeGenVTables &VTables = CGM.getVTables();
1699 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001700 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001701}
1702
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001703bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001704 // We don't emit available_externally vtables if we are in -fapple-kext mode
1705 // because kext mode does not permit devirtualization.
1706 if (CGM.getLangOpts().AppleKext)
1707 return false;
1708
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001709 // If we don't have any not emitted inline virtual function, and if vtable is
1710 // not hidden, then we are safe to emit available_externally copy of vtable.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001711 // FIXME we can still emit a copy of the vtable if we
1712 // can emit definition of the inline functions.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001713 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001714}
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001715static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001716 Address InitialPtr,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001717 int64_t NonVirtualAdjustment,
1718 int64_t VirtualAdjustment,
1719 bool IsReturnAdjustment) {
1720 if (!NonVirtualAdjustment && !VirtualAdjustment)
John McCall7f416cc2015-09-08 08:05:57 +00001721 return InitialPtr.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001722
John McCall7f416cc2015-09-08 08:05:57 +00001723 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001724
John McCall7f416cc2015-09-08 08:05:57 +00001725 // In a base-to-derived cast, the non-virtual adjustment is applied first.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001726 if (NonVirtualAdjustment && !IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001727 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1728 CharUnits::fromQuantity(NonVirtualAdjustment));
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001729 }
1730
John McCall7f416cc2015-09-08 08:05:57 +00001731 // Perform the virtual adjustment if we have one.
1732 llvm::Value *ResultPtr;
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001733 if (VirtualAdjustment) {
1734 llvm::Type *PtrDiffTy =
1735 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1736
John McCall7f416cc2015-09-08 08:05:57 +00001737 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001738 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1739
1740 llvm::Value *OffsetPtr =
1741 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1742
1743 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1744
1745 // Load the adjustment offset from the vtable.
John McCall7f416cc2015-09-08 08:05:57 +00001746 llvm::Value *Offset =
1747 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001748
1749 // Adjust our pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001750 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1751 } else {
1752 ResultPtr = V.getPointer();
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001753 }
1754
John McCall7f416cc2015-09-08 08:05:57 +00001755 // In a derived-to-base conversion, the non-virtual adjustment is
1756 // applied second.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001757 if (NonVirtualAdjustment && IsReturnAdjustment) {
John McCall7f416cc2015-09-08 08:05:57 +00001758 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1759 NonVirtualAdjustment);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001760 }
1761
1762 // Cast back to the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001763 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001764}
1765
1766llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001767 Address This,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001768 const ThisAdjustment &TA) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001769 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1770 TA.Virtual.Itanium.VCallOffsetOffset,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001771 /*IsReturnAdjustment=*/false);
1772}
1773
1774llvm::Value *
John McCall7f416cc2015-09-08 08:05:57 +00001775ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001776 const ReturnAdjustment &RA) {
1777 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1778 RA.Virtual.Itanium.VBaseOffsetOffset,
1779 /*IsReturnAdjustment=*/true);
1780}
1781
John McCall5d865c322010-08-31 07:33:07 +00001782void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1783 RValue RV, QualType ResultType) {
1784 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1785 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1786
1787 // Destructor thunks in the ARM ABI have indeterminate results.
John McCall7f416cc2015-09-08 08:05:57 +00001788 llvm::Type *T = CGF.ReturnValue.getElementType();
John McCall5d865c322010-08-31 07:33:07 +00001789 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1790 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1791}
John McCall8ed55a52010-09-02 09:58:18 +00001792
1793/************************** Array allocation cookies **************************/
1794
John McCallb91cd662012-05-01 05:23:51 +00001795CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1796 // The array cookie is a size_t; pad that up to the element alignment.
1797 // The cookie is actually right-justified in that space.
1798 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1799 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001800}
1801
John McCall7f416cc2015-09-08 08:05:57 +00001802Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1803 Address NewPtr,
1804 llvm::Value *NumElements,
1805 const CXXNewExpr *expr,
1806 QualType ElementType) {
John McCallb91cd662012-05-01 05:23:51 +00001807 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001808
John McCall7f416cc2015-09-08 08:05:57 +00001809 unsigned AS = NewPtr.getAddressSpace();
John McCall8ed55a52010-09-02 09:58:18 +00001810
John McCall9bca9232010-09-02 10:25:57 +00001811 ASTContext &Ctx = getContext();
John McCall7f416cc2015-09-08 08:05:57 +00001812 CharUnits SizeSize = CGF.getSizeSize();
John McCall8ed55a52010-09-02 09:58:18 +00001813
1814 // The size of the cookie.
1815 CharUnits CookieSize =
1816 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
John McCallb91cd662012-05-01 05:23:51 +00001817 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
John McCall8ed55a52010-09-02 09:58:18 +00001818
1819 // Compute an offset to the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001820 Address CookiePtr = NewPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001821 CharUnits CookieOffset = CookieSize - SizeSize;
1822 if (!CookieOffset.isZero())
John McCall7f416cc2015-09-08 08:05:57 +00001823 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001824
1825 // Write the number of elements into the appropriate slot.
John McCall7f416cc2015-09-08 08:05:57 +00001826 Address NumElementsPtr =
1827 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001828 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001829
1830 // Handle the array cookie specially in ASan.
Filipe Cabecinhas6f83fa92018-01-02 13:46:12 +00001831 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001832 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
1833 CGM.getCodeGenOpts().SanitizeAddressPoisonClassMemberArrayNewCookie)) {
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001834 // The store to the CookiePtr does not need to be instrumented.
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001835 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1836 llvm::FunctionType *FTy =
John McCall7f416cc2015-09-08 08:05:57 +00001837 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001838 llvm::Constant *F =
1839 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001840 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001841 }
John McCall8ed55a52010-09-02 09:58:18 +00001842
1843 // Finally, compute a pointer to the actual data buffer by skipping
1844 // over the cookie completely.
John McCall7f416cc2015-09-08 08:05:57 +00001845 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001846}
1847
John McCallb91cd662012-05-01 05:23:51 +00001848llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001849 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001850 CharUnits cookieSize) {
1851 // The element size is right-justified in the cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001852 Address numElementsPtr = allocPtr;
1853 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
John McCallb91cd662012-05-01 05:23:51 +00001854 if (!numElementsOffset.isZero())
1855 numElementsPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001856 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
John McCall8ed55a52010-09-02 09:58:18 +00001857
John McCall7f416cc2015-09-08 08:05:57 +00001858 unsigned AS = allocPtr.getAddressSpace();
1859 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001860 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
Kostya Serebryany4a9187a2014-08-29 01:01:32 +00001861 return CGF.Builder.CreateLoad(numElementsPtr);
1862 // In asan mode emit a function call instead of a regular load and let the
1863 // run-time deal with it: if the shadow is properly poisoned return the
1864 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1865 // We can't simply ignore this load using nosanitize metadata because
1866 // the metadata may be lost.
1867 llvm::FunctionType *FTy =
1868 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1869 llvm::Constant *F =
1870 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
John McCall7f416cc2015-09-08 08:05:57 +00001871 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
John McCall8ed55a52010-09-02 09:58:18 +00001872}
1873
John McCallb91cd662012-05-01 05:23:51 +00001874CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
John McCallc19c7062013-01-25 23:36:19 +00001875 // ARM says that the cookie is always:
John McCall8ed55a52010-09-02 09:58:18 +00001876 // struct array_cookie {
1877 // std::size_t element_size; // element_size != 0
1878 // std::size_t element_count;
1879 // };
John McCallc19c7062013-01-25 23:36:19 +00001880 // But the base ABI doesn't give anything an alignment greater than
1881 // 8, so we can dismiss this as typical ABI-author blindness to
1882 // actual language complexity and round up to the element alignment.
1883 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1884 CGM.getContext().getTypeAlignInChars(elementType));
John McCall8ed55a52010-09-02 09:58:18 +00001885}
1886
John McCall7f416cc2015-09-08 08:05:57 +00001887Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1888 Address newPtr,
1889 llvm::Value *numElements,
1890 const CXXNewExpr *expr,
1891 QualType elementType) {
John McCallb91cd662012-05-01 05:23:51 +00001892 assert(requiresArrayCookie(expr));
John McCall8ed55a52010-09-02 09:58:18 +00001893
John McCall8ed55a52010-09-02 09:58:18 +00001894 // The cookie is always at the start of the buffer.
John McCall7f416cc2015-09-08 08:05:57 +00001895 Address cookie = newPtr;
John McCall8ed55a52010-09-02 09:58:18 +00001896
1897 // The first element is the element size.
John McCall7f416cc2015-09-08 08:05:57 +00001898 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
John McCallc19c7062013-01-25 23:36:19 +00001899 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1900 getContext().getTypeSizeInChars(elementType).getQuantity());
1901 CGF.Builder.CreateStore(elementSize, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001902
1903 // The second element is the element count.
John McCall7f416cc2015-09-08 08:05:57 +00001904 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
John McCallc19c7062013-01-25 23:36:19 +00001905 CGF.Builder.CreateStore(numElements, cookie);
John McCall8ed55a52010-09-02 09:58:18 +00001906
1907 // Finally, compute a pointer to the actual data buffer by skipping
1908 // over the cookie completely.
John McCallc19c7062013-01-25 23:36:19 +00001909 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
John McCall7f416cc2015-09-08 08:05:57 +00001910 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001911}
1912
John McCallb91cd662012-05-01 05:23:51 +00001913llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001914 Address allocPtr,
John McCallb91cd662012-05-01 05:23:51 +00001915 CharUnits cookieSize) {
1916 // The number of elements is at offset sizeof(size_t) relative to
1917 // the allocated pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001918 Address numElementsPtr
1919 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
John McCall8ed55a52010-09-02 09:58:18 +00001920
John McCall7f416cc2015-09-08 08:05:57 +00001921 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
John McCallb91cd662012-05-01 05:23:51 +00001922 return CGF.Builder.CreateLoad(numElementsPtr);
John McCall8ed55a52010-09-02 09:58:18 +00001923}
1924
John McCall68ff0372010-09-08 01:44:27 +00001925/*********************** Static local initialization **************************/
1926
1927static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001928 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001929 // int __cxa_guard_acquire(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001930 llvm::FunctionType *FTy =
John McCall68ff0372010-09-08 01:44:27 +00001931 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
Jay Foad5709f7c2011-07-29 13:56:53 +00001932 GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001933 return CGM.CreateRuntimeFunction(
1934 FTy, "__cxa_guard_acquire",
1935 llvm::AttributeList::get(CGM.getLLVMContext(),
1936 llvm::AttributeList::FunctionIndex,
1937 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001938}
1939
1940static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001941 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001942 // void __cxa_guard_release(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001943 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001944 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001945 return CGM.CreateRuntimeFunction(
1946 FTy, "__cxa_guard_release",
1947 llvm::AttributeList::get(CGM.getLLVMContext(),
1948 llvm::AttributeList::FunctionIndex,
1949 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001950}
1951
1952static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
Chris Lattnera5f58b02011-07-09 17:41:47 +00001953 llvm::PointerType *GuardPtrTy) {
John McCall68ff0372010-09-08 01:44:27 +00001954 // void __cxa_guard_abort(__guard *guard_object);
Chris Lattner2192fe52011-07-18 04:24:23 +00001955 llvm::FunctionType *FTy =
Chris Lattnerece04092012-02-07 00:39:47 +00001956 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00001957 return CGM.CreateRuntimeFunction(
1958 FTy, "__cxa_guard_abort",
1959 llvm::AttributeList::get(CGM.getLLVMContext(),
1960 llvm::AttributeList::FunctionIndex,
1961 llvm::Attribute::NoUnwind));
John McCall68ff0372010-09-08 01:44:27 +00001962}
1963
1964namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001965 struct CallGuardAbort final : EHScopeStack::Cleanup {
John McCall68ff0372010-09-08 01:44:27 +00001966 llvm::GlobalVariable *Guard;
Chandler Carruth84537952012-03-30 19:44:53 +00001967 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
John McCall68ff0372010-09-08 01:44:27 +00001968
Craig Topper4f12f102014-03-12 06:41:41 +00001969 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +00001970 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1971 Guard);
John McCall68ff0372010-09-08 01:44:27 +00001972 }
1973 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001974}
John McCall68ff0372010-09-08 01:44:27 +00001975
1976/// The ARM code here follows the Itanium code closely enough that we
1977/// just special-case it at particular places.
John McCallcdf7ef52010-11-06 09:44:32 +00001978void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1979 const VarDecl &D,
John McCallb88a5662012-03-30 21:00:39 +00001980 llvm::GlobalVariable *var,
1981 bool shouldPerformInit) {
John McCall68ff0372010-09-08 01:44:27 +00001982 CGBuilderTy &Builder = CGF.Builder;
John McCallcdf7ef52010-11-06 09:44:32 +00001983
Richard Smith62f19e72016-06-25 00:15:56 +00001984 // Inline variables that weren't instantiated from variable templates have
1985 // partially-ordered initialization within their translation unit.
1986 bool NonTemplateInline =
1987 D.isInline() &&
1988 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1989
1990 // We only need to use thread-safe statics for local non-TLS variables and
1991 // inline variables; other global initialization is always single-threaded
1992 // or (through lazy dynamic loading in multiple threads) unsequenced.
Richard Smithdbf74ba2013-04-14 23:01:42 +00001993 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
Richard Smith62f19e72016-06-25 00:15:56 +00001994 (D.isLocalVarDecl() || NonTemplateInline) &&
1995 !D.getTLSKind();
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001996
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00001997 // If we have a global variable with internal linkage and thread-safe statics
1998 // are disabled, we can just let the guard variable be of type i8.
John McCallb88a5662012-03-30 21:00:39 +00001999 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2000
2001 llvm::IntegerType *guardTy;
John McCall7f416cc2015-09-08 08:05:57 +00002002 CharUnits guardAlignment;
John McCall5aa52592011-06-17 07:33:57 +00002003 if (useInt8GuardVariable) {
John McCallb88a5662012-03-30 21:00:39 +00002004 guardTy = CGF.Int8Ty;
John McCall7f416cc2015-09-08 08:05:57 +00002005 guardAlignment = CharUnits::One();
John McCall5aa52592011-06-17 07:33:57 +00002006 } else {
Tim Northover9bb857a2013-01-31 12:13:10 +00002007 // Guard variables are 64 bits in the generic ABI and size width on ARM
2008 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
John McCall7f416cc2015-09-08 08:05:57 +00002009 if (UseARMGuardVarABI) {
2010 guardTy = CGF.SizeTy;
2011 guardAlignment = CGF.getSizeAlign();
2012 } else {
2013 guardTy = CGF.Int64Ty;
2014 guardAlignment = CharUnits::fromQuantity(
2015 CGM.getDataLayout().getABITypeAlignment(guardTy));
2016 }
Anders Carlssonc5d3ba12011-04-27 04:37:08 +00002017 }
John McCallb88a5662012-03-30 21:00:39 +00002018 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
John McCall68ff0372010-09-08 01:44:27 +00002019
John McCallb88a5662012-03-30 21:00:39 +00002020 // Create the guard variable if we don't already have it (as we
2021 // might if we're double-emitting this function body).
2022 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2023 if (!guard) {
2024 // Mangle the name for the guard.
2025 SmallString<256> guardName;
2026 {
2027 llvm::raw_svector_ostream out(guardName);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002028 getMangleContext().mangleStaticGuardVariable(&D, out);
John McCallb88a5662012-03-30 21:00:39 +00002029 }
John McCall8e7cb6d2010-11-02 21:04:24 +00002030
John McCallb88a5662012-03-30 21:00:39 +00002031 // Create the guard variable with a zero-initializer.
2032 // Just absorb linkage and visibility from the guarded variable.
2033 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2034 false, var->getLinkage(),
2035 llvm::ConstantInt::get(guardTy, 0),
2036 guardName.str());
Rafael Espindola699f5d62018-02-07 22:15:33 +00002037 guard->setDSOLocal(var->isDSOLocal());
John McCallb88a5662012-03-30 21:00:39 +00002038 guard->setVisibility(var->getVisibility());
Richard Smithdbf74ba2013-04-14 23:01:42 +00002039 // If the variable is thread-local, so is its guard variable.
2040 guard->setThreadLocalMode(var->getThreadLocalMode());
John McCall7f416cc2015-09-08 08:05:57 +00002041 guard->setAlignment(guardAlignment.getQuantity());
John McCallb88a5662012-03-30 21:00:39 +00002042
Yaron Keren5bfa1082015-09-03 20:33:29 +00002043 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2044 // group as the associated data object." In practice, this doesn't work for
Dan Gohman839f2152017-01-17 21:46:38 +00002045 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002046 llvm::Comdat *C = var->getComdat();
Yaron Keren5bfa1082015-09-03 20:33:29 +00002047 if (!D.isLocalVarDecl() && C &&
Dan Gohman839f2152017-01-17 21:46:38 +00002048 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2049 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002050 guard->setComdat(C);
Richard Smith62f19e72016-06-25 00:15:56 +00002051 // An inline variable's guard function is run from the per-TU
2052 // initialization function, not via a dedicated global ctor function, so
2053 // we can't put it in a comdat.
2054 if (!NonTemplateInline)
2055 CGF.CurFn->setComdat(C);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002056 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2057 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
Rafael Espindola2ae4b632014-09-19 19:43:18 +00002058 }
2059
John McCallb88a5662012-03-30 21:00:39 +00002060 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2061 }
John McCall87590e62012-03-30 07:09:50 +00002062
John McCall7f416cc2015-09-08 08:05:57 +00002063 Address guardAddr = Address(guard, guardAlignment);
2064
John McCall68ff0372010-09-08 01:44:27 +00002065 // Test whether the variable has completed initialization.
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002066 //
John McCall68ff0372010-09-08 01:44:27 +00002067 // Itanium C++ ABI 3.3.2:
2068 // The following is pseudo-code showing how these functions can be used:
2069 // if (obj_guard.first_byte == 0) {
2070 // if ( __cxa_guard_acquire (&obj_guard) ) {
2071 // try {
2072 // ... initialize the object ...;
2073 // } catch (...) {
2074 // __cxa_guard_abort (&obj_guard);
2075 // throw;
2076 // }
2077 // ... queue object destructor with __cxa_atexit() ...;
2078 // __cxa_guard_release (&obj_guard);
2079 // }
2080 // }
Tim Northovera2ee4332014-03-29 15:09:45 +00002081
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002082 // Load the first byte of the guard variable.
2083 llvm::LoadInst *LI =
John McCall7f416cc2015-09-08 08:05:57 +00002084 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
John McCall68ff0372010-09-08 01:44:27 +00002085
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002086 // Itanium ABI:
2087 // An implementation supporting thread-safety on multiprocessor
2088 // systems must also guarantee that references to the initialized
2089 // object do not occur before the load of the initialization flag.
2090 //
2091 // In LLVM, we do this by marking the load Acquire.
2092 if (threadsafe)
JF Bastien92f4ef12016-04-06 17:26:42 +00002093 LI->setAtomic(llvm::AtomicOrdering::Acquire);
Eli Friedman84d28122011-09-13 22:21:56 +00002094
Justin Bogner0cbb6d82014-04-23 01:50:10 +00002095 // For ARM, we should only check the first bit, rather than the entire byte:
2096 //
2097 // ARM C++ ABI 3.2.3.1:
2098 // To support the potential use of initialization guard variables
2099 // as semaphores that are the target of ARM SWP and LDREX/STREX
2100 // synchronizing instructions we define a static initialization
2101 // guard variable to be a 4-byte aligned, 4-byte word with the
2102 // following inline access protocol.
2103 // #define INITIALIZED 1
2104 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2105 // if (__cxa_guard_acquire(&obj_guard))
2106 // ...
2107 // }
2108 //
2109 // and similarly for ARM64:
2110 //
2111 // ARM64 C++ ABI 3.2.2:
2112 // This ABI instead only specifies the value bit 0 of the static guard
2113 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2114 // variable is not initialized and 1 when it is.
2115 llvm::Value *V =
2116 (UseARMGuardVarABI && !useInt8GuardVariable)
2117 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2118 : LI;
Richard Smithae8d62c2017-07-26 22:01:09 +00002119 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
John McCall68ff0372010-09-08 01:44:27 +00002120
2121 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2122 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2123
2124 // Check if the first byte of the guard variable is zero.
Richard Smithae8d62c2017-07-26 22:01:09 +00002125 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2126 CodeGenFunction::GuardKind::VariableGuard, &D);
John McCall68ff0372010-09-08 01:44:27 +00002127
2128 CGF.EmitBlock(InitCheckBlock);
2129
2130 // Variables used when coping with thread-safe statics and exceptions.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002131 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002132 // Call __cxa_guard_acquire.
2133 llvm::Value *V
John McCall882987f2013-02-28 19:01:20 +00002134 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002135
John McCall68ff0372010-09-08 01:44:27 +00002136 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002137
John McCall68ff0372010-09-08 01:44:27 +00002138 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2139 InitBlock, EndBlock);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002140
John McCall68ff0372010-09-08 01:44:27 +00002141 // Call __cxa_guard_abort along the exceptional edge.
John McCallb88a5662012-03-30 21:00:39 +00002142 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002143
John McCall68ff0372010-09-08 01:44:27 +00002144 CGF.EmitBlock(InitBlock);
2145 }
2146
2147 // Emit the initializer and add a global destructor if appropriate.
John McCallb88a5662012-03-30 21:00:39 +00002148 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
John McCall68ff0372010-09-08 01:44:27 +00002149
John McCall5aa52592011-06-17 07:33:57 +00002150 if (threadsafe) {
John McCall68ff0372010-09-08 01:44:27 +00002151 // Pop the guard-abort cleanup if we pushed one.
2152 CGF.PopCleanupBlock();
2153
2154 // Call __cxa_guard_release. This cannot throw.
John McCall7f416cc2015-09-08 08:05:57 +00002155 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2156 guardAddr.getPointer());
John McCall68ff0372010-09-08 01:44:27 +00002157 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002158 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
John McCall68ff0372010-09-08 01:44:27 +00002159 }
2160
2161 CGF.EmitBlock(EndBlock);
2162}
John McCallc84ed6a2012-05-01 06:13:13 +00002163
2164/// Register a global destructor using __cxa_atexit.
2165static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2166 llvm::Constant *dtor,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002167 llvm::Constant *addr,
2168 bool TLS) {
Bill Wendling95cae882013-05-02 19:18:03 +00002169 const char *Name = "__cxa_atexit";
2170 if (TLS) {
2171 const llvm::Triple &T = CGF.getTarget().getTriple();
Manman Renf93fff22015-11-11 23:08:18 +00002172 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
Bill Wendling95cae882013-05-02 19:18:03 +00002173 }
Richard Smithdbf74ba2013-04-14 23:01:42 +00002174
John McCallc84ed6a2012-05-01 06:13:13 +00002175 // We're assuming that the destructor function is something we can
2176 // reasonably call with the default CC. Go ahead and cast it to the
2177 // right prototype.
2178 llvm::Type *dtorTy =
2179 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2180
2181 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2182 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2183 llvm::FunctionType *atexitTy =
2184 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2185
2186 // Fetch the actual function.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002187 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
John McCallc84ed6a2012-05-01 06:13:13 +00002188 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2189 fn->setDoesNotThrow();
2190
2191 // Create a variable that binds the atexit to this shared object.
2192 llvm::Constant *handle =
Reid Kleckner9de92142017-02-13 18:49:21 +00002193 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2194 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2195 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
John McCallc84ed6a2012-05-01 06:13:13 +00002196
Akira Hatanaka617e2612018-04-17 18:41:52 +00002197 if (!addr)
2198 // addr is null when we are trying to register a dtor annotated with
2199 // __attribute__((destructor)) in a constructor function. Using null here is
2200 // okay because this argument is just passed back to the destructor
2201 // function.
2202 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2203
John McCallc84ed6a2012-05-01 06:13:13 +00002204 llvm::Value *args[] = {
2205 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2206 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2207 handle
2208 };
John McCall882987f2013-02-28 19:01:20 +00002209 CGF.EmitNounwindRuntimeCall(atexit, args);
John McCallc84ed6a2012-05-01 06:13:13 +00002210}
2211
Akira Hatanaka617e2612018-04-17 18:41:52 +00002212void CodeGenModule::registerGlobalDtorsWithAtExit() {
2213 for (const auto I : DtorsUsingAtExit) {
2214 int Priority = I.first;
2215 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
2216
2217 // Create a function that registers destructors that have the same priority.
2218 //
2219 // Since constructor functions are run in non-descending order of their
2220 // priorities, destructors are registered in non-descending order of their
2221 // priorities, and since destructor functions are run in the reverse order
2222 // of their registration, destructor functions are run in non-ascending
2223 // order of their priorities.
2224 CodeGenFunction CGF(*this);
2225 std::string GlobalInitFnName =
2226 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
2227 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
2228 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
2229 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
2230 SourceLocation());
2231 ASTContext &Ctx = getContext();
2232 FunctionDecl *FD = FunctionDecl::Create(
2233 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
2234 &Ctx.Idents.get(GlobalInitFnName), Ctx.VoidTy, nullptr, SC_Static,
2235 false, false);
2236 CGF.StartFunction(GlobalDecl(FD), getContext().VoidTy, GlobalInitFn,
2237 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2238 SourceLocation(), SourceLocation());
2239
2240 for (auto *Dtor : Dtors) {
2241 // Register the destructor function calling __cxa_atexit if it is
2242 // available. Otherwise fall back on calling atexit.
2243 if (getCodeGenOpts().CXAAtExit)
2244 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
2245 else
2246 CGF.registerGlobalDtorWithAtExit(Dtor);
2247 }
2248
2249 CGF.FinishFunction();
2250 AddGlobalCtor(GlobalInitFn, Priority, nullptr);
2251 }
2252}
2253
John McCallc84ed6a2012-05-01 06:13:13 +00002254/// Register a global destructor as best as we know how.
2255void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
Richard Smithdbf74ba2013-04-14 23:01:42 +00002256 const VarDecl &D,
John McCallc84ed6a2012-05-01 06:13:13 +00002257 llvm::Constant *dtor,
2258 llvm::Constant *addr) {
2259 // Use __cxa_atexit if available.
Richard Smithdbf74ba2013-04-14 23:01:42 +00002260 if (CGM.getCodeGenOpts().CXAAtExit)
2261 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2262
2263 if (D.getTLSKind())
2264 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
John McCallc84ed6a2012-05-01 06:13:13 +00002265
2266 // In Apple kexts, we want to add a global destructor entry.
2267 // FIXME: shouldn't this be guarded by some variable?
Richard Smith9c6890a2012-11-01 22:30:59 +00002268 if (CGM.getLangOpts().AppleKext) {
John McCallc84ed6a2012-05-01 06:13:13 +00002269 // Generate a global destructor entry.
2270 return CGM.AddCXXDtorEntry(dtor, addr);
2271 }
2272
David Blaikieebe87e12013-08-27 23:57:18 +00002273 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
John McCallc84ed6a2012-05-01 06:13:13 +00002274}
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002275
David Majnemer9b21c332014-07-11 20:28:10 +00002276static bool isThreadWrapperReplaceable(const VarDecl *VD,
2277 CodeGen::CodeGenModule &CGM) {
2278 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
Manman Renf93fff22015-11-11 23:08:18 +00002279 // Darwin prefers to have references to thread local variables to go through
David Majnemer9b21c332014-07-11 20:28:10 +00002280 // the thread wrapper instead of directly referencing the backing variable.
2281 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002282 CGM.getTarget().getTriple().isOSDarwin();
David Majnemer9b21c332014-07-11 20:28:10 +00002283}
2284
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002285/// Get the appropriate linkage for the wrapper function. This is essentially
David Majnemer4632e1e2014-06-27 16:56:27 +00002286/// the weak form of the variable's linkage; every translation unit which needs
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002287/// the wrapper emits a copy, and we want the linker to merge them.
David Majnemer35ab3282014-06-11 04:08:55 +00002288static llvm::GlobalValue::LinkageTypes
2289getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2290 llvm::GlobalValue::LinkageTypes VarLinkage =
2291 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2292
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002293 // For internal linkage variables, we don't need an external or weak wrapper.
2294 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2295 return VarLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002296
David Majnemer9b21c332014-07-11 20:28:10 +00002297 // If the thread wrapper is replaceable, give it appropriate linkage.
Manman Ren68150262015-11-11 22:42:31 +00002298 if (isThreadWrapperReplaceable(VD, CGM))
2299 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2300 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2301 return VarLinkage;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002302 return llvm::GlobalValue::WeakODRLinkage;
2303}
2304
2305llvm::Function *
2306ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
Alexander Musmanf94c3182014-09-26 06:28:25 +00002307 llvm::Value *Val) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002308 // Mangle the name for the thread_local wrapper function.
2309 SmallString<256> WrapperName;
2310 {
2311 llvm::raw_svector_ostream Out(WrapperName);
2312 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002313 }
2314
Akira Hatanaka26907f92016-01-15 03:34:06 +00002315 // FIXME: If VD is a definition, we should regenerate the function attributes
2316 // before returning.
Alexander Musmanf94c3182014-09-26 06:28:25 +00002317 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002318 return cast<llvm::Function>(V);
2319
Akira Hatanaka26907f92016-01-15 03:34:06 +00002320 QualType RetQT = VD->getType();
2321 if (RetQT->isReferenceType())
2322 RetQT = RetQT.getNonReferenceType();
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002323
John McCallc56a8b32016-03-11 04:30:31 +00002324 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2325 getContext().getPointerType(RetQT), FunctionArgList());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002326
2327 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
David Majnemer35ab3282014-06-11 04:08:55 +00002328 llvm::Function *Wrapper =
2329 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2330 WrapperName.str(), &CGM.getModule());
Akira Hatanaka26907f92016-01-15 03:34:06 +00002331
2332 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2333
2334 if (VD->hasDefinition())
2335 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2336
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002337 // Always resolve references to the wrapper at link time.
Manman Ren68150262015-11-11 22:42:31 +00002338 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2339 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2340 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
Duncan P. N. Exon Smith4434d362014-05-07 22:36:11 +00002341 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
Manman Renb0b3af72015-12-17 00:42:36 +00002342
2343 if (isThreadWrapperReplaceable(VD, CGM)) {
2344 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2345 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2346 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002347 return Wrapper;
2348}
2349
2350void ItaniumCXXABI::EmitThreadLocalInitFuncs(
Richard Smith5a99c492015-12-01 01:10:48 +00002351 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2352 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2353 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002354 llvm::Function *InitFunc = nullptr;
Richard Smithfbe23692017-01-13 00:43:31 +00002355
2356 // Separate initializers into those with ordered (or partially-ordered)
2357 // initialization and those with unordered initialization.
2358 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2359 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2360 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2361 if (isTemplateInstantiation(
2362 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2363 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2364 CXXThreadLocalInits[I];
2365 else
2366 OrderedInits.push_back(CXXThreadLocalInits[I]);
2367 }
2368
2369 if (!OrderedInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +00002370 // Generate a guarded initialization function.
2371 llvm::FunctionType *FTy =
2372 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002373 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2374 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002375 SourceLocation(),
David Majnemerb3341ea2014-10-05 05:05:40 +00002376 /*TLS=*/true);
2377 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2378 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2379 llvm::GlobalVariable::InternalLinkage,
2380 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2381 Guard->setThreadLocal(true);
John McCall7f416cc2015-09-08 08:05:57 +00002382
2383 CharUnits GuardAlign = CharUnits::One();
2384 Guard->setAlignment(GuardAlign.getQuantity());
2385
Richard Smithfbe23692017-01-13 00:43:31 +00002386 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2387 Address(Guard, GuardAlign));
Manman Ren5e5d0462016-03-18 23:35:21 +00002388 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2389 if (CGM.getTarget().getTriple().isOSDarwin()) {
2390 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2391 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2392 }
David Majnemerb3341ea2014-10-05 05:05:40 +00002393 }
Richard Smithfbe23692017-01-13 00:43:31 +00002394
2395 // Emit thread wrappers.
Richard Smith5a99c492015-12-01 01:10:48 +00002396 for (const VarDecl *VD : CXXThreadLocals) {
2397 llvm::GlobalVariable *Var =
2398 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
Richard Smithfbe23692017-01-13 00:43:31 +00002399 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002400
David Majnemer9b21c332014-07-11 20:28:10 +00002401 // Some targets require that all access to thread local variables go through
2402 // the thread wrapper. This means that we cannot attempt to create a thread
2403 // wrapper or a thread helper.
Richard Smithfbe23692017-01-13 00:43:31 +00002404 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2405 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
David Majnemer9b21c332014-07-11 20:28:10 +00002406 continue;
Richard Smithfbe23692017-01-13 00:43:31 +00002407 }
David Majnemer9b21c332014-07-11 20:28:10 +00002408
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002409 // Mangle the name for the thread_local initialization function.
2410 SmallString<256> InitFnName;
2411 {
2412 llvm::raw_svector_ostream Out(InitFnName);
2413 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002414 }
2415
2416 // If we have a definition for the variable, emit the initialization
2417 // function as an alias to the global Init function (if any). Otherwise,
2418 // produce a declaration of the initialization function.
Craig Topper8a13c412014-05-21 05:09:00 +00002419 llvm::GlobalValue *Init = nullptr;
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002420 bool InitIsInitFunc = false;
2421 if (VD->hasDefinition()) {
2422 InitIsInitFunc = true;
Richard Smithfbe23692017-01-13 00:43:31 +00002423 llvm::Function *InitFuncToUse = InitFunc;
2424 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2425 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2426 if (InitFuncToUse)
Rafael Espindola234405b2014-05-17 21:30:14 +00002427 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
Richard Smithfbe23692017-01-13 00:43:31 +00002428 InitFuncToUse);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002429 } else {
2430 // Emit a weak global function referring to the initialization function.
2431 // This function will not exist if the TU defining the thread_local
2432 // variable in question does not need any dynamic initialization for
2433 // its thread_local variables.
2434 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
Richard Smithfbe23692017-01-13 00:43:31 +00002435 Init = llvm::Function::Create(FnTy,
2436 llvm::GlobalVariable::ExternalWeakLinkage,
2437 InitFnName.str(), &CGM.getModule());
John McCallc56a8b32016-03-11 04:30:31 +00002438 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
Akira Hatanaka26907f92016-01-15 03:34:06 +00002439 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002440 }
2441
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002442 if (Init) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002443 Init->setVisibility(Var->getVisibility());
Rafael Espindolaabdb3222018-03-07 23:18:06 +00002444 Init->setDSOLocal(Var->isDSOLocal());
2445 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002446
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002447 llvm::LLVMContext &Context = CGM.getModule().getContext();
2448 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
John McCall7f416cc2015-09-08 08:05:57 +00002449 CGBuilderTy Builder(CGM, Entry);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002450 if (InitIsInitFunc) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002451 if (Init) {
2452 llvm::CallInst *CallVal = Builder.CreateCall(Init);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002453 if (isThreadWrapperReplaceable(VD, CGM)) {
Manman Ren5e5d0462016-03-18 23:35:21 +00002454 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Akira Hatanaka1da9dbb2018-05-29 18:28:49 +00002455 llvm::Function *Fn =
2456 cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
2457 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2458 }
Manman Ren5e5d0462016-03-18 23:35:21 +00002459 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002460 } else {
2461 // Don't know whether we have an init function. Call it if it exists.
2462 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2463 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2464 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2465 Builder.CreateCondBr(Have, InitBB, ExitBB);
2466
2467 Builder.SetInsertPoint(InitBB);
David Blaikie4ba525b2015-07-14 17:27:39 +00002468 Builder.CreateCall(Init);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002469 Builder.CreateBr(ExitBB);
2470
2471 Builder.SetInsertPoint(ExitBB);
2472 }
2473
2474 // For a reference, the result of the wrapper function is a pointer to
2475 // the referenced object.
2476 llvm::Value *Val = Var;
2477 if (VD->getType()->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002478 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2479 Val = Builder.CreateAlignedLoad(Val, Align);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002480 }
Alexander Musmanf94c3182014-09-26 06:28:25 +00002481 if (Val->getType() != Wrapper->getReturnType())
2482 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2483 Val, Wrapper->getReturnType(), "");
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002484 Builder.CreateRet(Val);
2485 }
2486}
2487
Richard Smith0f383742014-03-26 22:48:22 +00002488LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2489 const VarDecl *VD,
2490 QualType LValType) {
Richard Smith5a99c492015-12-01 01:10:48 +00002491 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
Alexander Musmanf94c3182014-09-26 06:28:25 +00002492 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002493
Manman Renb0b3af72015-12-17 00:42:36 +00002494 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
Saleem Abdulrasool4a7130a2016-08-01 21:31:24 +00002495 CallVal->setCallingConv(Wrapper->getCallingConv());
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002496
2497 LValue LV;
2498 if (VD->getType()->isReferenceType())
Manman Renb0b3af72015-12-17 00:42:36 +00002499 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002500 else
Manman Renb0b3af72015-12-17 00:42:36 +00002501 LV = CGF.MakeAddrLValue(CallVal, LValType,
2502 CGF.getContext().getDeclAlign(VD));
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002503 // FIXME: need setObjCGCLValueClass?
2504 return LV;
2505}
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002506
2507/// Return whether the given global decl needs a VTT parameter, which it does
2508/// if it's a base constructor or destructor with virtual bases.
2509bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2510 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002511
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002512 // We don't have any virtual bases, just return early.
2513 if (!MD->getParent()->getNumVBases())
2514 return false;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002515
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002516 // Check if we have a base constructor.
2517 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2518 return true;
2519
2520 // Check if we have a base destructor.
2521 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2522 return true;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002523
Peter Collingbourne66f82e62013-06-28 20:45:28 +00002524 return false;
2525}
David Majnemere2cb8d12014-07-07 06:20:47 +00002526
2527namespace {
2528class ItaniumRTTIBuilder {
2529 CodeGenModule &CGM; // Per-module state.
2530 llvm::LLVMContext &VMContext;
2531 const ItaniumCXXABI &CXXABI; // Per-module state.
2532
2533 /// Fields - The fields of the RTTI descriptor currently being built.
2534 SmallVector<llvm::Constant *, 16> Fields;
2535
2536 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2537 llvm::GlobalVariable *
2538 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2539
2540 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2541 /// descriptor of the given type.
2542 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2543
2544 /// BuildVTablePointer - Build the vtable pointer for the given type.
2545 void BuildVTablePointer(const Type *Ty);
2546
2547 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2548 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2549 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2550
2551 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2552 /// classes with bases that do not satisfy the abi::__si_class_type_info
2553 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2554 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2555
2556 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2557 /// for pointer types.
2558 void BuildPointerTypeInfo(QualType PointeeTy);
2559
2560 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2561 /// type_info for an object type.
2562 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2563
2564 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2565 /// struct, used for member pointer types.
2566 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2567
2568public:
2569 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2570 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2571
2572 // Pointer type info flags.
2573 enum {
2574 /// PTI_Const - Type has const qualifier.
2575 PTI_Const = 0x1,
2576
2577 /// PTI_Volatile - Type has volatile qualifier.
2578 PTI_Volatile = 0x2,
2579
2580 /// PTI_Restrict - Type has restrict qualifier.
2581 PTI_Restrict = 0x4,
2582
2583 /// PTI_Incomplete - Type is incomplete.
2584 PTI_Incomplete = 0x8,
2585
2586 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2587 /// (in pointer to member).
Richard Smitha7d93782016-12-01 03:32:42 +00002588 PTI_ContainingClassIncomplete = 0x10,
2589
2590 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2591 //PTI_TransactionSafe = 0x20,
2592
2593 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2594 PTI_Noexcept = 0x40,
David Majnemere2cb8d12014-07-07 06:20:47 +00002595 };
2596
2597 // VMI type info flags.
2598 enum {
2599 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2600 VMI_NonDiamondRepeat = 0x1,
2601
2602 /// VMI_DiamondShaped - Class is diamond shaped.
2603 VMI_DiamondShaped = 0x2
2604 };
2605
2606 // Base class type info flags.
2607 enum {
2608 /// BCTI_Virtual - Base class is virtual.
2609 BCTI_Virtual = 0x1,
2610
2611 /// BCTI_Public - Base class is public.
2612 BCTI_Public = 0x2
2613 };
2614
2615 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2616 ///
2617 /// \param Force - true to force the creation of this RTTI value
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00002618 /// \param DLLExport - true to mark the RTTI value as DLLExport
2619 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2620 bool DLLExport = false);
David Majnemere2cb8d12014-07-07 06:20:47 +00002621};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002622}
David Majnemere2cb8d12014-07-07 06:20:47 +00002623
2624llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2625 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002626 SmallString<256> Name;
2627 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002628 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002629
2630 // We know that the mangled name of the type starts at index 4 of the
2631 // mangled name of the typename, so we can just index into it in order to
2632 // get the mangled name of the type.
2633 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2634 Name.substr(4));
2635
2636 llvm::GlobalVariable *GV =
2637 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2638
2639 GV->setInitializer(Init);
2640
2641 return GV;
2642}
2643
2644llvm::Constant *
2645ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2646 // Mangle the RTTI name.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00002647 SmallString<256> Name;
2648 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00002649 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00002650
2651 // Look for an existing global.
2652 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2653
2654 if (!GV) {
2655 // Create a new global variable.
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002656 // Note for the future: If we would ever like to do deferred emission of
2657 // RTTI, check if emitting vtables opportunistically need any adjustment.
2658
David Majnemere2cb8d12014-07-07 06:20:47 +00002659 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2660 /*Constant=*/true,
2661 llvm::GlobalValue::ExternalLinkage, nullptr,
2662 Name);
Rafael Espindola3f727a82018-03-14 18:14:46 +00002663 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2664 CGM.setGVProperties(GV, RD);
David Majnemere2cb8d12014-07-07 06:20:47 +00002665 }
2666
2667 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2668}
2669
2670/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2671/// info for that type is defined in the standard library.
2672static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2673 // Itanium C++ ABI 2.9.2:
2674 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2675 // the run-time support library. Specifically, the run-time support
2676 // library should contain type_info objects for the types X, X* and
2677 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2678 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2679 // long, unsigned long, long long, unsigned long long, float, double,
2680 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2681 // half-precision floating point types.
Richard Smith4a382012016-02-03 01:32:42 +00002682 //
2683 // GCC also emits RTTI for __int128.
2684 // FIXME: We do not emit RTTI information for decimal types here.
2685
2686 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
David Majnemere2cb8d12014-07-07 06:20:47 +00002687 switch (Ty->getKind()) {
2688 case BuiltinType::Void:
2689 case BuiltinType::NullPtr:
2690 case BuiltinType::Bool:
2691 case BuiltinType::WChar_S:
2692 case BuiltinType::WChar_U:
2693 case BuiltinType::Char_U:
2694 case BuiltinType::Char_S:
2695 case BuiltinType::UChar:
2696 case BuiltinType::SChar:
2697 case BuiltinType::Short:
2698 case BuiltinType::UShort:
2699 case BuiltinType::Int:
2700 case BuiltinType::UInt:
2701 case BuiltinType::Long:
2702 case BuiltinType::ULong:
2703 case BuiltinType::LongLong:
2704 case BuiltinType::ULongLong:
2705 case BuiltinType::Half:
2706 case BuiltinType::Float:
2707 case BuiltinType::Double:
2708 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002709 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002710 case BuiltinType::Float128:
Richard Smith3a8244d2018-05-01 05:02:45 +00002711 case BuiltinType::Char8:
David Majnemere2cb8d12014-07-07 06:20:47 +00002712 case BuiltinType::Char16:
2713 case BuiltinType::Char32:
2714 case BuiltinType::Int128:
2715 case BuiltinType::UInt128:
Richard Smith4a382012016-02-03 01:32:42 +00002716 return true;
2717
Alexey Bader954ba212016-04-08 13:40:33 +00002718#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2719 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00002720#include "clang/Basic/OpenCLImageTypes.def"
David Majnemere2cb8d12014-07-07 06:20:47 +00002721 case BuiltinType::OCLSampler:
2722 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002723 case BuiltinType::OCLClkEvent:
2724 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002725 case BuiltinType::OCLReserveID:
Richard Smith4a382012016-02-03 01:32:42 +00002726 return false;
David Majnemere2cb8d12014-07-07 06:20:47 +00002727
2728 case BuiltinType::Dependent:
2729#define BUILTIN_TYPE(Id, SingletonId)
2730#define PLACEHOLDER_TYPE(Id, SingletonId) \
2731 case BuiltinType::Id:
2732#include "clang/AST/BuiltinTypes.def"
2733 llvm_unreachable("asking for RRTI for a placeholder type!");
2734
2735 case BuiltinType::ObjCId:
2736 case BuiltinType::ObjCClass:
2737 case BuiltinType::ObjCSel:
2738 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2739 }
2740
2741 llvm_unreachable("Invalid BuiltinType Kind!");
2742}
2743
2744static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2745 QualType PointeeTy = PointerTy->getPointeeType();
2746 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2747 if (!BuiltinTy)
2748 return false;
2749
2750 // Check the qualifiers.
2751 Qualifiers Quals = PointeeTy.getQualifiers();
2752 Quals.removeConst();
2753
2754 if (!Quals.empty())
2755 return false;
2756
2757 return TypeInfoIsInStandardLibrary(BuiltinTy);
2758}
2759
2760/// IsStandardLibraryRTTIDescriptor - Returns whether the type
2761/// information for the given type exists in the standard library.
2762static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2763 // Type info for builtin types is defined in the standard library.
2764 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2765 return TypeInfoIsInStandardLibrary(BuiltinTy);
2766
2767 // Type info for some pointer types to builtin types is defined in the
2768 // standard library.
2769 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2770 return TypeInfoIsInStandardLibrary(PointerTy);
2771
2772 return false;
2773}
2774
2775/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2776/// the given type exists somewhere else, and that we should not emit the type
2777/// information in this translation unit. Assumes that it is not a
2778/// standard-library type.
2779static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2780 QualType Ty) {
2781 ASTContext &Context = CGM.getContext();
2782
2783 // If RTTI is disabled, assume it might be disabled in the
2784 // translation unit that defines any potential key function, too.
2785 if (!Context.getLangOpts().RTTI) return false;
2786
2787 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2788 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2789 if (!RD->hasDefinition())
2790 return false;
2791
2792 if (!RD->isDynamicClass())
2793 return false;
2794
2795 // FIXME: this may need to be reconsidered if the key function
2796 // changes.
David Majnemerbe9022c2015-08-06 20:56:55 +00002797 // N.B. We must always emit the RTTI data ourselves if there exists a key
2798 // function.
2799 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
Martin Storsjo3b528942018-02-02 06:22:35 +00002800
2801 // Don't import the RTTI but emit it locally.
2802 if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
2803 return false;
2804
David Majnemer1fb1a042014-11-07 07:26:38 +00002805 if (CGM.getVTables().isVTableExternal(RD))
Shoaib Meenai61118e72017-07-04 01:02:19 +00002806 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
2807 ? false
2808 : true;
David Majnemer1fb1a042014-11-07 07:26:38 +00002809
David Majnemerbe9022c2015-08-06 20:56:55 +00002810 if (IsDLLImport)
David Majnemer1fb1a042014-11-07 07:26:38 +00002811 return true;
David Majnemere2cb8d12014-07-07 06:20:47 +00002812 }
2813
2814 return false;
2815}
2816
2817/// IsIncompleteClassType - Returns whether the given record type is incomplete.
2818static bool IsIncompleteClassType(const RecordType *RecordTy) {
2819 return !RecordTy->getDecl()->isCompleteDefinition();
2820}
2821
2822/// ContainsIncompleteClassType - Returns whether the given type contains an
2823/// incomplete class type. This is true if
2824///
2825/// * The given type is an incomplete class type.
2826/// * The given type is a pointer type whose pointee type contains an
2827/// incomplete class type.
2828/// * The given type is a member pointer type whose class is an incomplete
2829/// class type.
2830/// * The given type is a member pointer type whoise pointee type contains an
2831/// incomplete class type.
2832/// is an indirect or direct pointer to an incomplete class type.
2833static bool ContainsIncompleteClassType(QualType Ty) {
2834 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2835 if (IsIncompleteClassType(RecordTy))
2836 return true;
2837 }
2838
2839 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2840 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2841
2842 if (const MemberPointerType *MemberPointerTy =
2843 dyn_cast<MemberPointerType>(Ty)) {
2844 // Check if the class type is incomplete.
2845 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2846 if (IsIncompleteClassType(ClassType))
2847 return true;
2848
2849 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2850 }
2851
2852 return false;
2853}
2854
2855// CanUseSingleInheritance - Return whether the given record decl has a "single,
2856// public, non-virtual base at offset zero (i.e. the derived class is dynamic
2857// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2858static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2859 // Check the number of bases.
2860 if (RD->getNumBases() != 1)
2861 return false;
2862
2863 // Get the base.
2864 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2865
2866 // Check that the base is not virtual.
2867 if (Base->isVirtual())
2868 return false;
2869
2870 // Check that the base is public.
2871 if (Base->getAccessSpecifier() != AS_public)
2872 return false;
2873
2874 // Check that the class is dynamic iff the base is.
2875 const CXXRecordDecl *BaseDecl =
2876 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2877 if (!BaseDecl->isEmpty() &&
2878 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2879 return false;
2880
2881 return true;
2882}
2883
2884void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2885 // abi::__class_type_info.
2886 static const char * const ClassTypeInfo =
2887 "_ZTVN10__cxxabiv117__class_type_infoE";
2888 // abi::__si_class_type_info.
2889 static const char * const SIClassTypeInfo =
2890 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2891 // abi::__vmi_class_type_info.
2892 static const char * const VMIClassTypeInfo =
2893 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2894
2895 const char *VTableName = nullptr;
2896
2897 switch (Ty->getTypeClass()) {
2898#define TYPE(Class, Base)
2899#define ABSTRACT_TYPE(Class, Base)
2900#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2901#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2902#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2903#include "clang/AST/TypeNodes.def"
2904 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2905
2906 case Type::LValueReference:
2907 case Type::RValueReference:
2908 llvm_unreachable("References shouldn't get here");
2909
2910 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002911 case Type::DeducedTemplateSpecialization:
2912 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00002913
Xiuli Pan9c14e282016-01-09 12:53:17 +00002914 case Type::Pipe:
2915 llvm_unreachable("Pipe types shouldn't get here");
2916
David Majnemere2cb8d12014-07-07 06:20:47 +00002917 case Type::Builtin:
2918 // GCC treats vector and complex types as fundamental types.
2919 case Type::Vector:
2920 case Type::ExtVector:
2921 case Type::Complex:
2922 case Type::Atomic:
2923 // FIXME: GCC treats block pointers as fundamental types?!
2924 case Type::BlockPointer:
2925 // abi::__fundamental_type_info.
2926 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2927 break;
2928
2929 case Type::ConstantArray:
2930 case Type::IncompleteArray:
2931 case Type::VariableArray:
2932 // abi::__array_type_info.
2933 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2934 break;
2935
2936 case Type::FunctionNoProto:
2937 case Type::FunctionProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00002938 // abi::__function_type_info.
2939 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
David Majnemere2cb8d12014-07-07 06:20:47 +00002940 break;
2941
2942 case Type::Enum:
2943 // abi::__enum_type_info.
2944 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2945 break;
2946
2947 case Type::Record: {
Rafael Espindolaf6688122018-03-22 21:14:16 +00002948 const CXXRecordDecl *RD =
2949 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
David Majnemere2cb8d12014-07-07 06:20:47 +00002950
2951 if (!RD->hasDefinition() || !RD->getNumBases()) {
2952 VTableName = ClassTypeInfo;
2953 } else if (CanUseSingleInheritance(RD)) {
2954 VTableName = SIClassTypeInfo;
2955 } else {
2956 VTableName = VMIClassTypeInfo;
2957 }
2958
2959 break;
2960 }
2961
2962 case Type::ObjCObject:
2963 // Ignore protocol qualifiers.
2964 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2965
2966 // Handle id and Class.
2967 if (isa<BuiltinType>(Ty)) {
2968 VTableName = ClassTypeInfo;
2969 break;
2970 }
2971
2972 assert(isa<ObjCInterfaceType>(Ty));
2973 // Fall through.
2974
2975 case Type::ObjCInterface:
2976 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2977 VTableName = SIClassTypeInfo;
2978 } else {
2979 VTableName = ClassTypeInfo;
2980 }
2981 break;
2982
2983 case Type::ObjCObjectPointer:
2984 case Type::Pointer:
2985 // abi::__pointer_type_info.
2986 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2987 break;
2988
2989 case Type::MemberPointer:
2990 // abi::__pointer_to_member_type_info.
2991 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2992 break;
2993 }
2994
2995 llvm::Constant *VTable =
2996 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
Rafael Espindolafe9a55a2018-03-23 01:36:23 +00002997 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
David Majnemere2cb8d12014-07-07 06:20:47 +00002998
2999 llvm::Type *PtrDiffTy =
3000 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
3001
3002 // The vtable address point is 2.
3003 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00003004 VTable =
3005 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
David Majnemere2cb8d12014-07-07 06:20:47 +00003006 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
3007
3008 Fields.push_back(VTable);
3009}
3010
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003011/// Return the linkage that the type info and type info name constants
David Majnemere2cb8d12014-07-07 06:20:47 +00003012/// should have for the given type.
Richard Smithbbb26552018-05-21 20:10:54 +00003013static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
3014 QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003015 // Itanium C++ ABI 2.9.5p7:
3016 // In addition, it and all of the intermediate abi::__pointer_type_info
3017 // structs in the chain down to the abi::__class_type_info for the
3018 // incomplete class type must be prevented from resolving to the
3019 // corresponding type_info structs for the complete class type, possibly
3020 // by making them local static objects. Finally, a dummy class RTTI is
3021 // generated for the incomplete type that will not resolve to the final
3022 // complete class RTTI (because the latter need not exist), possibly by
3023 // making it a local static object.
3024 if (ContainsIncompleteClassType(Ty))
Richard Smithbbb26552018-05-21 20:10:54 +00003025 return llvm::GlobalValue::InternalLinkage;
3026
3027 switch (Ty->getLinkage()) {
3028 case NoLinkage:
3029 case InternalLinkage:
3030 case UniqueExternalLinkage:
3031 return llvm::GlobalValue::InternalLinkage;
3032
3033 case VisibleNoLinkage:
3034 case ModuleInternalLinkage:
3035 case ModuleLinkage:
3036 case ExternalLinkage:
3037 // RTTI is not enabled, which means that this type info struct is going
3038 // to be used for exception handling. Give it linkonce_odr linkage.
3039 if (!CGM.getLangOpts().RTTI)
3040 return llvm::GlobalValue::LinkOnceODRLinkage;
3041
3042 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
3043 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3044 if (RD->hasAttr<WeakAttr>())
3045 return llvm::GlobalValue::WeakODRLinkage;
3046 if (CGM.getTriple().isWindowsItaniumEnvironment())
3047 if (RD->hasAttr<DLLImportAttr>() &&
3048 ShouldUseExternalRTTIDescriptor(CGM, Ty))
3049 return llvm::GlobalValue::ExternalLinkage;
3050 // MinGW always uses LinkOnceODRLinkage for type info.
3051 if (RD->isDynamicClass() &&
3052 !CGM.getContext()
3053 .getTargetInfo()
3054 .getTriple()
3055 .isWindowsGNUEnvironment())
3056 return CGM.getVTableLinkage(RD);
3057 }
3058
3059 return llvm::GlobalValue::LinkOnceODRLinkage;
3060 }
3061
3062 llvm_unreachable("Invalid linkage!");
David Majnemere2cb8d12014-07-07 06:20:47 +00003063}
3064
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003065llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
3066 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003067 // We want to operate on the canonical type.
Yaron Kerenebd14262016-03-16 12:14:43 +00003068 Ty = Ty.getCanonicalType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003069
3070 // Check if we've already emitted an RTTI descriptor for this type.
Yaron Kerene46f7ed2015-07-29 14:21:47 +00003071 SmallString<256> Name;
3072 llvm::raw_svector_ostream Out(Name);
David Majnemere2cb8d12014-07-07 06:20:47 +00003073 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
David Majnemere2cb8d12014-07-07 06:20:47 +00003074
3075 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
3076 if (OldGV && !OldGV->isDeclaration()) {
3077 assert(!OldGV->hasAvailableExternallyLinkage() &&
3078 "available_externally typeinfos not yet implemented");
3079
3080 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
3081 }
3082
3083 // Check if there is already an external RTTI descriptor for this type.
3084 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
3085 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
3086 return GetAddrOfExternalRTTIDescriptor(Ty);
3087
3088 // Emit the standard library with external linkage.
Richard Smithbbb26552018-05-21 20:10:54 +00003089 llvm::GlobalVariable::LinkageTypes Linkage;
David Majnemere2cb8d12014-07-07 06:20:47 +00003090 if (IsStdLib)
Richard Smithbbb26552018-05-21 20:10:54 +00003091 Linkage = llvm::GlobalValue::ExternalLinkage;
3092 else
3093 Linkage = getTypeInfoLinkage(CGM, Ty);
3094
David Majnemere2cb8d12014-07-07 06:20:47 +00003095 // Add the vtable pointer.
3096 BuildVTablePointer(cast<Type>(Ty));
3097
3098 // And the name.
Richard Smithbbb26552018-05-21 20:10:54 +00003099 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003100 llvm::Constant *TypeNameField;
3101
3102 // If we're supposed to demote the visibility, be sure to set a flag
3103 // to use a string comparison for type_info comparisons.
3104 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
Richard Smithbbb26552018-05-21 20:10:54 +00003105 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
David Majnemere2cb8d12014-07-07 06:20:47 +00003106 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3107 // The flag is the sign bit, which on ARM64 is defined to be clear
3108 // for global pointers. This is very ARM64-specific.
3109 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3110 llvm::Constant *flag =
3111 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3112 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3113 TypeNameField =
3114 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3115 } else {
3116 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3117 }
3118 Fields.push_back(TypeNameField);
3119
3120 switch (Ty->getTypeClass()) {
3121#define TYPE(Class, Base)
3122#define ABSTRACT_TYPE(Class, Base)
3123#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3124#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3125#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3126#include "clang/AST/TypeNodes.def"
3127 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3128
3129 // GCC treats vector types as fundamental types.
3130 case Type::Builtin:
3131 case Type::Vector:
3132 case Type::ExtVector:
3133 case Type::Complex:
3134 case Type::BlockPointer:
3135 // Itanium C++ ABI 2.9.5p4:
3136 // abi::__fundamental_type_info adds no data members to std::type_info.
3137 break;
3138
3139 case Type::LValueReference:
3140 case Type::RValueReference:
3141 llvm_unreachable("References shouldn't get here");
3142
3143 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003144 case Type::DeducedTemplateSpecialization:
3145 llvm_unreachable("Undeduced type shouldn't get here");
David Majnemere2cb8d12014-07-07 06:20:47 +00003146
Xiuli Pan9c14e282016-01-09 12:53:17 +00003147 case Type::Pipe:
3148 llvm_unreachable("Pipe type shouldn't get here");
3149
David Majnemere2cb8d12014-07-07 06:20:47 +00003150 case Type::ConstantArray:
3151 case Type::IncompleteArray:
3152 case Type::VariableArray:
3153 // Itanium C++ ABI 2.9.5p5:
3154 // abi::__array_type_info adds no data members to std::type_info.
3155 break;
3156
3157 case Type::FunctionNoProto:
Richard Smithb17d6fa2016-12-01 03:04:07 +00003158 case Type::FunctionProto:
David Majnemere2cb8d12014-07-07 06:20:47 +00003159 // Itanium C++ ABI 2.9.5p5:
3160 // abi::__function_type_info adds no data members to std::type_info.
3161 break;
3162
3163 case Type::Enum:
3164 // Itanium C++ ABI 2.9.5p5:
3165 // abi::__enum_type_info adds no data members to std::type_info.
3166 break;
3167
3168 case Type::Record: {
3169 const CXXRecordDecl *RD =
3170 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3171 if (!RD->hasDefinition() || !RD->getNumBases()) {
3172 // We don't need to emit any fields.
3173 break;
3174 }
3175
3176 if (CanUseSingleInheritance(RD))
3177 BuildSIClassTypeInfo(RD);
3178 else
3179 BuildVMIClassTypeInfo(RD);
3180
3181 break;
3182 }
3183
3184 case Type::ObjCObject:
3185 case Type::ObjCInterface:
3186 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3187 break;
3188
3189 case Type::ObjCObjectPointer:
3190 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3191 break;
3192
3193 case Type::Pointer:
3194 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3195 break;
3196
3197 case Type::MemberPointer:
3198 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3199 break;
3200
3201 case Type::Atomic:
3202 // No fields, at least for the moment.
3203 break;
3204 }
3205
3206 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3207
Rafael Espindolacb92c192015-01-15 23:18:01 +00003208 llvm::Module &M = CGM.getModule();
David Majnemere2cb8d12014-07-07 06:20:47 +00003209 llvm::GlobalVariable *GV =
Rafael Espindolacb92c192015-01-15 23:18:01 +00003210 new llvm::GlobalVariable(M, Init->getType(),
Richard Smithbbb26552018-05-21 20:10:54 +00003211 /*Constant=*/true, Linkage, Init, Name);
Rafael Espindolacb92c192015-01-15 23:18:01 +00003212
David Majnemere2cb8d12014-07-07 06:20:47 +00003213 // If there's already an old global variable, replace it with the new one.
3214 if (OldGV) {
3215 GV->takeName(OldGV);
3216 llvm::Constant *NewPtr =
3217 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3218 OldGV->replaceAllUsesWith(NewPtr);
3219 OldGV->eraseFromParent();
3220 }
3221
Yaron Keren04da2382015-07-29 15:42:28 +00003222 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3223 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3224
David Majnemere2cb8d12014-07-07 06:20:47 +00003225 // The Itanium ABI specifies that type_info objects must be globally
3226 // unique, with one exception: if the type is an incomplete class
3227 // type or a (possibly indirect) pointer to one. That exception
3228 // affects the general case of comparing type_info objects produced
3229 // by the typeid operator, which is why the comparison operators on
3230 // std::type_info generally use the type_info name pointers instead
3231 // of the object addresses. However, the language's built-in uses
3232 // of RTTI generally require class types to be complete, even when
3233 // manipulating pointers to those class types. This allows the
3234 // implementation of dynamic_cast to rely on address equality tests,
3235 // which is much faster.
3236
3237 // All of this is to say that it's important that both the type_info
3238 // object and the type_info name be uniqued when weakly emitted.
3239
3240 // Give the type_info object and name the formal visibility of the
3241 // type itself.
Richard Smithbbb26552018-05-21 20:10:54 +00003242 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3243 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3244 // If the linkage is local, only default visibility makes sense.
3245 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3246 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3247 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3248 else
3249 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003250
Richard Smithbbb26552018-05-21 20:10:54 +00003251 TypeName->setVisibility(llvmVisibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003252 CGM.setDSOLocal(TypeName);
Rafael Espindola699f5d62018-02-07 22:15:33 +00003253
Richard Smithbbb26552018-05-21 20:10:54 +00003254 GV->setVisibility(llvmVisibility);
Rafael Espindola3dd49812018-02-23 00:22:15 +00003255 CGM.setDSOLocal(GV);
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003256
3257 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3258 auto RD = Ty->getAsCXXRecordDecl();
3259 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3260 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3261 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Shoaib Meenai61118e72017-07-04 01:02:19 +00003262 } else if (RD && RD->hasAttr<DLLImportAttr>() &&
3263 ShouldUseExternalRTTIDescriptor(CGM, Ty)) {
Saleem Abdulrasool18820022016-12-02 22:46:18 +00003264 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3265 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3266
3267 // Because the typename and the typeinfo are DLL import, convert them to
3268 // declarations rather than definitions. The initializers still need to
3269 // be constructed to calculate the type for the declarations.
3270 TypeName->setInitializer(nullptr);
3271 GV->setInitializer(nullptr);
3272 }
3273 }
David Majnemere2cb8d12014-07-07 06:20:47 +00003274
3275 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3276}
3277
David Majnemere2cb8d12014-07-07 06:20:47 +00003278/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3279/// for the given Objective-C object type.
3280void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3281 // Drop qualifiers.
3282 const Type *T = OT->getBaseType().getTypePtr();
3283 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3284
3285 // The builtin types are abi::__class_type_infos and don't require
3286 // extra fields.
3287 if (isa<BuiltinType>(T)) return;
3288
3289 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3290 ObjCInterfaceDecl *Super = Class->getSuperClass();
3291
3292 // Root classes are also __class_type_info.
3293 if (!Super) return;
3294
3295 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3296
3297 // Everything else is single inheritance.
3298 llvm::Constant *BaseTypeInfo =
3299 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3300 Fields.push_back(BaseTypeInfo);
3301}
3302
3303/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3304/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3305void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3306 // Itanium C++ ABI 2.9.5p6b:
3307 // It adds to abi::__class_type_info a single member pointing to the
3308 // type_info structure for the base type,
3309 llvm::Constant *BaseTypeInfo =
3310 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3311 Fields.push_back(BaseTypeInfo);
3312}
3313
3314namespace {
3315 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3316 /// a class hierarchy.
3317 struct SeenBases {
3318 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3319 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3320 };
3321}
3322
3323/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3324/// abi::__vmi_class_type_info.
3325///
3326static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3327 SeenBases &Bases) {
3328
3329 unsigned Flags = 0;
3330
3331 const CXXRecordDecl *BaseDecl =
3332 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3333
3334 if (Base->isVirtual()) {
3335 // Mark the virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003336 if (!Bases.VirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003337 // If this virtual base has been seen before, then the class is diamond
3338 // shaped.
3339 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3340 } else {
3341 if (Bases.NonVirtualBases.count(BaseDecl))
3342 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3343 }
3344 } else {
3345 // Mark the non-virtual base as seen.
David Blaikie82e95a32014-11-19 07:49:47 +00003346 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003347 // If this non-virtual base has been seen before, then the class has non-
3348 // diamond shaped repeated inheritance.
3349 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3350 } else {
3351 if (Bases.VirtualBases.count(BaseDecl))
3352 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3353 }
3354 }
3355
3356 // Walk all bases.
3357 for (const auto &I : BaseDecl->bases())
3358 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3359
3360 return Flags;
3361}
3362
3363static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3364 unsigned Flags = 0;
3365 SeenBases Bases;
3366
3367 // Walk all bases.
3368 for (const auto &I : RD->bases())
3369 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3370
3371 return Flags;
3372}
3373
3374/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3375/// classes with bases that do not satisfy the abi::__si_class_type_info
3376/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3377void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3378 llvm::Type *UnsignedIntLTy =
3379 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3380
3381 // Itanium C++ ABI 2.9.5p6c:
3382 // __flags is a word with flags describing details about the class
3383 // structure, which may be referenced by using the __flags_masks
3384 // enumeration. These flags refer to both direct and indirect bases.
3385 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3386 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3387
3388 // Itanium C++ ABI 2.9.5p6c:
3389 // __base_count is a word with the number of direct proper base class
3390 // descriptions that follow.
3391 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3392
3393 if (!RD->getNumBases())
3394 return;
3395
David Majnemere2cb8d12014-07-07 06:20:47 +00003396 // Now add the base class descriptions.
3397
3398 // Itanium C++ ABI 2.9.5p6c:
3399 // __base_info[] is an array of base class descriptions -- one for every
3400 // direct proper base. Each description is of the type:
3401 //
3402 // struct abi::__base_class_type_info {
3403 // public:
3404 // const __class_type_info *__base_type;
3405 // long __offset_flags;
3406 //
3407 // enum __offset_flags_masks {
3408 // __virtual_mask = 0x1,
3409 // __public_mask = 0x2,
3410 // __offset_shift = 8
3411 // };
3412 // };
Reid Klecknerd8b04662016-08-25 22:16:30 +00003413
3414 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3415 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3416 // LLP64 platforms.
3417 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3418 // LLP64 platforms.
3419 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3420 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3421 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3422 OffsetFlagsTy = CGM.getContext().LongLongTy;
3423 llvm::Type *OffsetFlagsLTy =
3424 CGM.getTypes().ConvertType(OffsetFlagsTy);
3425
David Majnemere2cb8d12014-07-07 06:20:47 +00003426 for (const auto &Base : RD->bases()) {
3427 // The __base_type member points to the RTTI for the base type.
3428 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3429
3430 const CXXRecordDecl *BaseDecl =
3431 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3432
3433 int64_t OffsetFlags = 0;
3434
3435 // All but the lower 8 bits of __offset_flags are a signed offset.
3436 // For a non-virtual base, this is the offset in the object of the base
3437 // subobject. For a virtual base, this is the offset in the virtual table of
3438 // the virtual base offset for the virtual base referenced (negative).
3439 CharUnits Offset;
3440 if (Base.isVirtual())
3441 Offset =
3442 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3443 else {
3444 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3445 Offset = Layout.getBaseClassOffset(BaseDecl);
3446 };
3447
3448 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3449
3450 // The low-order byte of __offset_flags contains flags, as given by the
3451 // masks from the enumeration __offset_flags_masks.
3452 if (Base.isVirtual())
3453 OffsetFlags |= BCTI_Virtual;
3454 if (Base.getAccessSpecifier() == AS_public)
3455 OffsetFlags |= BCTI_Public;
3456
Reid Klecknerd8b04662016-08-25 22:16:30 +00003457 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
David Majnemere2cb8d12014-07-07 06:20:47 +00003458 }
3459}
3460
Richard Smitha7d93782016-12-01 03:32:42 +00003461/// Compute the flags for a __pbase_type_info, and remove the corresponding
3462/// pieces from \p Type.
3463static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3464 unsigned Flags = 0;
David Majnemere2cb8d12014-07-07 06:20:47 +00003465
Richard Smitha7d93782016-12-01 03:32:42 +00003466 if (Type.isConstQualified())
3467 Flags |= ItaniumRTTIBuilder::PTI_Const;
3468 if (Type.isVolatileQualified())
3469 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3470 if (Type.isRestrictQualified())
3471 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3472 Type = Type.getUnqualifiedType();
David Majnemere2cb8d12014-07-07 06:20:47 +00003473
3474 // Itanium C++ ABI 2.9.5p7:
3475 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3476 // incomplete class type, the incomplete target type flag is set.
Richard Smitha7d93782016-12-01 03:32:42 +00003477 if (ContainsIncompleteClassType(Type))
3478 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3479
3480 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003481 if (Proto->isNothrow()) {
Richard Smitha7d93782016-12-01 03:32:42 +00003482 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003483 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
Richard Smitha7d93782016-12-01 03:32:42 +00003484 }
3485 }
3486
3487 return Flags;
3488}
3489
3490/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3491/// used for pointer types.
3492void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3493 // Itanium C++ ABI 2.9.5p7:
3494 // __flags is a flag word describing the cv-qualification and other
3495 // attributes of the type pointed to
3496 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003497
3498 llvm::Type *UnsignedIntLTy =
3499 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3500 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3501
3502 // Itanium C++ ABI 2.9.5p7:
3503 // __pointee is a pointer to the std::type_info derivation for the
3504 // unqualified type being pointed to.
3505 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003506 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003507 Fields.push_back(PointeeTypeInfo);
3508}
3509
3510/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3511/// struct, used for member pointer types.
3512void
3513ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3514 QualType PointeeTy = Ty->getPointeeType();
3515
David Majnemere2cb8d12014-07-07 06:20:47 +00003516 // Itanium C++ ABI 2.9.5p7:
3517 // __flags is a flag word describing the cv-qualification and other
3518 // attributes of the type pointed to.
Richard Smitha7d93782016-12-01 03:32:42 +00003519 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003520
3521 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
David Majnemere2cb8d12014-07-07 06:20:47 +00003522 if (IsIncompleteClassType(ClassType))
3523 Flags |= PTI_ContainingClassIncomplete;
3524
3525 llvm::Type *UnsignedIntLTy =
3526 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3527 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3528
3529 // Itanium C++ ABI 2.9.5p7:
3530 // __pointee is a pointer to the std::type_info derivation for the
3531 // unqualified type being pointed to.
3532 llvm::Constant *PointeeTypeInfo =
Richard Smitha7d93782016-12-01 03:32:42 +00003533 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
David Majnemere2cb8d12014-07-07 06:20:47 +00003534 Fields.push_back(PointeeTypeInfo);
3535
3536 // Itanium C++ ABI 2.9.5p9:
3537 // __context is a pointer to an abi::__class_type_info corresponding to the
3538 // class type containing the member pointed to
3539 // (e.g., the "A" in "int A::*").
3540 Fields.push_back(
3541 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3542}
3543
David Majnemer443250f2015-03-17 20:35:00 +00003544llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003545 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3546}
3547
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003548void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3549 bool DLLExport) {
David Majnemere2cb8d12014-07-07 06:20:47 +00003550 QualType PointerType = getContext().getPointerType(Type);
3551 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003552 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3553 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3554 DLLExport);
3555 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3556 DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003557}
3558
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003559void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
Richard Smith4a382012016-02-03 01:32:42 +00003560 // Types added here must also be added to TypeInfoIsInStandardLibrary.
David Majnemere2cb8d12014-07-07 06:20:47 +00003561 QualType FundamentalTypes[] = {
3562 getContext().VoidTy, getContext().NullPtrTy,
3563 getContext().BoolTy, getContext().WCharTy,
3564 getContext().CharTy, getContext().UnsignedCharTy,
3565 getContext().SignedCharTy, getContext().ShortTy,
3566 getContext().UnsignedShortTy, getContext().IntTy,
3567 getContext().UnsignedIntTy, getContext().LongTy,
3568 getContext().UnsignedLongTy, getContext().LongLongTy,
Richard Smith4a382012016-02-03 01:32:42 +00003569 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3570 getContext().UnsignedInt128Ty, getContext().HalfTy,
David Majnemere2cb8d12014-07-07 06:20:47 +00003571 getContext().FloatTy, getContext().DoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003572 getContext().LongDoubleTy, getContext().Float128Ty,
Richard Smith3a8244d2018-05-01 05:02:45 +00003573 getContext().Char8Ty, getContext().Char16Ty,
3574 getContext().Char32Ty
David Majnemere2cb8d12014-07-07 06:20:47 +00003575 };
3576 for (const QualType &FundamentalType : FundamentalTypes)
Saleem Abdulrasool8dbaf5c2016-09-30 23:11:05 +00003577 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
David Majnemere2cb8d12014-07-07 06:20:47 +00003578}
3579
3580/// What sort of uniqueness rules should we use for the RTTI for the
3581/// given type?
3582ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3583 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3584 if (shouldRTTIBeUnique())
3585 return RUK_Unique;
3586
3587 // It's only necessary for linkonce_odr or weak_odr linkage.
3588 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3589 Linkage != llvm::GlobalValue::WeakODRLinkage)
3590 return RUK_Unique;
3591
3592 // It's only necessary with default visibility.
3593 if (CanTy->getVisibility() != DefaultVisibility)
3594 return RUK_Unique;
3595
3596 // If we're not required to publish this symbol, hide it.
3597 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3598 return RUK_NonUniqueHidden;
3599
3600 // If we're required to publish this symbol, as we might be under an
3601 // explicit instantiation, leave it with default visibility but
3602 // enable string-comparisons.
3603 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3604 return RUK_NonUniqueVisible;
3605}
Rafael Espindola91f68b42014-09-15 19:20:10 +00003606
Rafael Espindola1e4df922014-09-16 15:18:21 +00003607// Find out how to codegen the complete destructor and constructor
3608namespace {
3609enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3610}
3611static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3612 const CXXMethodDecl *MD) {
3613 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3614 return StructorCodegen::Emit;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003615
Rafael Espindola1e4df922014-09-16 15:18:21 +00003616 // The complete and base structors are not equivalent if there are any virtual
3617 // bases, so emit separate functions.
3618 if (MD->getParent()->getNumVBases())
3619 return StructorCodegen::Emit;
3620
3621 GlobalDecl AliasDecl;
3622 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3623 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3624 } else {
3625 const auto *CD = cast<CXXConstructorDecl>(MD);
3626 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3627 }
3628 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3629
Pavel Labathb3b02552018-05-21 11:47:45 +00003630 // All discardable structors can be RAUWed, but we don't want to do that in
3631 // unoptimized code, as that makes complete structor symbol disappear
3632 // completely, which degrades debugging experience.
3633 // Symbols with private linkage can be safely aliased, so we special case them
3634 // here.
3635 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3636 return CGM.getCodeGenOpts().OptimizationLevel > 0 ? StructorCodegen::RAUW
3637 : StructorCodegen::Alias;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003638
Pavel Labathb3b02552018-05-21 11:47:45 +00003639 // Linkonce structors cannot be aliased nor placed in a comdat, so these need
3640 // to be emitted separately.
Pavel Labathc370f262018-05-14 11:35:44 +00003641 // FIXME: Should we allow available_externally aliases?
Pavel Labathb3b02552018-05-21 11:47:45 +00003642 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) ||
3643 !llvm::GlobalAlias::isValidLinkage(Linkage))
3644 return CGM.getCodeGenOpts().OptimizationLevel > 0 ? StructorCodegen::RAUW
3645 : StructorCodegen::Emit;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003646
Rafael Espindola0806f982014-09-16 20:19:43 +00003647 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
Dan Gohman839f2152017-01-17 21:46:38 +00003648 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3649 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3650 CGM.getTarget().getTriple().isOSBinFormatWasm())
Rafael Espindola0806f982014-09-16 20:19:43 +00003651 return StructorCodegen::COMDAT;
3652 return StructorCodegen::Emit;
3653 }
Rafael Espindola1e4df922014-09-16 15:18:21 +00003654
3655 return StructorCodegen::Alias;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003656}
3657
Rafael Espindola1e4df922014-09-16 15:18:21 +00003658static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3659 GlobalDecl AliasDecl,
3660 GlobalDecl TargetDecl) {
3661 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3662
3663 StringRef MangledName = CGM.getMangledName(AliasDecl);
3664 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3665 if (Entry && !Entry->isDeclaration())
3666 return;
3667
3668 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
Rafael Espindola1e4df922014-09-16 15:18:21 +00003669
3670 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +00003671 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003672
3673 // Switch any previous uses to the alias.
3674 if (Entry) {
NAKAMURA Takumie9621042015-09-15 01:39:27 +00003675 assert(Entry->getType() == Aliasee->getType() &&
Rafael Espindola1e4df922014-09-16 15:18:21 +00003676 "declaration exists with different type");
3677 Alias->takeName(Entry);
3678 Entry->replaceAllUsesWith(Alias);
3679 Entry->eraseFromParent();
3680 } else {
3681 Alias->setName(MangledName);
3682 }
3683
3684 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +00003685 CGM.SetCommonAttributes(AliasDecl, Alias);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003686}
3687
3688void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3689 StructorType Type) {
3690 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3691 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3692
3693 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3694
3695 if (Type == StructorType::Complete) {
3696 GlobalDecl CompleteDecl;
3697 GlobalDecl BaseDecl;
3698 if (CD) {
3699 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3700 BaseDecl = GlobalDecl(CD, Ctor_Base);
3701 } else {
3702 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3703 BaseDecl = GlobalDecl(DD, Dtor_Base);
3704 }
3705
3706 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3707 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3708 return;
3709 }
3710
3711 if (CGType == StructorCodegen::RAUW) {
3712 StringRef MangledName = CGM.getMangledName(CompleteDecl);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003713 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
Rafael Espindola1e4df922014-09-16 15:18:21 +00003714 CGM.addReplacement(MangledName, Aliasee);
3715 return;
Rafael Espindola91f68b42014-09-15 19:20:10 +00003716 }
3717 }
3718
3719 // The base destructor is equivalent to the base destructor of its
3720 // base class if there is exactly one non-virtual base class with a
3721 // non-trivial destructor, there are no fields with a non-trivial
3722 // destructor, and the body of the destructor is trivial.
Rafael Espindola1e4df922014-09-16 15:18:21 +00003723 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3724 !CGM.TryEmitBaseDestructorAsAlias(DD))
Rafael Espindola91f68b42014-09-15 19:20:10 +00003725 return;
3726
Richard Smith5b349582017-10-13 01:55:36 +00003727 // FIXME: The deleting destructor is equivalent to the selected operator
3728 // delete if:
3729 // * either the delete is a destroying operator delete or the destructor
3730 // would be trivial if it weren't virtual,
3731 // * the conversion from the 'this' parameter to the first parameter of the
3732 // destructor is equivalent to a bitcast,
3733 // * the destructor does not have an implicit "this" return, and
3734 // * the operator delete has the same calling convention and IR function type
3735 // as the destructor.
3736 // In such cases we should try to emit the deleting dtor as an alias to the
3737 // selected 'operator delete'.
3738
Rafael Espindola1e4df922014-09-16 15:18:21 +00003739 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003740
Rafael Espindola1e4df922014-09-16 15:18:21 +00003741 if (CGType == StructorCodegen::COMDAT) {
3742 SmallString<256> Buffer;
3743 llvm::raw_svector_ostream Out(Buffer);
3744 if (DD)
3745 getMangleContext().mangleCXXDtorComdat(DD, Out);
3746 else
3747 getMangleContext().mangleCXXCtorComdat(CD, Out);
3748 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3749 Fn->setComdat(C);
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003750 } else {
3751 CGM.maybeSetTrivialComdat(*MD, *Fn);
Rafael Espindola91f68b42014-09-15 19:20:10 +00003752 }
Rafael Espindola91f68b42014-09-15 19:20:10 +00003753}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003754
3755static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3756 // void *__cxa_begin_catch(void*);
3757 llvm::FunctionType *FTy = llvm::FunctionType::get(
3758 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3759
3760 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3761}
3762
3763static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3764 // void __cxa_end_catch();
3765 llvm::FunctionType *FTy =
3766 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3767
3768 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3769}
3770
3771static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3772 // void *__cxa_get_exception_ptr(void*);
3773 llvm::FunctionType *FTy = llvm::FunctionType::get(
3774 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3775
3776 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3777}
3778
3779namespace {
3780 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3781 /// exception type lets us state definitively that the thrown exception
3782 /// type does not have a destructor. In particular:
3783 /// - Catch-alls tell us nothing, so we have to conservatively
3784 /// assume that the thrown exception might have a destructor.
3785 /// - Catches by reference behave according to their base types.
3786 /// - Catches of non-record types will only trigger for exceptions
3787 /// of non-record types, which never have destructors.
3788 /// - Catches of record types can trigger for arbitrary subclasses
3789 /// of the caught type, so we have to assume the actual thrown
3790 /// exception type might have a throwing destructor, even if the
3791 /// caught type's destructor is trivial or nothrow.
David Blaikie7e70d682015-08-18 22:40:54 +00003792 struct CallEndCatch final : EHScopeStack::Cleanup {
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003793 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3794 bool MightThrow;
3795
3796 void Emit(CodeGenFunction &CGF, Flags flags) override {
3797 if (!MightThrow) {
3798 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3799 return;
3800 }
3801
3802 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3803 }
3804 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003805}
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003806
3807/// Emits a call to __cxa_begin_catch and enters a cleanup to call
3808/// __cxa_end_catch.
3809///
3810/// \param EndMightThrow - true if __cxa_end_catch might throw
3811static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3812 llvm::Value *Exn,
3813 bool EndMightThrow) {
3814 llvm::CallInst *call =
3815 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3816
3817 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3818
3819 return call;
3820}
3821
3822/// A "special initializer" callback for initializing a catch
3823/// parameter during catch initialization.
3824static void InitCatchParam(CodeGenFunction &CGF,
3825 const VarDecl &CatchParam,
John McCall7f416cc2015-09-08 08:05:57 +00003826 Address ParamAddr,
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003827 SourceLocation Loc) {
3828 // Load the exception from where the landing pad saved it.
3829 llvm::Value *Exn = CGF.getExceptionFromSlot();
3830
3831 CanQualType CatchType =
3832 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3833 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3834
3835 // If we're catching by reference, we can just cast the object
3836 // pointer to the appropriate pointer.
3837 if (isa<ReferenceType>(CatchType)) {
3838 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3839 bool EndCatchMightThrow = CaughtType->isRecordType();
3840
3841 // __cxa_begin_catch returns the adjusted object pointer.
3842 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3843
3844 // We have no way to tell the personality function that we're
3845 // catching by reference, so if we're catching a pointer,
3846 // __cxa_begin_catch will actually return that pointer by value.
3847 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3848 QualType PointeeType = PT->getPointeeType();
3849
3850 // When catching by reference, generally we should just ignore
3851 // this by-value pointer and use the exception object instead.
3852 if (!PointeeType->isRecordType()) {
3853
3854 // Exn points to the struct _Unwind_Exception header, which
3855 // we have to skip past in order to reach the exception data.
3856 unsigned HeaderSize =
3857 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3858 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3859
3860 // However, if we're catching a pointer-to-record type that won't
3861 // work, because the personality function might have adjusted
3862 // the pointer. There's actually no way for us to fully satisfy
3863 // the language/ABI contract here: we can't use Exn because it
3864 // might have the wrong adjustment, but we can't use the by-value
3865 // pointer because it's off by a level of abstraction.
3866 //
3867 // The current solution is to dump the adjusted pointer into an
3868 // alloca, which breaks language semantics (because changing the
3869 // pointer doesn't change the exception) but at least works.
3870 // The better solution would be to filter out non-exact matches
3871 // and rethrow them, but this is tricky because the rethrow
3872 // really needs to be catchable by other sites at this landing
3873 // pad. The best solution is to fix the personality function.
3874 } else {
3875 // Pull the pointer for the reference type off.
3876 llvm::Type *PtrTy =
3877 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3878
3879 // Create the temporary and write the adjusted pointer into it.
John McCall7f416cc2015-09-08 08:05:57 +00003880 Address ExnPtrTmp =
3881 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003882 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3883 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3884
3885 // Bind the reference to the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003886 AdjustedExn = ExnPtrTmp.getPointer();
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003887 }
3888 }
3889
3890 llvm::Value *ExnCast =
3891 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3892 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3893 return;
3894 }
3895
3896 // Scalars and complexes.
3897 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3898 if (TEK != TEK_Aggregate) {
3899 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3900
3901 // If the catch type is a pointer type, __cxa_begin_catch returns
3902 // the pointer by value.
3903 if (CatchType->hasPointerRepresentation()) {
3904 llvm::Value *CastExn =
3905 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3906
3907 switch (CatchType.getQualifiers().getObjCLifetime()) {
3908 case Qualifiers::OCL_Strong:
3909 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3910 // fallthrough
3911
3912 case Qualifiers::OCL_None:
3913 case Qualifiers::OCL_ExplicitNone:
3914 case Qualifiers::OCL_Autoreleasing:
3915 CGF.Builder.CreateStore(CastExn, ParamAddr);
3916 return;
3917
3918 case Qualifiers::OCL_Weak:
3919 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3920 return;
3921 }
3922 llvm_unreachable("bad ownership qualifier!");
3923 }
3924
3925 // Otherwise, it returns a pointer into the exception object.
3926
3927 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3928 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3929
3930 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
John McCall7f416cc2015-09-08 08:05:57 +00003931 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003932 switch (TEK) {
3933 case TEK_Complex:
3934 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3935 /*init*/ true);
3936 return;
3937 case TEK_Scalar: {
3938 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3939 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3940 return;
3941 }
3942 case TEK_Aggregate:
3943 llvm_unreachable("evaluation kind filtered out!");
3944 }
3945 llvm_unreachable("bad evaluation kind");
3946 }
3947
3948 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCall7f416cc2015-09-08 08:05:57 +00003949 auto catchRD = CatchType->getAsCXXRecordDecl();
3950 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003951
3952 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3953
3954 // Check for a copy expression. If we don't have a copy expression,
3955 // that means a trivial copy is okay.
3956 const Expr *copyExpr = CatchParam.getInit();
3957 if (!copyExpr) {
3958 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCall7f416cc2015-09-08 08:05:57 +00003959 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3960 caughtExnAlignment);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00003961 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
3962 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
Richard Smithe78fac52018-04-05 20:52:58 +00003963 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003964 return;
3965 }
3966
3967 // We have to call __cxa_get_exception_ptr to get the adjusted
3968 // pointer before copying.
3969 llvm::CallInst *rawAdjustedExn =
3970 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3971
3972 // Cast that to the appropriate type.
John McCall7f416cc2015-09-08 08:05:57 +00003973 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3974 caughtExnAlignment);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003975
3976 // The copy expression is defined in terms of an OpaqueValueExpr.
3977 // Find it and map it to the adjusted expression.
3978 CodeGenFunction::OpaqueValueMapping
3979 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3980 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3981
3982 // Call the copy ctor in a terminate scope.
3983 CGF.EHStack.pushTerminate();
3984
3985 // Perform the copy construction.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003986 CGF.EmitAggExpr(copyExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003987 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003988 AggValueSlot::IsNotDestructed,
3989 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003990 AggValueSlot::IsNotAliased,
3991 AggValueSlot::DoesNotOverlap));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00003992
3993 // Leave the terminate scope.
3994 CGF.EHStack.popTerminate();
3995
3996 // Undo the opaque value mapping.
3997 opaque.pop();
3998
3999 // Finally we can call __cxa_begin_catch.
4000 CallBeginCatch(CGF, Exn, true);
4001}
4002
4003/// Begins a catch statement by initializing the catch variable and
4004/// calling __cxa_begin_catch.
4005void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
4006 const CXXCatchStmt *S) {
4007 // We have to be very careful with the ordering of cleanups here:
4008 // C++ [except.throw]p4:
4009 // The destruction [of the exception temporary] occurs
4010 // immediately after the destruction of the object declared in
4011 // the exception-declaration in the handler.
4012 //
4013 // So the precise ordering is:
4014 // 1. Construct catch variable.
4015 // 2. __cxa_begin_catch
4016 // 3. Enter __cxa_end_catch cleanup
4017 // 4. Enter dtor cleanup
4018 //
4019 // We do this by using a slightly abnormal initialization process.
4020 // Delegation sequence:
4021 // - ExitCXXTryStmt opens a RunCleanupsScope
4022 // - EmitAutoVarAlloca creates the variable and debug info
4023 // - InitCatchParam initializes the variable from the exception
4024 // - CallBeginCatch calls __cxa_begin_catch
4025 // - CallBeginCatch enters the __cxa_end_catch cleanup
4026 // - EmitAutoVarCleanups enters the variable destructor cleanup
4027 // - EmitCXXTryStmt emits the code for the catch body
4028 // - EmitCXXTryStmt close the RunCleanupsScope
4029
4030 VarDecl *CatchParam = S->getExceptionDecl();
4031 if (!CatchParam) {
4032 llvm::Value *Exn = CGF.getExceptionFromSlot();
4033 CallBeginCatch(CGF, Exn, true);
4034 return;
4035 }
4036
4037 // Emit the local.
4038 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
4039 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
4040 CGF.EmitAutoVarCleanups(var);
4041}
4042
4043/// Get or define the following function:
4044/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
4045/// This code is used only in C++.
4046static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
4047 llvm::FunctionType *fnTy =
4048 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Reid Klecknerde864822017-03-21 16:57:30 +00004049 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
4050 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004051
4052 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
4053 if (fn && fn->empty()) {
4054 fn->setDoesNotThrow();
4055 fn->setDoesNotReturn();
4056
4057 // What we really want is to massively penalize inlining without
4058 // forbidding it completely. The difference between that and
4059 // 'noinline' is negligible.
4060 fn->addFnAttr(llvm::Attribute::NoInline);
4061
4062 // Allow this function to be shared across translation units, but
4063 // we don't want it to turn into an exported symbol.
4064 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
4065 fn->setVisibility(llvm::Function::HiddenVisibility);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004066 if (CGM.supportsCOMDAT())
4067 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004068
4069 // Set up the function.
4070 llvm::BasicBlock *entry =
4071 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
John McCall7f416cc2015-09-08 08:05:57 +00004072 CGBuilderTy builder(CGM, entry);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004073
4074 // Pull the exception pointer out of the parameter list.
4075 llvm::Value *exn = &*fn->arg_begin();
4076
4077 // Call __cxa_begin_catch(exn).
4078 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
4079 catchCall->setDoesNotThrow();
4080 catchCall->setCallingConv(CGM.getRuntimeCC());
4081
4082 // Call std::terminate().
David Blaikie4ba525b2015-07-14 17:27:39 +00004083 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00004084 termCall->setDoesNotThrow();
4085 termCall->setDoesNotReturn();
4086 termCall->setCallingConv(CGM.getRuntimeCC());
4087
4088 // std::terminate cannot return.
4089 builder.CreateUnreachable();
4090 }
4091
4092 return fnRef;
4093}
4094
4095llvm::CallInst *
4096ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
4097 llvm::Value *Exn) {
4098 // In C++, we want to call __cxa_begin_catch() before terminating.
4099 if (Exn) {
4100 assert(CGF.CGM.getLangOpts().CPlusPlus);
4101 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
4102 }
4103 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
4104}
Peter Collingbourne60108802017-12-13 21:53:04 +00004105
4106std::pair<llvm::Value *, const CXXRecordDecl *>
4107ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4108 const CXXRecordDecl *RD) {
4109 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4110}